【问题标题】:Android: How to move a BitmapDrawable?Android:如何移动 BitmapDrawable?
【发布时间】:2011-03-11 08:33:38
【问题描述】:

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

【问题讨论】:

    标签: android animation drawable


    【解决方案1】:

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

    【讨论】:

    • 但是边界呢?为什么它对 ImageDrawable 不起作用,而对 ShapeDrawable 却完美无缺?
    • 我查看了它,并修改了我的答案,解释了它为什么不起作用。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-01
    相关资源
    最近更新 更多