您可以使用ObjectAnimator类来回调
每当您想绘制更多的路径时,就调用您的类方法之一。
import android.animation.ObjectAnimator;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.DashPathEffect;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PathEffect;
import android.graphics.PathMeasure;
import android.util.AttributeSet;
import android.view.View;
import android.util.Log;
public class PathView extends View
{
Path path;
Paint paint;
float length;
public PathView(Context context)
{
super(context);
}
public PathView(Context context, AttributeSet attrs)
{
super(context, attrs);
}
public PathView(Context context, AttributeSet attrs, int defStyleAttr)
{
super(context, attrs, defStyleAttr);
}
public void init()
{
paint = new Paint();
paint.setColor(Color.BLUE);
paint.setStrokeWidth(10);
paint.setStyle(Paint.Style.STROKE);
path = new Path();
path.moveTo(50, 50);
path.lineTo(50, 500);
path.lineTo(200, 500);
path.lineTo(200, 300);
path.lineTo(350, 300);
// Measure the path
PathMeasure measure = new PathMeasure(path, false);
length = measure.getLength();
float[] intervals = new float[]{length, length};
ObjectAnimator animator = ObjectAnimator.ofFloat(PathView.this, "phase", 1.0f, 0.0f);
animator.setDuration(3000);
animator.start();
}
//is called by animtor object
public void setPhase(float phase)
{
Log.d("pathview","setPhase called with:" + String.valueOf(phase));
paint.setPathEffect(createPathEffect(length, phase, 0.0f));
invalidate();//will calll onDraw
}
private static PathEffect createPathEffect(float pathLength, float phase, float offset)
{
return new DashPathEffect(new float[] { pathLength, pathLength },
Math.max(phase * pathLength, offset));
}
@Override
public void onDraw(Canvas c)
{
super.onDraw(c);
c.drawPath(path, paint);
}
}
然后,只需调用 init() 来开始动画,如下所示(或者如果您希望它在视图膨胀后立即启动,请将 init() 调用放在构造函数中):
PathView path_view = (PathView) root_view.findViewById(R.id.path);
path_view.init();
另请参阅这个问题here https://stackoverflow.com/questions/24790936/weird-flickering-with-dashpatheffect-animation, and
使用值动画示例 https://stackoverflow.com/questions/18616035/how-to-animate-a-path-on-canvas-android
参考文献1 http://www.curious-creature.org/2013/12/21/android-recipe-4-path-tracing/
参考2 https://stackoverflow.com/questions/5367950/android-drawing-an-animated-line
参考文献3 https://stackoverflow.com/questions/47220112/drawing-multiple-lines-on-canvas-with-delay-in-between