ShapeDrawable animate alpha property in Custom View

271 Views Asked by At

I'm having trouble with a simple alpha animation of a drawable. Bellow you have a test project which illustrates the problem.

Class that holds a ShapeDrawable

public class CustomDrawable {

public ShapeDrawable shapeDrawable;

public CustomDrawable(int left, int top, int right, int bottom, int color) {
    shapeDrawable = new ShapeDrawable(new RectShape());
    shapeDrawable.setBounds(new Rect(left, top, right, bottom));
    shapeDrawable.getPaint().setStyle(Paint.Style.FILL_AND_STROKE);
    shapeDrawable.getPaint().setColor(Color.BLUE);
}

public ShapeDrawable getShapeDrawable() {
    return shapeDrawable;
}

}

A custom view

public class CustomView extends View {

private CustomDrawable drawable;

public CustomView(Context context, AttributeSet attrs) {
    super(context, attrs);
}

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    drawable.getShapeDrawable().draw(canvas);
}

public void animateDrawable() {
    ValueAnimator va = ValueAnimator.ofInt(255, 0);
    va.setDuration(1000);
    va.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
        int alpha;
        @Override
        public void onAnimationUpdate(ValueAnimator animation) {
            alpha = (int) animation.getAnimatedValue();
            drawable.getShapeDrawable().setAlpha(alpha);
            drawable.getShapeDrawable().getPaint().setAlpha(alpha);

            // This works but invalidates the whole view...
            //postInvalidate();
        }
    });
    va.start();
}

@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
    super.onSizeChanged(w, h, oldw, oldh);
    drawable = new CustomDrawable(0, 0, h/2, w/2, Color.MAGENTA);
}
}

Activity

public class MainActivity extends AppCompatActivity {
private final static String TAG = "MainActivity";
private CustomView customView;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    customView = (CustomView) findViewById(R.id.customView);
    Button fadeOutBtn = (Button) findViewById(R.id.fadeOut);
    fadeOutBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            customView.animateDrawable();
        }
    });

}

}

If I don't call postnvalidate() in animateDrawable then there's no animation. Seeing other examples (non complete) it seems that the shape drawable should be animated only by using an animator, no need to manually call postInvalidate() in the view...

So, is my understanding correct, do I need to invalidate the whole view myself? And if that is the case will the whole view be "repainted" or just the dirty region?

Thanks

0

There are 0 best solutions below