安卓文字描边

tech2023-12-23  84

有个需求,要为指定文字描边,于是就写了个小东西,大家可以扩展着用 原理就是在后面创建一个一摸一样的textview,然后后面的textview只绘制边框。 代码如下:

import android.content.Context import android.graphics.Canvas import android.graphics.Color import android.graphics.Paint import android.graphics.Typeface import android.util.AttributeSet import android.view.ViewGroup import androidx.appcompat.widget.AppCompatTextView import com.damailab.camera.utils.DisplayUtil /** * Created by Mafanwei on 2020/9/3. */ open class StrokeTextView : AppCompatTextView { private val outLineTextView: AppCompatTextView private var outLineColor = "#FFEECB" constructor(context: Context) : super(context) { outLineTextView = AppCompatTextView(context) init() } constructor(context: Context, attrs: AttributeSet? = null) : super(context, attrs) { outLineTextView = AppCompatTextView(context, attrs) init() } constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0) : super(context, attrs, defStyleAttr) { outLineTextView = AppCompatTextView(context, attrs, defStyleAttr) init() } private fun init() { val paint = outLineTextView.paint paint.strokeWidth = 10f paint.style = Paint.Style.STROKE outLineTextView.setTextColor(Color.parseColor(outLineColor)) outLineTextView.gravity = gravity } override fun setLayoutParams(params: ViewGroup.LayoutParams?) { super.setLayoutParams(params) outLineTextView.layoutParams = params } fun setOutLineTextViewFont(typeface: Typeface) { outLineTextView.typeface = typeface } fun setOutLineColor(colorString: String) { outLineColor = colorString outLineTextView.setTextColor(Color.parseColor(outLineColor)) } fun setStrokeWidth(width: Float) { val paint = outLineTextView.paint paint.strokeWidth = width } override fun setTextSize(size: Float) { super.setTextSize(size) outLineTextView.textSize = size } override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { super.onMeasure(widthMeasureSpec, heightMeasureSpec) val outLineText = outLineTextView.text if (outLineText == null || outLineText != this.text) { outLineTextView.text = this.text postInvalidate() } outLineTextView.measure(widthMeasureSpec, heightMeasureSpec) } override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int) { super.onLayout(changed, left, top, right, bottom) outLineTextView.layout(left, top, right, bottom) } override fun onDraw(canvas: Canvas?) { outLineTextView.draw(canvas) super.onDraw(canvas) } }

使用和textview完全一样,如果要自定义字体,需要调用

setOutLineTextViewFont

才能使内外text字体一致。 调用

setStrokeWidth

设置描边粗细

调用

setOutLineColor

设置边框颜色

最新回复(0)