回收的ImageView位图位图、ImageView

2023-09-12 01:05:23 作者:那抹微笑已成伤

我有这样的事情:

Bitmap.Config conf = Bitmap.Config.ARGB_8888;
WeakReference<Bitmap> bm = new WeakReference<Bitmap>(Bitmap.createBitmap(3000 + 3000, 2000, conf));

Canvas canvas = new Canvas(bm.get());
canvas.drawBitmap(firstBitmap, 0, 0, null);
canvas.drawBitmap(bm, firstBitmap.getWidth(), 0, null);

imageView.setImageBitmap(bm);

和我将此在其上创建一个接一个超过10的ImageView。 每当我创造新的ImageView,我要回收从第一个的BM的对象,导致此code在那里,使我堆增长越来越多,再抛的OutOfMemoryError ,所以我做的:

And I apply this on more than 10 imageView's which are created one by one. Whenever I create new ImageView, I want to recycle the 'bm' object from the first one, cause this code up there, causes my heap to grow more and more and then throw OutOfMemoryError, so I do:

bm.recycle()

之后我定了位图(BM)的ImageView的对象。 这将导致不同的是,ImageView的画布要吸取回收位图。

right after I set the Bitmap (bm) to the imageView object. This causes exception that the ImageView's canvas wants to draw recycled Bitmap.

什么是回收已被置为图像的ImageView位图的方式?

What is the way to recycle a Bitmap that has already been put as image on ImageView?

Thanksb

推荐答案

在你的onDestroy方法,你可以尝试这样的:

In your onDestroy method you could try something like this:

ImageView imageView = (ImageView)findViewById(R.id.my_image);
Drawable drawable = imageView.getDrawable();
if (drawable instanceof BitmapDrawable) {
    BitmapDrawable bitmapDrawable = (BitmapDrawable) drawable;
    Bitmap bitmap = bitmapDrawable.getBitmap();
    bitmap.recycle();
}

演员应该工作,因为setImageBitmap被实现为

The cast should work since setImageBitmap is implemented as

public void setImageBitmap(Bitmap bm) {
    setImageDrawable(new BitmapDrawable(mContext.getResources(), bm));
}