我希望在我的活动中有一个动画图像: 只是一个在轨迹上移动的白色圆圈(黑线)。
最好的方法是什么?
实施可能是:
到目前为止,我尝试了一个FrameAnimation,但是我只得到10个帧的outOfMemoryError。
答案 0 :(得分:0)
以下代码实现了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();
}
}