效果图:
view分析:UI给到的图有一个渐变的大背景、第二进度条、当前进度条、当前进度条上的斜线、小圆
开始自定义view,后面附完整源码
1.新建HorizontalProgressBar类继承View
class HorizontalProgressBar : View {
constructor(context: Context) : this(context, null)
constructor(context: Context, attributeSet: AttributeSet?) : this(context, attributeSet, 0)
constructor(context: Context, attributeSet: AttributeSet?, defStyleAttr: Int) : super(
context,
attributeSet,
defStyleAttr
) {
}
}
2.自定义属性
<declare-styleable name="HorizontalProgressBar">
<attr name="secondProgressColor" format="color" />
<attr name="hpbProgressStartColor" format="color" />
<attr name="hpbProgressEndColor" format="color" />
<attr name="hpbSmallCircleColor" format="color" />
<attr name="hpbMaxProgress" format="integer" />
<attr name="hpbAnimationDuration" format="integer" />
</declare-styleable>
secondProgressColor:第二进度条颜色 hpbProgressStartColor:渐变开始颜色 hpbProgressEndColor:渐变结束颜色 hpbSmallCircleColor:小圆颜色 hpbMaxProgress:最大进度 hpbAnimationDuration:动画市场 3.获取宽高
override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
super.onSizeChanged(w, h, oldw, oldh)
Log.i(TAG, "w: $w h:$h oldw:$oldw oldh:$oldh")
mWidth = w.toFloat()
mHeight = h.toFloat()
}
4.开始绘制
override fun onDraw(canvas: Canvas?) {
super.onDraw(canvas)
drawOuterBackground(canvas)
drawSecondProgress(canvas)
drawSlash(canvas)
drawProgress(canvas)
drawSmallCircle(canvas)
}
5.代码分析
5.1 最外层背景
/**
*外围背景
*/
private fun drawOuterBackground(canvas: Canvas?) {
paint.apply {
style = Paint.Style.STROKE
strokeWidth = mHeight
//strokeCap 使笔刷两端为半圆形
strokeCap = Paint.Cap.ROUND
//添加渐变颜色
var mShader = LinearGradient(
0f,
0f,
mWidth,
0f,
intArrayOf(Color.parseColor("#FFFFFFFF"), Color.parseColor("#00FFFFFF")),
null,
Shader.TileMode.REPEAT
)