要在Android中使用Kotlin编写一个带描边效果的TextView,可以通过自定义TextView类,并在onDraw方法中添加描边效果。下面是一个示例代码,演示如何创建一个带描边效果的TextView:
1.创建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
// 保存当前文本画笔的状态
val currentTextColor = currentTextColor
// 设置描边效果
paint.style = Paint.Style.STROKE
paint.strokeWidth = strokeWidth
paint.setColor(strokeColor)
canvas.drawText(text, (width - paint.measureText(text)) / 2, baseline.toFloat(), paint)
// 恢复原本的文本画笔
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"/>