日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

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

欄目分類
最近更新