您的位置:首页 > 移动开发 > Android开发

Android开发艺术探索------Bitmap的高效加载

2015-10-04 20:45 507 查看
Android读书笔记——图片的高效加载

(内容来源于Android开发艺术探索)

为了高效的加载图片  减少内存的占用 在加载图片前 应该事先对图片进行压缩处理。通过BitmapFactory.Options对象来缩放,这里运用到了inSampleSize采样率的概念。
采样率是图片的缩放比例 当其为1时,为原图大小,当其大于1时宽/高为原来的1/inSampleSize,像素大小为1/inSampleSize的2次方的大小。例如:当1张大小为1024X1024像素的图片,假定它的存储格式为ARGB8888 其像素大小为1024x1024x4---4M的大小,当设定它的采样率为2时 其宽高缩小为512X512 像素大小缩小为512x512x4 缩小了4倍。官方同样指出:inSampleSize的大小需要为2的指数。1,2,4,8,16......这类数值,如果不为2的指数,系统会自动向下取整,选取一个最接近的2的指数来代替。例如3 会选择2代替。
获得采样率的步骤


BitmapFactory.Options options = new BitmapFactory.Options();\
options.inJustDecodeBounds = true;
BitmapFactory.decodeResource(res, resId, options);
//计算采样率  得出合适采样率进行缩放
options.inSampleSize = calculateInSampleSize(options,reqWidth,reWheight);

/**
* @param options
* @param reqWidth  需要的宽
* @param reqHeight 需要的高
* @return
*/
private int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
final int height = options.outHeight;
final int width = options.outWidth;
int isSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
final int halfHeight = height / 2;
final int halfWidth = width / 2
while ((halfHeight / isSampleSize) >= reqHeight && (halfWidth / isSampleSize) >= reqWidth) {
isSampleSize*=2;
}
}
return isSampleSize;
}


1、BitmapFactory.Options获得原bitmap中的一些参数

inJustDecodeBounds==true时 代表只解析图片宽高值,并不加载图片大小。

2、通过options对象 的outWidth/outHeight方法得到原图的宽高数据

3、计算采样率

4、将inJustDecodeBounds==false
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  读书笔记 android