欢迎访问宙启技术站
智能推送

怎么在android项目中实现一个倒计时动态圈

发布时间:2023-05-18 06:48:20

实现一个倒计时动态圈可以提高应用的用户体验,为用户提供更好的视觉效果。在Android项目中实现一个倒计时动态圈需要用到Canvas画布来绘制,以及ValueAnimator动画来实现圆形的动态效果。

步:定义一个自定义View,继承自View类。

public class CountdownView extends View {
    private int mRadius = 150;    // 圆形半径
    private Paint mPaint;    // 画笔
    private int mProgress = 0;    // 当前进度
    private int mTotalProgress = 100;    // 总进度
    
    public CountdownView(Context context) {
        this(context, null);
    }

    public CountdownView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public CountdownView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initPaint();
    }

    private void initPaint() {
        mPaint = new Paint();
        mPaint.setColor(Color.parseColor("#86C063"));
        mPaint.setStyle(Paint.Style.STROKE);
        mPaint.setStrokeWidth(10);
        mPaint.setAntiAlias(true);
    }

    // 绘制圆形
    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        // 绘制圆弧
        RectF rectF = new RectF(getWidth() / 2 - mRadius, getHeight() / 2 - mRadius, getWidth() / 2 + mRadius, getHeight() / 2 + mRadius);
        canvas.drawArc(rectF, -90, mProgress * 360 / mTotalProgress, false, mPaint);
    }

    // 设置进度
    public void setProgress(int progress) {
        mProgress = progress;
        invalidate();
    }
}

第二步:在布局文件中添加我们所定义的自定义View。

<com.example.countdownview.CountdownView
    android:id="@+id/countdown_view"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"/>

第三步:在Activity中实现倒计时效果,并通过ValueAnimator动画来实现圆形的动态效果。

public class MainActivity extends AppCompatActivity {
    private CountdownView mCountdownView;

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

        mCountdownView = findViewById(R.id.countdown_view);

        ValueAnimator animator = ValueAnimator.ofInt(0, 100);
        animator.setDuration(10000);
        animator.setInterpolator(new DecelerateInterpolator());
        animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                int progress = (int) animation.getAnimatedValue();
                mCountdownView.setProgress(progress);
            }
        });
        animator.start();
    }
}

在此代码中,ValueAnimator.ofInt(0, 100)表示数值从0到100的渐变过程,setDuration(10000)表示动画时长为10秒,setInterpolator(new DecelerateInterpolator())表示动画开始快结束慢的插值器。addUpdateListener监听动画数值的变化,并将变化的数值赋值给自定义View的进度值,再调用invalidate()方法更新绘制。

至此,一个简单的倒计时动态圈就实现了。你可以根据自己的需求来定制颜色、进度值和半径大小,让效果更加炫酷。