Animating a line moving on a Canvas
<p>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 (<code>DURATION</code>). It should update it's position every <code>DELAY</code>, 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 <code>DELAY</code> 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? </p>

<pre><code>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 &gt;= 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 &lt; getWidth()) {
            // Position is still below getWidth, keep animating
            postInvalidate();
        }

    }

}
</code></pre>
