自定義CircleProgressView

背景

在網上看到一個效果,雖然很簡單,但是做的很漂亮我很喜歡,正好在學習自定義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下載連接

https://gitee.com/Android_Wang/CircleProgressView

原文連接

https://www.jianshu.com/p/bfe74a8620b3

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章