这是一位大佬在写代码的过程中的一些思考,希望对大家的学习有帮助。
讲述一个代码随需求而变的过程,曾一度因为既有代码不能满足新的需求而卡壳。在阅读了 Android 源码后茅塞顿开,立马一顿重构。但重构完成之后,我陷入了沉思……
1.纯色进度条
最开始,需求是展示如下进度条:
用自定义 View 画两个圆角矩形就能实现:
class ProgressBar @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0
) :View(context, attrs, defStyleAttr) {
// 背景色
var backgroundColor: String = "#00ff00"
set(value) {
field = value
barPaint.color = Color.parseColor(value)
}
// 进度条色
var progressColor: String = "#0000ff"
set(value) {
field = value
progressPaint.color = Color.parseColor(value)
}
// 内边距
var paddingStart: Float = 0f
set(value) {
field = value.dp
}
var paddingEnd: Float = 0f
set(value) {
field = value.dp
}
var paddingTop: Float = 0f
set(value) {
field = value.dp
}
var paddingBottom: Float = 0f
set(value) {
field = value.dp
}
var padding: Float = 0f
set(value) {
field = value.dp
paddingStart = value
paddingEnd = value
paddingTop = value
paddingBottom = value
}
// 背景圆角
var backgroundRx: Float = 0f
set(value) {
field = value.dp
}
var backgroundRy: Float = 0f
set(value) {
field = value.dp
}
// 进度条圆角
var progressRx: Float = 0f
set(value) {
field = value.dp
}
var progressRy: Float = 0f
set(value) {
field = value.dp
}
// 进度(0-100)
var percentage: Int = 0
// 背景画笔
private var barPaint: Paint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
color = Color.parseColor(backgroundColor)
style = Paint.Style.FILL
}
// 进度条画笔
var progressPaint: Paint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
color = Color.parseColor(progressColor)
style = Paint.Style.FILL
}
// 进度条区域
var progressRectF = RectF()
// 背景区域
private var backgroundRectF = RectF()
override fun onDraw(canvas: Canvas?) {
// 背景撑满整个控件
backgroundRectF.set(0f, 0f, width.toFloat(), height.toFloat())
// 画背景圆角矩形
canvas?.drawRoundRect(backgroundRectF, backgroundRx, backgroundRy, barPaint)
// 画进度条圆角矩形
val foregroundWidth = width * percentage/100F
val foregroundTop = paddingTop
val foregroundRight = foregroundWidth - paddingEnd
val foregroundBottom = height.toFloat() - paddingBottom
val foregroundLeft = paddingStart
progressRectF.set(foregroundLeft, foregroundTop, foregroundRight, foregroundBottom)
canvas?.drawRoundRect(progressRectF, progressRx, progressRy, progressPaint)
}
}
然后就可以像这样构建一个30%的进度条:
ProgressBar(context).apply {
percentage = 30
backgroundRx = 20f
backgroundRy = 20f
backgroundColor = "#e9e9e9"
progressColor = "#ff00ff"
progressRx = 15f
progressRy = 15f
padding = 2f
}
2.渐变进度条
新的需求是渐变色的进度条。只需在绘