Android自定义View,彩色分段进度条~

最近公司项目需求,要做一个可以动态设置所占空间多段颜色百分比的进度条,没找到合适的,需求很简单,代码也很简单,简单记录一下,直接上代码:
 

    private Paint paint;
    private int totalParts = 100; // 总共分成100份
    private List<ColorsBean> colorsBeanList;
    public CustomRectangleView(Context context) {
        super(context);
        init();
    }

    public CustomRectangleView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public CustomRectangleView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        paint = new Paint();
        paint.setStyle(Paint.Style.FILL);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        int width = getWidth(); // 获取View的宽度
        int height = getHeight(); // 获取View的高度

        // 计算每份的宽度
        float partWidth = (float) width / totalParts;

        // 绘制总的长方形
        RectF rect = new RectF(0, 0, width, height);
        //进度条背景色
        paint.setColor(Color.parseColor("#f5f5f5"));
        //画圆角矩形
        canvas.drawRoundRect(rect, 8f,8f,paint);

        // 绘制进度条色彩部分
        if (colorsBeanList != null ){
            for (int i = 0; i < colorsBeanList.size(); i++) {
                ColorsBean bean = colorsBeanList.get(i);
                paint.setColor(bean.getColor());
                RectF redRect = new RectF(bean.getStart() * partWidth, 0,                 
                bean.getEnd() * partWidth, height);
                canvas.drawRect(redRect, paint);
            }
        }


    }

    // 设置进度条色彩部分的起始和结束位置
    public void setSegmentPart(List<ColorsBean> colorsBeans) {
        this.colorsBeanList = colorsBeans;
        invalidate(); // 通知View重新绘制
    }

思路:绘制一个长方形,把长方形宽度分成一百份,按照起止位置的百分比绘制颜色。
 

ColorsBean:

data class ColorsBean(
    var start:Int,
    var end:Int,
    var color:Int,
)

使用:

<com.crb.card.data.view.CustomRectangleView
                android:id="@+id/custom_view_progress"
                android:layout_width="match_parent"
                android:layout_height="@dimen/dp_16"/>
val colorList = arrayListOf<ColorsBean>()
//设置0%-4%为蓝色
colorList.add(ColorsBean(0,4,Color.BLUE))
//设置4%-10%为蓝色
colorList.add(ColorsBean(4,10,Color.RED))
//设置10%-20%为蓝色
colorList.add(ColorsBean(10,20,Color.GREEN))
mBinding.customViewProgress.setSegmentPart(colorList)

根据以上代码可以自行添加动画效果,圆角效果等。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值