Android:如何移动BitmapDrawable?

fut*_*lib 6 animation android drawable

我正试图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();
    }
}
Run Code Online (Sandbox Code Playgroud)

但是,如果我使用a BitmapDrawable,drawable的边界会发生变化,onDraw则会调用该方法,但图像会保留在屏幕上的位置.

以下构造函数将通过创建BitmapDrawable来重现该问题:

public MyView() {
    image = getResources().getDrawable(R.drawable.image);
    image.setBounds(0, 0, 100, 100);
}
Run Code Online (Sandbox Code Playgroud)

我怎么能搬家BitmapDrawable

pca*_*ans 11

Drawable.getBounds()的文档说明如下:

注意:为了提高效率,返回的对象可能是存储在drawable中的相同对象(虽然这不保证),因此如果需要边界的持久副本,请调用copyBounds(rect).您也不应该更改此方法返回的对象,因为它可能是存储在drawable中的同一对象.

这不是cristal clear,但看起来我们不能改变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();
}
Run Code Online (Sandbox Code Playgroud)

移动Drawable的另一种方法是移动画布上的画布:

@Override
protected void onDraw(Canvas canvas) {
    canvas.translate(x, y);
    image.draw(canvas);
}
Run Code Online (Sandbox Code Playgroud)