zoukankan      html  css  js  c++  java
  • 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));

  • 相关阅读:
    Docker找不到私有nuget服务
    EF中字符串转数字排序
    一个简单的注册页面
    【转】【数据库SQL】SQL查询和替换含有回车,空格,TAB,等
    RGB颜色记录
    javascript中event.keycode
    java基础总结
    面试干货
    jQuery、实例大全
    使用Sql按日期条件查询
  • 原文地址:https://www.cnblogs.com/shen-hua/p/6197760.html
Copyright © 2011-2022 走看看