文字在中间的进度条件,主要思路是文字覆盖到一根线上。然后使用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}%"
网友评论