我正在尝试在自定义视图中移动BitmapDrawable.它适用于ShapeDrawable,如下所示:
@H_502_2@public class MyView extends View {
private Drawable image;
public MyView() {
image = new ShapeDrawable(new RectShape());
image.setBounds(0,100,100);
((ShapeDrawable) image).getPaint().setColor(Color.BLACK);
}
@Override
protected void onDraw(Canvas canvas) {
image.draw(canvas);
}
public void move(int x,int y) {
Rect bounds = image.getBounds();
bounds.left += x;
bounds.right += x;
bounds.top += y;
bounds.bottom += y;
invalidate();
}
}
但是,如果我使用BitmapDrawable,drawable的边界会发生变化,则会调用onDraw方法,但图像会保留在屏幕上的位置.
以下构造函数将通过创建BitmapDrawable来重现该问题:
@H_502_2@public MyView() { image = getResources().getDrawable(R.drawable.image); image.setBounds(0,100); }如何移动BitmapDrawable?
解决方法
Drawable.getBounds()的文档说明如下:
Note: for efficiency,the returned
object may be the same object stored
in the drawable (though this is not
guaranteed),so if a persistent copy
of the bounds is needed,call
copyBounds(rect) instead. You should
also not change the object returned by
this method as it may be the same
object stored in the drawable.
这不是cristal clear,但看起来我们不能改变getBounds()返回的值,它会引发一些令人讨厌的副作用.
通过使用copyBounds()和setBounds(),它就像一个魅力.
@H_502_2@public void move(int x,int y) { Rect bounds = image.copyBounds(); bounds.left += x; bounds.right += x; bounds.top += y; bounds.bottom += y; image.setBounds(bounds); invalidate(); }移动Drawable的另一种方法是移动画布上的画布:
@H_502_2@@Override protected void onDraw(Canvas canvas) { canvas.translate(x,y); image.draw(canvas); }