Android 自定义View 之 Path PathMeasure (三)之渐变色进度条Progress

本文介绍了一种可调整渐变效果的进度条实现方案,包括初始化画笔、路径设置、绘制渐变过程及动态进度动画的实现方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

可调整渐变的进度条Progress

在这里插入图片描述
如上图所示

需求场景:
  • 进度条
  • 颜色渐变
  • 可静态\可自动
代码解析
  • 初始化背景进度条画笔、前景可渐变进度条画笔
	/**
	初始化背景进度条画笔、前景可渐变进度条画笔
	**/
    private void initView(Context context, AttributeSet attrs) {

        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.ProgressCirce);
        gradientLeftColor = typedArray.getColor(R.styleable.ProgressCirce_gradient_left_color, -1);
        gradientRightColor = typedArray.getColor(R.styleable.ProgressCirce_gradient_right_color, -1);
        normalColor = typedArray.getColor(R.styleable.ProgressCirce_gradient_normal_color, 0xFFF4F4F6);


        backPaint = new Paint();
        backPaint.setStyle(Paint.Style.FILL);
        backPaint.setColor(normalColor);
        backPaint.setAntiAlias(true);


        forPaint = new Paint();
        forPaint.setAntiAlias(true);
        forPaint.setStyle(Paint.Style.FILL);

        typedArray.recycle();

//        forPaint.setColor(Color.RED);
    }

  • 使用path初始化背景进度路径
   @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        forPath = new Path();
        backPath = new Path();
        backPath.addRoundRect(
                getPaddingLeft(),
                getPaddingTop(),
                getMeasuredWidth(),
                getMeasuredHeight(),
                radius, radius, Path.Direction.CCW);


    }
  • 绘制
    通过传入当前的progress 和progressMax(最大值)计算出当前 进度处于width 中什么位置
    得到停止位置stopD ,绘制出前景progress
   forPath.reset();
        canvas.drawPath(backPath, backPaint);

        float stopD = (float) (Math.abs(progress)) / progressMax * getMeasuredWidth();
        forPaint.setShader(getLinearGradient());
        forPath.addRoundRect(
                getPaddingLeft(),
                getPaddingTop(),
                stopD,
                getMeasuredHeight(),
                radius, radius, Path.Direction.CCW);
        if (progress != 1) {
            canvas.drawPath(forPath, forPaint);
        }
  • 线性渐变
    获取线性渐变值,通知传入的color id,设置渐变。

    /**
     * 获取线性渐变
     *
     * @return
     */
    private LinearGradient getLinearGradient() {
        if (linearGradient == null) {
            linearGradient = new LinearGradient(0, 0,
                    getMeasuredWidth(),
                    getMeasuredHeight(),
                    gradientLeftColor,
                    gradientRightColor,
                    Shader.TileMode.CLAMP); //根据R文件中的id获取到color
        }
        return linearGradient;
    }

  • 开启动态progress动画
  /**
     * 开启自动进度动画
     */
    public void startAutoProcessAnimation(final AnimationInterface animationInterface) {
        if (valueAnimator == null) {
            valueAnimator = ValueAnimator.ofInt(0, (int) progressMax);
            valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {


                @Override
                public void onAnimationUpdate(ValueAnimator animation) {
                    setProgress((Integer) animation.getAnimatedValue());
                    if (animationInterface != null) {
                        animationInterface.animationRunning((Integer) animation.getAnimatedValue());
                    }
                }

            });
            valueAnimator.setDuration(2000);
            valueAnimator.setInterpolator(new LinearInterpolator());
            valueAnimator.start();
        }
    }

    /**
     * 停止自动进度动画
     */
    public void stopAutoProcessAnimation() {
        if (valueAnimator != null) {
            valueAnimator.cancel();
            valueAnimator = null;
        }
    }

    public interface AnimationInterface {
        void animationRunning(int progress);

    }
  • 设置静态progress
  /**
     * 设置静态progress
     *
     * @param progress
     */
    public void setProgress(int progress) {
        if (progress > progressMax) {
            this.progress = (int) progressMax;
        } else if (progress <= 0) {
            this.progress = 1;
        } else {
            this.progress = progress;
        }
        invalidate();
    }

至此,可渐变的Progress就完成了。

### Android 环形渐变色进度条 为了实现在Android应用程序中的环形渐变色进度条,可以利用`GradientDrawable`类来定义背景资源文件,并通过自定义View的方式绘制环形进度条。 #### 自定义 View 绘制环形进度条 ```java public class CircleProgress extends View { private Paint paint; private RectF oval; private float startAngle = -90; // 起始角度 private int progress = 0; public CircleProgress(Context context) { super(context); init(); } public CircleProgress(Context context, AttributeSet attrs) { super(context, attrs); init(); } private void init() { paint = new Paint(Paint.ANTI_ALIAS_FLAG); oval = new RectF(); Shader shader = new SweepGradient( getWidth() / 2, getHeight() / 2, new int[]{Color.parseColor("#FF4CAF50"), Color.parseColor("#FF8BC34A")}, null); paint.setShader(shader); paint.setStyle(Paint.Style.STROKE); paint.setStrokeWidth(15); // 设置线条宽度 } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); int center = Math.min(getWidth(), getHeight()) / 2 - 75; oval.set(center, center, getWidth() - center, getHeight() - center); canvas.drawArc(oval, startAngle, ((float)progress / getMaxValue()) * 360, false, paint); } public void setProgress(int value){ this.progress=value; invalidate(); // 刷新界面重新绘制 } } ``` 此代码片段展示了如何创建一个简单的环形进度条并为其添加渐变效果[^1]。需要注意的是,在实际项目中可能还需要处理更多细节如触摸反馈、动画过渡等特性。 ### iOS 环形渐变色进度条 对于iOS平台而言,可以通过组合使用`CAShapeLayer`和`CAGradientLayer`两个核心图形层对象轻松构建出具有视觉吸引力的环形渐变色进度条组件。 #### 使用 CAShapeLayer 和 CAGradientLayer 创建环形进度条 ```swift import UIKit class GradientCircleProgressBar: UIView { let shapeLayer = CAShapeLayer() var gradientLayer:CAGradientLayer! override func layoutSubviews() { super.layoutSubviews() let circularPath = UIBezierPath(arcCenter: CGPoint(x: frame.size.width/2.0, y: frame.size.height/2.0), radius: (frame.size.width - 10)/2, startAngle: -.pi / 2, endAngle: 3 * .pi / 2, clockwise: true) shapeLayer.path = circularPath.cgPath shapeLayer.strokeColor = UIColor.clear.cgColor shapeLayer.lineWidth = 10 shapeLayer.fillColor = UIColor.clear.cgColor shapeLayer.lineCap = .round gradientLayer = CAGradientLayer() gradientLayer.frame = bounds gradientLayer.colors = [ UIColor.systemGreen.cgColor, UIColor.systemYellow.cgColor, UIColor.systemRed.cgColor ] gradientLayer.startPoint = CGPoint(x: 0.5, y: 0) gradientLayer.endPoint = CGPoint(x: 0.5, y: 1) gradientLayer.mask = shapeLayer layer.addSublayer(shapeLayer) layer.insertSublayer(gradientLayer, at: 0) } func updateProgress(_ percent: CGFloat) { CATransaction.begin() CATransaction.setDisableActions(true) shapeLayer.strokeEnd = percent CATransaction.commit() } } ``` 上述Swift代码实现了基于Core Animation框架下的环形渐变色进度指示器[^2]。该控件能够根据传入的比例参数动态调整显示状态,适用于多种场景需求。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值