Animate color of Paint object

2019-05-11 17:06发布

问题:

I am trying to animate a Paint object in my custom view between colors. But the animation is not working.

ObjectAnimator colorFade = ObjectAnimator.ofObject(mCirclePaint, "color", new ArgbEvaluator(), getColor(), 0xff000000);
              colorFade.setDuration(1500);
              colorFade.start();

            invalidate();

I have previously set the paints color like this:

mCirclePaint.setColor(Color.RED);

UPDATE I don't think the Handler makes a difference to whether it animated or not. Even without the Handler I cannot animate the paint object.

回答1:

This is the solution I found:

ObjectAnimator    colorFade = ObjectAnimator.ofObject(mCirclePaint, "color", new ArgbEvaluator(), getColor(), mColors[randomNum]);
                  colorFade.setDuration(1500);
                colorFade.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {

                    @Override
                    public void onAnimationUpdate(ValueAnimator animation) {
                        // TODO Auto-generated method stub
                        invalidate();

                    }


                });

                  colorFade.start();


回答2:

try this:

class MyView extends View {
    private Paint mPaint;
    public MyView(Context context) {
        super(context);
        mPaint = new Paint();

        ArgbEvaluator evaluator = new ArgbEvaluator();
        ObjectAnimator animator = ObjectAnimator.ofObject(this, "color", evaluator, 0xffff0000, 0xff00ff00, 0xff0000ff);
        animator.setDuration(6000).start();
    }

    public void setColor(int color) {
        mPaint.setColor(color);
        invalidate();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        canvas.drawPaint(mPaint);
    }
}