I’ve made this fairly simple View. It’s supposed to animate a red line that travels from left to right over a period of time (DURATION). It should update it’s position every DELAY, so that you can adjust the animation to be more smoother if you would want that. It should be noted that I’m testing this on the emulator. Well, if I increase DELAY then the animation finishes faster, even though it should have no effect on the total animation time. Am I simply animating too fast, hogging all the resources? Or is my math off?
public class AnimView extends View {
// Animation duration in milliseconds
private static final int DURATION = 4000;
// Update frame every delay (in milliseconds)
private static final int DELAY = 10;
private int pos;
private long lastTick;
private Paint paint;
public AnimView(Context context, AttributeSet attrs) {
super(context, attrs);
pos = 0;
lastTick = 0;
paint = new Paint();
paint.setColor(Color.RED);
}
@Override
protected void onDraw(Canvas canvas) {
if(System.currentTimeMillis() - lastTick >= DELAY) {
// Calculate a new position for the line
pos += (int) (((double) DELAY / DURATION) * getWidth());
lastTick = System.currentTimeMillis();
}
canvas.drawRect(pos, 0, pos + 1, getHeight(), paint);
if(pos < getWidth()) {
// Position is still below getWidth, keep animating
postInvalidate();
}
}
}
You should be updating lastTick in the if statement:
Otherwise you will draw each time after DELAY passes. So when you increase DELAY, less drawing happens and so the program finishes faster.