首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >安卓:如何移动BitmapDrawable?

安卓:如何移动BitmapDrawable?
EN

Stack Overflow用户
提问于 2011-03-11 16:33:38
回答 1查看 6.8K关注 0票数 6

我正在尝试在自定义视图中移动BitmapDrawable。它可以很好地与ShapeDrawable配合使用,如下所示:

代码语言:javascript
复制
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来重现问题:

代码语言:javascript
复制
public MyView() {
    image = getResources().getDrawable(R.drawable.image);
    image.setBounds(0, 0, 100, 100);
}

如何移动BitmapDrawable

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2011-03-11 17:15:17

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

您也不应该更改此方法返回的对象,因为它可能与存储在drawable中的对象相同。

这不是很清楚,但看起来我们不能改变getBounds()返回的值,它会引发一些令人讨厌的副作用。

通过使用copyBounds()和setBounds(),它的工作方式非常出色。

代码语言:javascript
复制
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();
}

移动可绘制的另一种方法是将Canvas移动到您正在绘制的位置:

代码语言:javascript
复制
@Override
protected void onDraw(Canvas canvas) {
    canvas.translate(x, y);
    image.draw(canvas);
}
票数 11
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/5270639

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档