android kotlin 自定义控件换行,多行绘制

自定义控件换行主要依靠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)
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值