Android Java 实现弯曲的进度条动画:完整代码示例
以下是 Android Java 实现弯曲的进度条动画的完整代码。
首先,在 XML 布局文件中添加一个自定义的 View:
<com.example.customprogress.CustomProgressView
android:id="@+id/custom_progress_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true" />
接着,创建一个 CustomProgressView 类,继承 View,并实现 onDraw 方法:
public class CustomProgressView extends View {
private Paint paint;
private Path path;
private int progress;
public CustomProgressView(Context context) {
super(context);
init();
}
public CustomProgressView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public CustomProgressView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
private void init() {
paint = new Paint();
paint.setColor(Color.BLUE);
paint.setStrokeWidth(10);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeCap(Paint.Cap.ROUND);
path = new Path();
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
int centerX = getWidth() / 2;
int centerY = getHeight() / 2;
int radius = Math.min(centerX, centerY) - 20;
path.reset();
float startAngle = -225;
float sweepAngle = progress * 2.7f;
path.addArc(new RectF(centerX - radius, centerY - radius, centerX + radius, centerY + radius), startAngle, sweepAngle);
canvas.drawPath(path, paint);
}
public void setProgress(int progress) {
this.progress = progress;
invalidate();
}
}
在 init 方法中,我们初始化了画笔和路径对象。在 onDraw 方法中,我们根据当前进度值计算出路径的起始角度和扫描角度,并将其添加到路径中。最后,我们调用 canvas 的 drawPath 方法绘制路径。
最后,在 Activity 中设置进度值,并启动动画:
CustomProgressView customProgressView = findViewById(R.id.custom_progress_view);
ObjectAnimator animator = ObjectAnimator.ofInt(customProgressView, 'progress', 0, 100);
animator.setDuration(3000);
animator.start();
这里我们使用了 ObjectAnimator 对象来设置进度值,并设置了动画时长为 3 秒。最后,调用 start 方法启动动画。
本文详细介绍了如何创建一个弯曲的进度条动画,并提供了完整代码示例。你可以根据自己的需求修改代码,创建出更加丰富的动画效果。
原文地址: https://www.cveoy.top/t/topic/oznG 著作权归作者所有。请勿转载和采集!