Android: How to move BitmapDrawable?

I am trying to move BitmapDrawableto a custom view. It works fine with the ShapeDrawablefollowing:

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

However, if I use BitmapDrawable, the changeable borders change, the method is called onDraw, but the image remains where it is on the screen.

The following constructor will reproduce the problem by creating BitmapDrawable instead:

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

How can i move BitmapDrawable?

+5
source share
1 answer

The documentation for Drawable.getBounds () states the following:

: ( ), , , copyBounds (rect) . , , , .

, , , 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);
}
+9

All Articles