根据用户设置的宽高去绘制一个半径为高度一半的圆角矩形,注意要对padding属性进行处理,这部分就是背景,代码如下:
val halfHeight = height / 2f
val saveCount = canvas.saveLayer(0f, 0f, width.toFloat(), height.toFloat(), null)
// Draw background.
backgroundRectF.left = paddingStart.toFloat()
backgroundRectF.top = paddingTop.toFloat()
backgroundRectF.right = width - paddingEnd.toFloat()
backgroundRectF.bottom = height - paddingBottom.toFloat()
canvas.drawRoundRect(backgroundRectF, halfHeight, halfHeight, backgroundPaint)
在背景圆角矩形的左边绘制另外一个半径为高度一半的圆角矩形,宽高和背景圆角矩形一样,但是左右坐标会随着percent的增加而增加,绘制完毕后的表现就是往右移动,然后利用PorterDuffXfermode处理重叠部分,这部分就是进度,代码如下:
private val progressTextPaint by lazy {
TextPaint().apply {
isAntiAlias = true
isDither = true
style = Paint.Style.FILL
color = progressTextColor
}
}
// Draw progress.
progressRectF.left = -backgroundRectF.width() + percent * width
progressRectF.top = backgroundRectF.top
progressRectF.right = progressRectF.left + backgroundRectF.width()
progressRectF.bottom = backgroundRectF.bottom
canvas.drawRoundRect(progressRectF, halfHeight, halfHeight, progressPaint)
canvas.restoreToCount(saveCount)
根据用户需要绘制一个百分比文本,左右坐标也是随着percent增加而增加,绘制完毕后的表现也是向右移动,不过是位于进度条弧形的左边,注意要准确测量文字的宽高,代码如下:
if (isShowProgressText && percent >= 0.1f) {
progressTextPaint.run {
textSize = halfHeight
fontMetrics.let {
val progress