Android项目中如何优化Bitmap的加载-创新互联

Android项目中如何优化Bitmap的加载?相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。

创新互联公司长期为成百上千家客户提供的网站建设服务,团队从业经验10年,关注不同地域、不同群体,并针对不同对象提供差异化的产品和服务;打造开放共赢平台,与合作伙伴共同营造健康的互联网生态环境。为化隆企业提供专业的网站设计、成都网站设计,化隆网站改版等技术服务。拥有十年丰富建站经验和众多成功案例,为您定制开发。

一 . 高效加载 Bitmap

BitMapFactory 提供了四类方法: decodeFile,decodeResource,decodeStream 和 decodeByteArray 分别用于从文件系统,资源,输入流以及字节数组中加载出一个 Bitmap 对象。

高效加载 Bitmap 很简单,即采用 BitMapFactory.options 来加载所需要尺寸图片。BitMapFactory.options 就可以按照一定的采样率来加载缩小后的图片,将缩小后的图片置于 ImageView 中显示。

通过采样率即可高效的加载图片,遵循如下方式获取采样率:

  1. BitmapFactory.Options 的 inJustDecodeBounds 参数设置为 true 并加载图片
  2. BitmapFactory.Options 中取出图片的原始宽高信息,即对应于 outWidth 和 outHeight 参数
  3. 根据采样率的规则并结合目标 View 的所需大小计算出采样率 inSampleSize
  4. BitmapFactory.Options 的 injustDecodeBounds 参数设置为 false,然后重新加载图片
     

过上述四个步骤,加载出的图片就是最终缩放后的图片,当然也有可能没有缩放。

代码实现如下:

public 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 int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
 if (reqWidth == 0 || reqHeight == 0) {
  return 1;
 }

 // Raw height and width of image
 final int height = options.outHeight;
 final int width = options.outWidth;
 Log.d(TAG, "origin, w= " + width + " h=" + height);
 int inSampleSize = 1;

 if (height > reqHeight || width > reqWidth) {
  final int halfHeight = height / 2;
  final int halfWidth = width / 2;

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

 Log.d(TAG, "sampleSize:" + inSampleSize);
 return inSampleSize;
}

当前标题:Android项目中如何优化Bitmap的加载-创新互联
网址分享:http://myzitong.com/article/dcodeo.html