Android:如何移动BitmapDrawable?

6

我正在尝试在自定义视图中移动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
1个回答

11

Drawable.getBounds()的文档如下:

注意:为了提高效率,返回的对象可能是存储在drawable中的同一对象(尽管不能保证),所以如果需要持久副本的边界,请调用copyBounds(rect)。您也不应更改此方法返回的对象,因为它可能是存储在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();
}

移动Drawable的另一种方法是移动您正在绘制的Canvas

@Override
protected void onDraw(Canvas canvas) {
    canvas.translate(x, y);
    image.draw(canvas);
}

但是边界呢?为什么它对于ShapeDrawable运行得非常好,而对于ImageDrawable却不起作用? - futlib
我仔细研究了一下,并修改了我的答案,解释了为什么它不起作用。 - pcans

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接