Android的:如何移动BitmapDrawable? [英] Android: How to move a BitmapDrawable?

查看:193
本文介绍了Android的:如何移动BitmapDrawable?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想自定义视图移动 BitmapDrawable 。它工作正常使用 ShapeDrawable 如下:

I'm trying to move a BitmapDrawable in a custom view. It works fine with a ShapeDrawable as follows:

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 方法被调用,但图像保持它是在屏幕上。

However, if I use a BitmapDrawable, the drawable's bounds change, the onDraw method is called, but the image stays where it is on the screen.

下面的构造将通过创建BitmapDrawable而不是重现该问题:

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

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

我怎样才能移动 BitmapDrawable

推荐答案

对于 Drawable.getBounds()文档说以下内容:

注:为提高效率,返回
  对象可以被存储在相同的对象
  在提拉(尽管这不是
  保证的),所以如果一个持久副本
  是需要界,调用
  copyBounds(矩形)来代替。你应该
  也不会改变由返回的对象
  这种方法,因为它可以是相同的
  对象存储在可绘制的。

Note: for efficiency, the returned object may be the same object stored in the drawable (though this is not guaranteed), so if a persistent copy of the bounds is needed, call copyBounds(rect) instead. You should also not change the object returned by this method as it may be the same object stored in the drawable.

这不是水晶清楚,但看起来我们的不得的getBounds返回变化值(),它触发了一些讨厌的副作用。

This is not cristal clear but it looks like we must not change value returned by getBounds(), it fires some nasty side effects.

通过使用 copyBounds()的setBounds()它的工作原理就像一个魅力。

By using copyBounds() and setBounds() it works like a charm.

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

动的另一种方式的可绘制可能是移动的画布在至极您绘制:

Another way of moving a Drawable could be to move the Canvas on wich you are drawing:

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

这篇关于Android的:如何移动BitmapDrawable?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