在自定义View用StaticLayout让文字换行

先上代码吧:

class MyCustomView @JvmOverloads constructor(context: Context?, attrs: AttributeSet? = null, defStyleAttr: Int = 0):View(context, attrs, defStyleAttr) {

    var text = ""
    var textPlaint = TextPaint()
    var size = 50f
    var textColor = Color.BLACK
    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)
        val size = 100 * context.resources.displayMetrics.density.toInt()
        setMeasuredDimension(
            max(suggestedMinimumWidth, resolveSize(size,widthMeasureSpec)),
        max(suggestedMinimumHeight, resolveSize(size,heightMeasureSpec))
        )
    }

    @RequiresApi(Build.VERSION_CODES.M)
    override fun onDraw(canvas: Canvas?) {
        textPlaint.apply {
            this.textSize = size
            this.color = textColor
        }
        val layout = StaticLayout.Builder.obtain(text,0,text.length,textPlaint,textPlaint.measureText(text).toInt()).build()
        layout.draw(canvas)
    }

}

在activity中设置文字:

findViewById(R.id.myCustomView).text = "第一行字\n第二行字"

代码的实现其实很简单,就是让StaticLayout去解释文字中的换行符"\n"。核心就以下这两句:

val layout = StaticLayout.Builder.obtain(text,0,text.length,textPlaint,textPlaint.measureText(text).toInt()).build()
layout.draw(canvas)

效果如下:


Screenshot_1656950107.png

你可能感兴趣的:(在自定义View用StaticLayout让文字换行)