Search code examples
androidanimationcanvasobjectanimator

Animating a point on Android canvas


Every time onDraw() is called I am drawing a series of points on the canvas. How do I animate one point so that it changes colour or fades in and out? So essentially goes from orange->red and back or opaque->transparent and back?

I am doing the following:

public void onDraw(Canvas canvas) {
  drawDots();
}

private void drawDots() {
  canvas.drawCircle(xcoord, ycoord, 20, getPaintObj(param));
}

private Paint getPaintObj(int param) {
  if (param % 2 == 0) {
     ObjectAnimator colorFade = ObjectAnimator.ofObject(paintObj, "color", new ArgbEvaluator(), 0xff00ff00, 0xffff0000, 0xff0000ff);
     colorFade.setDuration(2000);
     colorFade.setInterpolator(new LinearInterpolator());
     colorFade.setRepeatCount(ValueAnimator.INFINITE);
     colorFade.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
        @Override
        public void onAnimationUpdate(ValueAnimator animation) {
            invalidate();
        }
     });
     colorFade.start();
    return paintObj;

  } else {
    return otherPaintObj;
  }
}

The problem is that it doesn't animate. It sticks to the first colour (0xff00ff00). What am I doing wrong?


Solution

  • ObjectAnimator doesn't work very well with the canvas as I was trying to animate a circle drawn on the canvas itself. Works better for actual objects (TextView, ImageView, etc.) rather than points drawn on canvases.

    The solution I used is redrawing the canvas every once in a while and modifying the radius of the circle drawn to simulate an animation.