要在Android中使用Kotlin編寫一個帶描邊效果的TextView绪穆,可以通過自定義TextView類辨泳,并在onDraw方法中添加描邊效果。下面是一個示例代碼玖院,演示如何創(chuàng)建一個帶描邊效果的TextView:
1.創(chuàng)建TextView自定義類
import android.content.Context
import android.graphics.Canvas
import android.graphics.Paint
import android.util.AttributeSet
import androidx.appcompat.widget.AppCompatTextView
import com.sisyphe.framework.R
/**
* 描邊文字
*/
class OutlinedTextView @JvmOverloads constructor(
context: Context, attrs: AttributeSet? = null
) : AppCompatTextView(context, attrs) {
private var strokeColor: Int = 0xFF000000.toInt() // 描邊顏色菠红,默認為黑色
private var strokeWidth: Float = 4f // 描邊寬度
init {
context.theme.obtainStyledAttributes(
attrs,
R.styleable.OutlinedTextView,
0, 0
).apply {
try {
strokeColor = getColor(R.styleable.OutlinedTextView_strokeColor, strokeColor)
strokeWidth = getDimension(R.styleable.OutlinedTextView_strokeWidth, strokeWidth)
} finally {
recycle()
}
}
}
override fun onDraw(canvas: Canvas) {
val text = text.toString()
val paint = paint
// 保存當(dāng)前文本畫筆的狀態(tài)
val currentTextColor = currentTextColor
// 設(shè)置描邊效果
paint.style = Paint.Style.STROKE
paint.strokeWidth = strokeWidth
paint.setColor(strokeColor)
canvas.drawText(text, (width - paint.measureText(text)) / 2, baseline.toFloat(), paint)
// 恢復(fù)原本的文本畫筆
paint.style = Paint.Style.FILL
paint.setColor(currentTextColor)
canvas.drawText(text, (width - paint.measureText(text)) / 2, baseline.toFloat(), paint)
}
}
2.定義自定義屬性:
在res/values/attrs.xml中定義自定義屬性:
<resources>
<declare-styleable name="OutlinedTextView">
<attr name="strokeColor" format="color" />
<attr name="strokeWidth" format="dimension" />
</declare-styleable>
</resources>
3.在布局文件中使用自定義TextView:
<com.example.customview.OutlinedTextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello, World!"
android:textSize="24sp"
app:strokeColor="@android:color/holo_blue_dark"
app:strokeWidth="2dp"/>