自定义渐变进度条

本文介绍如何在Android中创建一个自定义的渐变进度条,包括详细步骤:从新建HorizontalProgressBar类,定义属性,到逐步绘制背景、第二进度条、当前进度条、斜线和小圆等元素。并提供了完整的源码分析。
摘要由CSDN通过智能技术生成

效果图:

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
            )
          
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

韩~晓强

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值