旋转位图会导致OutOfMemoryException异常 [英] Rotating bitmap causes outOfMemoryException
问题描述
我旋转一个位图这样一来,每个按钮点击图片旋转90度
I am rotating a bitmap this way, on every button click the image rotates 90 degrees
Matrix matrix = new Matrix();
matrix.postRotate(90);
rotated = Bitmap.createBitmap(rotated, 0, 0,
rotated.getWidth(), rotated.getHeight(), matrix, true);
iv.setImageBitmap(rotated);
我想这与大量的图片,但现在之一导致OutOfMemoryError异常。有没有一种方法,以prevent呢?当然,我可以叫循环,但后来我失去了位图,必须从ImageView的再次获取。我不认为,这将使任何区别。
I tried this with a lot of images, but now one caused an OutOfMemoryError. Is there a way to prevent this? Of course I can call recycle, but then I lose the bitmap and have to get it again from the imageview. I don't think that will make any difference.
推荐答案
我有建议给你。
1)如果您有任何内存饥饿的任务,方法和可能的话使用带有的AsyncTask
。
2)声明对象为的WeakReference
。这会给你机会,使用后释放内存。参见下面的例子。
1) When you have any memory hunger task, use in methods and if possible with AsyncTask
.
2) Declare objects as WeakReference
. This will give you chance to release memory after use. See below example.
public class RotateTask extends AsyncTask<Void, Void, Bitmap> {
private WeakReference<ImageView> imgInputView;
private WeakReference<Bitmap> rotateBitmap;
public RotateTask(ImageView imgInputView){
this.imgInputView = new WeakReference<ImageView>(imgInputView);
}
@Override
protected void onPreExecute() {
//if you want to show progress dialog
}
@Override
protected Bitmap doInBackground(Void... params) {
Matrix matrix = new Matrix();
matrix.postRotate(90);
rotateBitmap = new WeakReference<Bitmap>(Bitmap.createBitmap(rotated, 0, 0,rotated.getWidth(), rotated.getHeight(), matrix, true));
return rotateBitmap.get();
}
@Override
protected void onPostExecute(Bitmap result) {
//dismiss progress dialog
imgInputView.get().setImageBitmap(result);
}
}
该任务有各方面的意见和对象的WeakReference
。当这项任务完成后,所有使用该任务的记忆是免费的。试试这个办法。我用我的应用程序。
This task has all the views and object as WeakReference
. When this task is completed, all the memory used by this Task is free. Try this approach. I used in my application.
这篇关于旋转位图会导致OutOfMemoryException异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!