簡體   English   中英

Android:如何移動BitmapDrawable?

[英]Android: How to move a BitmapDrawable?

我正在嘗試在自定義視圖中移動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 ,drawable的邊界會發生變化,則會調用onDraw方法,但圖像會保留在屏幕上的位置。

以下構造函數將通過創建BitmapDrawable來重現該問題:

public MyView() {
    image = getResources().getDrawable(R.drawable.image);
    image.setBounds(0, 0, 100, 100);
}

如何移動BitmapDrawable

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();
}

移動Drawable的另一種方法是移動畫布上的畫布

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM