美文网首页
在自定义View用StaticLayout让文字换行

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

作者: Kyunban | 来源:发表于2022-07-04 00:01 被阅读0次

    先上代码吧:

    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<MyCustomView>(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让文字换行

          本文链接:https://www.haomeiwen.com/subject/wnbjbrtx.html