Chinaunix首页 | 论坛 | 博客
  • 博客访问: 836834
  • 博文数量: 182
  • 博客积分: 1992
  • 博客等级: 上尉
  • 技术积分: 1766
  • 用 户 组: 普通用户
  • 注册时间: 2010-10-18 11:49
文章分类

全部博文(182)

文章存档

2019年(1)

2016年(5)

2015年(29)

2014年(38)

2013年(21)

2012年(36)

2011年(52)

我的朋友

分类: Android平台

2014-09-27 15:30:54

做android对大图片加载常会出现out of memory,其实在这么小的屏幕上可以不要这么高精度而大的图。下面引用google的android文档中的方法,也是最好的方法了


点击(此处)折叠或打开

  1. public static int calculateInSampleSize(
  2.             BitmapFactory.Options options, int reqWidth, int reqHeight) {
  3.     // Raw height and width of image
  4.     final int height = options.outHeight;
  5.     final int width = options.outWidth;
  6.     int inSampleSize = 1;

  7.     if (height > reqHeight || width > reqWidth) {

  8.         final int halfHeight = height / 2;
  9.         final int halfWidth = width / 2;

  10.         // Calculate the largest inSampleSize value that is a power of 2 and keeps both
  11.         // height and width larger than the requested height and width.
  12.         while ((halfHeight / inSampleSize) > reqHeight
  13.                 && (halfWidth / inSampleSize) > reqWidth) {
  14.             inSampleSize *= 2;
  15.         }
  16.     }

  17.     return inSampleSize;
  18. }

点击(此处)折叠或打开

  1. public static Bitmap decodeSampledBitmapFromResource(Resources res, int resId,
  2.         int reqWidth, int reqHeight) {

  3.     // First decode with inJustDecodeBounds=true to check dimensions
  4.     final BitmapFactory.Options options = new BitmapFactory.Options();
  5.     options.inJustDecodeBounds = true;
  6.     BitmapFactory.decodeResource(res, resId, options);

  7.     // Calculate inSampleSize
  8.     options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);

  9.     // Decode bitmap with inSampleSize set
  10.     options.inJustDecodeBounds = false;
  11.     return BitmapFactory.decodeResource(res, resId, options);
  12. }

当我们的显示面积很小时,其实应该用较大的sample size,加快速度和节约内存。



阅读(737) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~