CircleProgressView

521 阅读3分钟

背景

在网上看到一个效果,虽然很简单,但是做的很漂亮我很喜欢,正好在学习自定义View,于是拿来练练手。来看下效果,直接用的人家的效果图,后面给出连接,不过我做的是个简化版的,毕竟是拿来练手的。

分析View中的元素

  • 背景圆
  • 进度条弧线
  • 进度条头部的圆
  • 中间的进度文字

实现

  • 画一个空心的背景圆,需要圆心坐标、半径和宽度,这个很简单;
  • 绘制进度,需要计算出弧的圆心角度数、起始点、宽度(不能小于背景圆的宽度吧);
  • 进度头的圆是2个,内圆和外圆,圆心位置是关键,需要用到三角函数,也很简单;
  • 中间的文字绘制关键点是确定文字的起始位置;

确定需要的属性

新建res/values/attr.xml,定义如下属性

<declare-styleable name="CircleProgressView">
    <attr name="background_circle_width" format="dimension" />
    <attr name="background_circle_color" format="color" />

    <attr name="progress_width" format="dimension" />
    <attr name="progress_color" format="color" />

    <attr name="progress_percent" format="integer" />

    <attr name="progress_text_size" format="dimension" />
    <attr name="progress_text_color" format="color" />

    <attr name="progress_circle_width" format="dimension"/>
</declare-styleable>

在构造方法中获取定义的属性

private void initAttrs(Context context, AttributeSet attributeSet) {
    TypedArray ta = context.obtainStyledAttributes(attributeSet, R.styleable.CircleProgressView);
    mBackgroundCircleWidth = ta.getDimension(R.styleable.CircleProgressView_background_circle_width, mBackgroundCircleWidth);
    mBackgroundCircleColor = ta.getColor(R.styleable.CircleProgressView_background_circle_color, mBackgroundCircleColor);

    mProgressWidth = ta.getDimension(R.styleable.CircleProgressView_progress_width, mProgressWidth);
    mProgressColor = ta.getColor(R.styleable.CircleProgressView_progress_color, mProgressColor);
    mProgressWidth = Math.max(mBackgroundCircleWidth, mProgressWidth);
    mProgressPercent = ta.getInt(R.styleable.CircleProgressView_progress_percent, 0);

    mProgressTextSize = ta.getDimension(R.styleable.CircleProgressView_progress_text_size, mProgressTextSize);
    mProgressTextColor = ta.getColor(R.styleable.CircleProgressView_progress_text_color, mProgressColor);

    mProgressCircleWidth = ta.getDimension(R.styleable.CircleProgressView_progress_circle_width, mProgressCircleWidth);

    ta.recycle();
}

绘制自然需要画笔,初始化需要的画笔

private void initPaint() {
    mBackgroundCirclePaint = new Paint();
    mBackgroundCirclePaint.setAntiAlias(true);
    mBackgroundCirclePaint.setStyle(Paint.Style.STROKE);
    mBackgroundCirclePaint.setStrokeWidth(mBackgroundCircleWidth);
    mBackgroundCirclePaint.setColor(mBackgroundCircleColor);
    mRect = new RectF();
    ////////////////////////////////////////
    mProgressPaint = new Paint();
    mProgressPaint.setAntiAlias(true);
    mProgressPaint.setStyle(Paint.Style.STROKE);
    mProgressPaint.setStrokeCap(Paint.Cap.ROUND);
    mProgressPaint.setStrokeWidth(mProgressWidth);
    mProgressPaint.setColor(mProgressColor);
    ///////////////////////////////////////
    mProgressCirclePaint = new Paint();
    mProgressCirclePaint.setAntiAlias(true);
    mProgressCirclePaint.setStyle(Paint.Style.STROKE);
    mProgressCirclePaint.setColor(mProgressColor);
    mProgressCirclePaint.setStrokeWidth(mProgressCircleWidth);
    //////////////////////////////////////
    mProgressTextPaint = new Paint();
    mProgressTextPaint.setAntiAlias(true);
    mProgressTextPaint.setFakeBoldText(true);
    mProgressTextPaint.setTextSize(mProgressTextSize);
    mProgressTextPaint.setColor(mProgressTextColor);
    mTextRect = new Rect();
}

