因为API自带的加粗属性不能满足UI的审美,需要自己调整加粗效果
效果展示
代码展示
1.自定义TextView,主要是修改描边宽度以实现加粗效果
@SuppressLint("Recycle")
class BoldTextView @JvmOverloads constructor(
context: Context, attrs: AttributeSet? = null
) : androidx.appcompat.widget.AppCompatTextView(context, attrs) {
/**
* 数值越大,字体越粗,0.0f表示常规画笔的宽度,相当于默认情况
*/
private var mStrokeWidth = 0.8f
init {
//获取xml定义属性
val array = context.obtainStyledAttributes(attrs, R.styleable.BoldTextView, 0, 0)
mStrokeWidth = array.getFloat(R.styleable.BoldTextView_stroke_width, mStrokeWidth)
}
override fun onDraw(canvas: Canvas) {
//获取当前控件的画笔
val paint = paint
//设置画笔的描边宽度值
paint.strokeWidth = mStrokeWidth
paint.style = Paint.Style.FILL_AND_STROKE
super.onDraw(canvas)
}
fun setStrokeWidth(mStrokeWidth: Float) {
this.mStrokeWidth = mStrokeWidth
invalidate()
}
}
2.在xml中使用
<com.zhou.common.view.text.BoldTextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/custom_bold_string"
android:textSize="18sp"
app:stroke_width="0.8"/>
源码地址:GitHub - zhoulei519/MyTest
demo中还有很多其他小工具,欢迎查看