Android模仿圆形圆圈倒计时实现

现在看到很多App的开屏图都是画一个圆圈,从0度画到360度,然后倒计时三秒。感觉挺好玩,刚才忍不住写了一个,贴一下代码:

/**
 * weichenglin create in 17/1/25
 */
public class CountDownCircleView extends TextView {
    private static final int COUNT = 3;
    final float PADDING = dip2px(1f);
    Paint mPaint = new Paint();
    float mAngel = 0f;
    private volatile int countDownMilli = 0;
    private Timer mTimer;
    private ValueAnimator mValueAnimator;

    public CountDownCircleView(Context context) {
        super(context);
        init();
    }

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

    public static int dip2px(float dip) {
        return (int) TypedValue.applyDimension(
                TypedValue.COMPLEX_UNIT_DIP, dip, MyApplication.getApplication().getResources().getDisplayMetrics()
        );
    }

    private void init() {
        mPaint.setColor(Color.RED);
        mPaint.setAntiAlias(true);
        mPaint.setStrokeWidth(MyUtils.dip2px(1f));
        mPaint.setStyle(Paint.Style.STROKE);
    }

    public void start() {
        countDownMilli = COUNT + 1;
        mAngel = 0f;
        if (mTimer != null) {
            mTimer.cancel();
        }
        if (mValueAnimator != null) {
            mValueAnimator.cancel();
        }

        mValueAnimator = ValueAnimator.ofFloat(0f, 360f);
        mValueAnimator.setDuration(COUNT * 1000);
        mValueAnimator.setInterpolator(new LinearInterpolator());
        mValueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                mAngel = (Float) animation.getAnimatedValue();
                invalidate();
            }
        });

        mValueAnimator.start();


        mTimer = new Timer();
        mTimer.scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
                countDownMilli--;
                ((Activity) getContext()).runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        setText(countDownMilli + "");
                    }
                });

                if (countDownMilli == 0) {
                    mTimer.cancel();
                }

            }
        }, 0, 1000);
    }


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

        RectF rectF = new RectF(PADDING, PADDING, getWidth() - PADDING, getHeight() - PADDING);
        canvas.drawArc(rectF, 0f, mAngel, false, mPaint);

    }
}


如果你觉得帮到了你,请给作者打赏一口饭吃:



你可能感兴趣的:(Android模仿圆形圆圈倒计时实现)