Android中由于设置的背景图片太大可能会导致OOM

例如mImageView.setImageBitmap();

布局文件中

android:background="@drawable/xxx.jpg"

下面提供其中的一种处理方式:

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);        }        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) {                // Calculate ratios of height and width to requested height and width                final int heightRatio = Math.round((float) height / (float) reqHeight);                final int widthRatio = Math.round((float) width / (float) reqWidth);                // Choose the smallest ratio as inSampleSize value, this will guarantee                // a final image with both dimensions larger than or equal to the                // requested height and width.                inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;            }            return inSampleSize;        }

通过在代码中对所需要加载的图片进行处理,得到的bitmap设置到控件上即可。

更多相关文章

  1. 指纹支付相关的细节处理
  2. 【转】Android字体小结
  3. View有关基础
  4. ListView点击效果设置
  5. android 输入法弹出 标题栏不被顶出去
  6. Android的Menu
  7. VMware虚拟机Ubuntu1804编译Android(安卓)10.0
  8. Android设置Settings实现:PreferenceActivity【1】
  9. Android屏幕相关设置

随机推荐

  1. Android测试方法总结汇总
  2. Android(安卓)Scroll详解(三):Android(安
  3. Android程序结构
  4. Android项目源码混淆问题解决方法
  5. android 优秀开源项目收集
  6. android中WebView的简单使用
  7. Android微信登录
  8. Android内核开发:学会分析系统的启动log
  9. 为android开放类增加自定义成员方法
  10. Android菜鸟的成长笔记(6)——剖析源码学自