美文网首页
一天一个丑不垃圾的自定义view,带文字的进度条

一天一个丑不垃圾的自定义view,带文字的进度条

作者: nich | 来源:发表于2022-11-10 14:19 被阅读0次
WechatIMG857.png

文字在中间的进度条件,主要思路是文字覆盖到一根线上。然后使用PorterDuffXfermode处理文字的bitmap去掉线,
看到github上人家是画左右两根线和文字处理办法都可以

val mPaint = Paint(Paint.ANTI_ALIAS_FLAG)

    private var progressCount = 0

    init {
        setLayerType(LAYER_TYPE_SOFTWARE,null)
        mPaint.apply {
            color = Color.BLUE
            strokeWidth = 10f
            textSize = 80f
            isAntiAlias = true
            isDither = true
        }
        val an = ValueAnimator.ofInt(0,100)
        an.duration = 10000
        an.interpolator = AccelerateInterpolator()
        an.addUpdateListener {
             progressCount = it.animatedValue as Int
             invalidate()
        }
        an.start()
    }


    @SuppressLint("DrawAllocation")
    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)
        val lineWidth = width.toFloat()
        canvas.drawLine(0f,height/2f,lineWidth,height/2f,mPaint)
        mPaint.xfermode = PorterDuffXfermode(PorterDuff.Mode.SRC_OVER)
        val bm = drawTextView()
        val textX = (lineWidth - bm.width)/100*progressCount
        canvas.drawBitmap(drawTextView(),textX,height/2f-bm.height/2,mPaint)
        mPaint.xfermode = null
    }

    private fun drawTextView():Bitmap{
        val rect = Rect()
        mPaint.getTextBounds(getProgress(),0,getProgress().length,rect)
        val bm = Bitmap.createBitmap(rect.width(),rect.height(),Bitmap.Config.ARGB_8888)
        val canvas = Canvas(bm)
        val fontMetrics = mPaint.fontMetrics
        val dy = (fontMetrics.bottom - fontMetrics.top) / 2 - fontMetrics.bottom
        val baseLineY = bm.height / 2 + dy
        canvas.drawText(getProgress(),0f,baseLineY,mPaint)
        return bm
    }

    private fun getProgress():String = "${progressCount}%"

相关文章

网友评论

      本文标题:一天一个丑不垃圾的自定义view,带文字的进度条

      本文链接:https://www.haomeiwen.com/subject/lxxatdtx.html