0

我在绘制一个简单的 alpha 动画时遇到了问题。下面你有一个说明问题的测试项目。

持有 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;
}

}

自定义视图

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);
}
}

活动

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();
        }
    });

}

}

如果我不在 animateDrawable 中调用 postnvalidate() ,那么就没有动画。看到其他示例(不完整)似乎只能通过使用动画器来为形状绘制动画,无需在视图中手动调用 postInvalidate() ...

那么,我的理解是否正确,我是否需要自己使整个视图无效?如果是这样的话,整个视图会被“重绘”还是只是脏区?

谢谢

4

0 回答 0