学无先后,达者为师

网站首页 编程语言 正文

Android Canvas - StaticLayout 绘制多行文字

作者:teletian 更新时间: 2022-07-13 编程语言

Canvas.drawText 只能绘制一行文字,文字多了会超出屏幕之外。
要想绘制多行文字,可以使用 StaticLayout。

class CustomView(context: Context?, attrs: AttributeSet?) : View(context, attrs) {

    private val textPaint: TextPaint = TextPaint(Paint.ANTI_ALIAS_FLAG)
    private val staticLayout: StaticLayout by lazy {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            val builder = StaticLayout.Builder.obtain(TEXT, 0, TEXT.length, textPaint, width)
                .setAlignment(Layout.Alignment.ALIGN_NORMAL)
                .setLineSpacing(0f, 1f) // add, multiplier
                .setIncludePad(false)
            builder.build()
        } else {
            StaticLayout(TEXT, textPaint, width, Layout.Alignment.ALIGN_NORMAL, 1.0f, 0f, false)
        }
    }

    init {
        textPaint.color = Color.RED
        textPaint.textSize = 30f
    }

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)
        staticLayout.draw(canvas)
    }

    companion object {
        private const val TEXT =
            "abcdefghigklmnopqrstuvwxyzabcdefghigklmnopqrstuvwxyzabcdefghigklmnopqrstuvwxyz"
    }
}

原文链接:https://blog.csdn.net/tianjf0514/article/details/125609044

栏目分类
最近更新