Android Canvas - StaticLayout 绘制多行文字
Posted teletian
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Android Canvas - StaticLayout 绘制多行文字相关的知识,希望对你有一定的参考价值。
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 绘制多行文字的主要内容,如果未能解决你的问题,请参考以下文章
Android UICanvas 画布 ② ( Canvas 状态栈 | Canvas 状态栈出栈到指定层级 )
canvas.save(Canvas.ALL_SAVE_FLAG)在android 9中不起作用