自定义控件换行主要依靠paint的breakText方法,该方法会根据给定的宽度计算所需要给的字符数,然后通过canvas绘制
代码:
package com.example.opencvapplication
import android.content.Context
import android.graphics.*
import android.util.AttributeSet
import android.util.Log
import android.view.View
import kotlin.math.log
class MyMoreTextView(context: Context?, attrs: AttributeSet?) : View(context, attrs) {
val txtPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
textSize = 20f.dp
color = Color.RED
}
val txt="围殴进行是多少厘米 第三轮的摩尔方面的发 的福克斯的老妇人两条命令癞" +
"蛤蟆同仁们发二零让他们让老公判断句地方更多VS离开" +
"对方十多天了人吗二五欧舒丹法克法克发偶分给客人四点零分敏锐目" +
"光热门动力方面明天给你比哦发哈个人艾迪康功能入口我分割开来交给会让你篇看到v波莫瑞开" +
"花结果肉体你哦对符合v爱的看是否能沃尔夫均为哦怕v才" +
"能把瑞格让你不敢靠近对方v啊OJFIOENGFKLNRGDFKGFNHBFKGLBNDF上帝给你多少的双方的父母定律美容品g"
var tcBitmap: Bitmap = getBitmap(100.dp)
val widths=FloatArray(1)
var metrics = Paint.FontMetrics()
override fun onDraw(canvas: Canvas?) {
super.onDraw(canvas)
//画图片
canvas?.drawBitmap(tcBitmap,(width-tcBitmap.width).toFloat(),50f.dp,txtPaint)
txtPaint.getFontMetrics(metrics)
var allCount=0
//行高
var txtHeight=-metrics.top
var txtWidth=width.toFloat()
while (allCount<txt.length){
val count= txtPaint.breakText(txt,allCount,txt.length,true,txtWidth,widths)
canvas?.drawText(txt,allCount,allCount+count,0f,txtHeight,txtPaint)
allCount+=count
txtHeight+=txtPaint.fontSpacing
if(txtHeight>50f.dp&&txtHeight<50f.dp+tcBitmap.height+txtPaint.fontSpacing){
txtWidth=width-tcBitmap.width.toFloat()
}else{
txtWidth=width.toFloat()
}
}
}
fun getBitmap(width:Int):Bitmap{
val options=BitmapFactory.Options()
options.inJustDecodeBounds=true
BitmapFactory.decodeResource(resources,R.drawable.icon_tx,options)
options.inJustDecodeBounds=false
options.inDensity=options.outWidth
options.inTargetDensity=width
return BitmapFactory.decodeResource(resources,R.drawable.icon_tx,options)
}
}