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);

    }
}


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



  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值