Android设置图片内存溢出(OOM)问题——Android开发进阶之路6

ImageView设置图片必备常识技术:

Android设备会给每个应用分配16M的内存空间,如果你设置的图片的比较大且同一个页面有多个时,经常会报OOM错误导致程序奔溃。所以在这种情况下我们必须要对设置的图片进行处理:

方法一:简单粗暴点,图片大小调低点。方法可使但是很弱智,当然不推荐使用;

方法二:看代码

public static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
        //Raw height and width of image
        final int height = options.outHeight;
        final int width = options.outWidth;
        int inSampleSize = 1;
        if (height > reqHeight || width > reqWidth) {
            if (width > height) {
                inSampleSize = Math.round((float) height / (float) reqHeight);
            } else {
                inSampleSize
                        = Math.round((float) width
                        / (float) reqWidth);
            }
        }
        return inSampleSize;
    }

 

public static Bitmap decodeSampledBitmapFromResource(Resources res, int resId, int reqWidth, int reqHeight) {
        //First decode with inJustDecodeBounds=true to check dimensions
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeResource(res, resId, options);
        //Calculate inSampleSize
        options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
        //Decode bitmap with inSampleSize set
        options.inJustDecodeBounds = false;
        return BitmapFactory.decodeResource(res, resId, options);
    }

设置图片时只需要:mImageView.setImageBitmap(decodeSampledBitmapFromResource(Context.getResources(), R.mipmap.ic_launchar, 100, 100));

posted @ 2016-12-19 15:45  SiberiaDante  阅读(731)  评论(0编辑  收藏  举报