android – 旋转位图导致outOfMemoryException

前端之家收集整理的这篇文章主要介绍了android – 旋转位图导致outOfMemoryException前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我以这种方式旋转位图,在每个按钮上单击图像旋转90度
Matrix matrix = new Matrix();
matrix.postRotate(90);
rotated = Bitmap.createBitmap(rotated,rotated.getWidth(),rotated.getHeight(),matrix,true);
iv.setImageBitmap(rotated);

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

解决方法

我有你的建议.

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,true));
        return rotateBitmap.get();
    }

    @Override
    protected void onPostExecute(Bitmap result) {
        //dismiss progress dialog
        imgInputView.get().setImageBitmap(result);
    }
}

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

原文链接:https://www.f2er.com/android/317062.html

猜你在找的Android相关文章