确定位置

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);

    int widthMode = MeasureSpec.getMode(widthMeasureSpec);
    int heightMode = MeasureSpec.getMode(heightMeasureSpec);
    if (MeasureSpec.AT_MOST == widthMode || MeasureSpec.AT_MOST == heightMode) {
        ViewGroup.LayoutParams layoutParams = getLayoutParams();
        layoutParams.width = ViewGroup.LayoutParams.MATCH_PARENT;
        layoutParams.height = ViewGroup.LayoutParams.MATCH_PARENT;
        setLayoutParams(layoutParams);
    }
}

确定圆心和半径

@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
    super.onSizeChanged(w, h, oldw, oldh);

    mCenterX = w / 2;
    mCenterY = h / 2;
    mRadius = Math.min(w, h) / 3;
    mRect.set(mCenterX - mRadius, mCenterY - mRadius, mCenterX + mRadius, mCenterY + mRadius);
}

onDraw中进行绘制,注释都写的很清楚了

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    //1.绘制底部的圆
    canvas.drawCircle(mCenterX, mCenterY, mRadius, mBackgroundCirclePaint);
    //2.绘制进度,-180度为起始点
    float mProgressAngel = 360 * mProgressPercent / 100;
    canvas.drawArc(mRect, -180, mProgressAngel, false, mProgressPaint);
    //3.绘制进度圆圈
    if (mProgressPercent > 0 && mProgressPercent < 100) {
        canvas.drawCircle((float) (mCenterX + mRadius * Math.cos((mProgressAngel - 180) / 360 * (2 * Math.PI))), (float) (mCenterY + mRadius * Math.sin((mProgressAngel - 180) / 360 * (2 * Math.PI))), mBackgroundCircleWidth, mProgressCirclePaint);
        canvas.drawCircle((float) (mCenterX + mRadius * Math.cos((mProgressAngel - 180) / 360 * (2 * Math.PI))), (float) (mCenterY + mRadius * Math.sin((mProgressAngel - 180) / 360 * (2 * Math.PI))), mBackgroundCircleWidth / 3, mBackgroundCirclePaint);
    }
    //4.绘制中间的文字
    String mText = mProgressPercent + "%";
    mProgressTextPaint.getTextBounds(mText, 0, mText.length(), mTextRect);
    canvas.drawText(mText, mCenterX - mTextRect.width() / 2, mCenterY + mTextRect.height() / 2, mProgressTextPaint);
}

绘制没有动画,很生硬怎么办?

private void startAnimation() {
    if (mValueAnimator == null) {
        mValueAnimator = new ValueAnimator();
        mValueAnimator.setDuration(400);
        mValueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                mProgressPercent = (int) animation.getAnimatedValue();
                invalidate();
            }

        });
    }
    mValueAnimator.setIntValues(0, mProgressPercent);
    mValueAnimator.start();
}

什么时候调用动画呢?我是在onAttachedToWindow中调用的动画,在onDetachedFromWindow中取消动画

@Override
protected void onDetachedFromWindow() {
    super.onDetachedFromWindow();
    if (mValueAnimator != null) {
        mValueAnimator.cancel();
        mValueAnimator = null;
    }
}

只能在xml中设置进度数据怎么可以?提供个方法吧

public void setProgress(int progress) {
    mProgressPercent = progress;
    startAnimation();
}

怎么使用呢?直接XML中

<com.example.administrator.circleprogressdemo.CircleProgressView
    android:id="@+id/circle_progress_view"
    android:layout_width="200dp"
    android:layout_height="200dp"
    app:background_circle_width="6dp"
    app:progress_circle_width="6dp"
    app:progress_color="#FC7F03"
    app:progress_percent="28"
    app:progress_text_size="16sp"
    app:progress_width="2dp" />


private int progress=0;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    final CircleProgressView mCircleProgressView = (CircleProgressView) findViewById(R.id.circle_progress_view);
    SeekBar seekBar=(SeekBar) findViewById(R.id.seekBar);

    seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            MainActivity.this.progress=progress;
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {

        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
            mCircleProgressView.setProgress(progress);
        }
    });
}

效果

代码和apk下载连接

gitee.com/Android_Wan…

原文连接

www.jianshu.com/p/bfe74a862…