在自定义View用StaticLayout让文字换行
【摘要】
先上代码吧:
class MyCustomView @JvmOverloads constructor(context: Context?, attrs: AttributeSet? = null, d...
先上代码吧:
class MyCustomView @JvmOverloads constructor(context: Context?, attrs: AttributeSet? = null, defStyleAttr: Int = 0):View(context, attrs, defStyleAttr) {
var text = ""
var textPlaint = TextPaint()
var size = 50f
var textColor = Color.BLACK
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec)
val size = 100 * context.resources.displayMetrics.density.toInt()
setMeasuredDimension(
max(suggestedMinimumWidth, resolveSize(size,widthMeasureSpec)),
max(suggestedMinimumHeight, resolveSize(size,heightMeasureSpec))
)
}
@RequiresApi(Build.VERSION_CODES.M)
override fun onDraw(canvas: Canvas?) {
textPlaint.apply {
this.textSize = size
this.color = textColor
}
val layout = StaticLayout.Builder.obtain(text,0,text.length,textPlaint,textPlaint.measureText(text).toInt()).build()
layout.draw(canvas)
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
在activity中设置文字:
findViewById<MyCustomView>(R.id.myCustomView).text = "第一行字\n第二行字"
- 1
代码的实现其实很简单,就是让StaticLayout去解释文字中的换行符"\n"。核心就以下这两句:
val layout = StaticLayout.Builder.obtain(text,0,text.length,textPlaint,textPlaint.measureText(text).toInt()).build()
layout.draw(canvas)
- 1
- 2
效果如下:
文章来源: blog.csdn.net,作者:WongKyunban,版权归原作者所有,如需转载,请联系作者。
原文链接:blog.csdn.net/weixin_40763897/article/details/125610970
【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)