自定义VIew之圆形百分比效果

效果

首先看一下效果

思路

实现很简单,就是通过进度百分比来画一段圆弧:

1.画一个圆形,设置画笔线的宽度
2.画一段圆弧,设置画笔颜色
3.画另外一段圆弧
4.开启线程通过标记切换画圆弧

自定义VIew之圆形百分比效果_第1张图片

public class CirCleView extends View {

    private Paint mPaint;
    private int mCircleWidth;
    private RectF mRect;
    private int mFirstColor;
    private int mSecondColor;

    private boolean mFirstDraw = true;
    private int mProgress = 0;

    public CirCleView(Context context) {
        this(context, null);
    }

    public CirCleView(Context context, AttributeSet attrs) {
        super(context, attrs);

        mFirstColor = Color.GREEN;
        mSecondColor = Color.BLUE;
        mCircleWidth = 30;

        mPaint = new Paint();
        // 设置画笔
        // 消除锯齿
        mPaint.setAntiAlias(true);
        // 设置画笔宽度
        mPaint.setStrokeWidth(mCircleWidth);
        // 设置画笔为空心
        mPaint.setStyle(Paint.Style.STROKE);

        new Thread() {

            @Override
            public void run() {

                mFirstDraw = false;
                while (true) {

                    mProgress++;
                    if (mProgress == 360) {

                        mProgress = 0;
                        mFirstDraw = !mFirstDraw;
                    }
                    postInvalidate();
                    try {
                        Thread.sleep(20);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                }
            }
        }.start();
    }

    @Override
    protected void onDraw(Canvas canvas) {

        // 定义圆弧形状的界限
        // 获取圆心坐标
        int circle = getWidth() / 2;
        Log.d("ch", "circle  " + circle);
        int redius = circle - mCircleWidth / 2;
        if (mRect == null) {

            // 定义圆弧的形状以及大小的界限
            mRect = new RectF(circle - redius, circle - redius, circle + redius, circle + redius);
        }

        if (mFirstDraw) {

            // 画一段狐
            mPaint.setColor(mFirstColor);
            canvas.drawCircle(circle, circle, redius, mPaint);
            mPaint.setColor(mSecondColor);
            canvas.drawArc(mRect, 0, mProgress, false, mPaint);
        } else {

            // 画一段狐
            mPaint.setColor(mSecondColor);
            canvas.drawCircle(circle, circle, redius, mPaint);
            mPaint.setColor(mFirstColor);
            canvas.drawArc(mRect, 0, mProgress, false, mPaint);
        }
    }
}

#

没啥好总结的,还是比较简单,一些细节没有优化,快一点了,睡觉觉!革命尚未成功,同志仍需努力!

你可能感兴趣的:(自定义控件)