美文网首页
Android Canvas - StaticLayout 绘制

Android Canvas - StaticLayout 绘制

作者: teletian | 来源:发表于2022-07-04 21:26 被阅读0次

    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"
        }
    }
    

    相关文章

      网友评论

          本文标题:Android Canvas - StaticLayout 绘制

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