【Android】 给我一个Path,还你一个动画View
时间: 2024-03-10 11:44:39 浏览: 122
好的,以下是一个简单的实现:
```java
public class PathAnimationView extends View {
private static final int DEFAULT_DURATION = 2000; // 默认动画时长为2秒
private Path mPath;
private Paint mPaint;
private PathMeasure mPathMeasure;
private float mPathLength;
private ValueAnimator mValueAnimator;
private float mAnimatedValue;
private float[] mPos;
private float[] mTan;
public PathAnimationView(Context context) {
this(context, null);
}
public PathAnimationView(Context context, @Nullable AttributeSet attrs) {
this(context, attrs, 0);
}
public PathAnimationView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
private void init() {
mPaint = new Paint();
mPaint.setColor(Color.RED);
mPaint.setStrokeWidth(5);
mPaint.setStyle(Paint.Style.STROKE);
mPath = new Path();
mPath.addCircle(0, 0, 100, Path.Direction.CW);
mPathMeasure = new PathMeasure(mPath, false);
mPathLength = mPathMeasure.getLength();
mPos = new float[2];
mTan = new float[2];
mValueAnimator = ValueAnimator.ofFloat(0, 1);
mValueAnimator.setDuration(DEFAULT_DURATION);
mValueAnimator.setRepeatCount(ValueAnimator.INFINITE);
mValueAnimator.setInterpolator(new LinearInterpolator());
mValueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
mAnimatedValue = (float) animation.getAnimatedValue();
invalidate();
}
});
}
public void startAnimation() {
mValueAnimator.start();
}
public void stopAnimation() {
mValueAnimator.cancel();
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawColor(Color.WHITE);
float distance = mPathLength * mAnimatedValue;
mPathMeasure.getPosTan(distance, mPos, mTan);
canvas.drawPath(mPath, mPaint);
canvas.drawCircle(mPos[0], mPos[1], 20, mPaint);
}
}
```
使用方法:
```java
PathAnimationView pathAnimationView = new PathAnimationView(context);
addView(pathAnimationView);
pathAnimationView.startAnimation(); // 开始动画
pathAnimationView.stopAnimation(); // 停止动画
```
这是一个简单的 Path 动画,通过 ValueAnimator 来控制动画进度,再根据 PathMeasure 获取路径上的点,最后绘制圆点实现动画效果。你可以根据具体需求修改 Path,以及动画时长等参数。
阅读全文