Android Canvas - StaticLayout 绘制
2022-07-04 本文已影响0人
teletian
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"
}
}