我正在尝试在自定义 View 中移动BitmapDrawable
。可以使用ShapeDrawable
正常工作,如下所示:
public class MyView extends View {
private Drawable image;
public MyView() {
image = new ShapeDrawable(new RectShape());
image.setBounds(0, 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
,则可绘制对象的边界会更改,则会调用onDraw
方法,但图像会保留在屏幕上的位置。以下构造函数将通过创建BitmapDrawable来重现该问题:
public MyView() {
image = getResources().getDrawable(R.drawable.image);
image.setBounds(0, 0, 100, 100);
}
如何移动
BitmapDrawable
? 最佳答案
Drawable.getBounds()的文档表示以下内容:
这还不是很清楚,但看起来一定不能更改 getBounds()返回的值,它会产生一些令人讨厌的副作用。
通过使用 copyBounds()和 setBounds(),它就像一种魅力。
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();
}
移动可绘制的另一种方法是在绘制时将 Canvas 移动:
@Override
protected void onDraw(Canvas canvas) {
canvas.translate(x, y);
image.draw(canvas);
}