旋转位图会导致outOfMemoryException

Ray*_*d P 8 android bitmap out-of-memory

我以这种方式旋转位图,在每个按钮上单击图像旋转90度

Matrix matrix = new Matrix();
matrix.postRotate(90);
rotated = Bitmap.createBitmap(rotated, 0, 0,
        rotated.getWidth(), rotated.getHeight(), matrix, true);
iv.setImageBitmap(rotated);
Run Code Online (Sandbox Code Playgroud)

我用很多图像试过这个,但是现在一个引起了OutOfMemoryError.有办法防止这种情况吗?当然我可以调用recycle,但后来我丢失了位图并且必须从imageview再次获取它.我认为这不会有任何区别.

Chi*_*hod 13

我有你的建议.

1)当你有任何记忆饥饿任务时,请使用方法,如果可能的话AsyncTask.
2)将对象声明为WeakReference.这将使您有机会在使用后释放内存.见下面的例子.

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

此任务具有所有视图和对象WeakReference.完成此任务后,此任务使用的所有内存都是空闲的.试试这种方法.我在我的申请中使用过.