• 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));

  • 相关阅读:
    获得指定目录路径
    播放音乐(mciSendString)
    INotifyPropertyChanged接口
    从excel表格加载数据返回DataSet
    事件与委托
    .net中实现伪静态的学习小结
    今天开通博客了
    EasyUI后台管理系统学习四
    EasyUI后台管理系统学习三
    EasyUI后台管理系统学习二
  • 原文地址:https://www.cnblogs.com/shen-hua/p/6197760.html
Copyright © 2020-2023  润新知