下面的代码实现了这种Canvas
方式。高效且无OOM。您只需要将您的轨迹更改为一个Path
对象。
public class TestView extends View {
private Path path;
private Paint pathPaint;
private Paint dotPaint;
private long beginTime;
private long duration = 3000;
private float dotRadius = 3;
private PathMeasure pm;
public TestView(Context context) {
super(context);
init();
}
public TestView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public TestView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
private void init() {
path = new Path();
path.moveTo(0, 100);
path.lineTo(100, 200);
path.lineTo(200, 50);
//TODO: Put your path here
pm = new PathMeasure(path, false);
pathPaint = new Paint();
pathPaint.setARGB(255, 0, 0, 0);
pathPaint.setStrokeWidth(2);
pathPaint.setStyle(Paint.Style.STROKE);
dotPaint = new Paint();
dotPaint.setARGB(255, 255, 255, 255);
dotPaint.setStyle(Paint.Style.FILL);
beginTime = 0;
}
@Override
protected void onDraw(Canvas canvas) {
canvas.drawARGB(0, 0, 0, 0);
canvas.drawPath(path, pathPaint);
long currentTime = System.currentTimeMillis();
float currentDistance;
if (beginTime == 0) {
beginTime = currentTime;
currentDistance = 0;
} else if (beginTime > 0 && currentTime - beginTime < duration) {
currentDistance = (float) (currentTime - beginTime) / (float) duration * pm.getLength();
} else {
beginTime = -1;
return;
}
float pos[] = new float[2];
pm.getPosTan(currentDistance, pos, null);
canvas.drawCircle(pos[0], pos[1], dotRadius, dotPaint);
invalidate();
}
}