我正在尝试在自定义视图中移动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
发布于 2011-03-11 17:15:17
Drawable.getBounds()的文档说明如下:
您也不应该更改此方法返回的对象,因为它可能与存储在drawable中的对象相同。
这不是很清楚,但看起来我们不能改变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);
}
https://stackoverflow.com/questions/5270639
复制相似问题