为什么bitmap需要高效加载
因为现在图片的大小都比较大,如果按原尺寸显示的话应用就很可能会出现OOM,因为系统给每个App分的内存空间都不大
加载BitMap的方式
DecodeFile:从文件中加载
DecodeResourece:从应用的资源文件夹中加载
DecodeStream:从流中加载
DecodeByteArray:从字节数组中加载
BitmapFactory.Options的参数
1.inSampleSize参数
当inSampleSize = 1时,即采样后的图片大小为原始大小,当<1时,按1来算,当》1s时,缩放比例为1/(inSampleSize)的二次方
如:102410244 = 4M,如果inSampleSize=2,那么采样后的图片内存大小为1M
2.inJustDecodeBounds参数
这个参数的作用就是获取图片的宽、高,不加载图片,这样我们就可以提前计算好缩放比了。
流程
1将BitmapFactory.Options的inJustDecodeBounds参数设为true并加载图片。
2从BitmapFactory.Options中取出图片的原始宽高信息,它们对应于outWidth和 outHeight参数。
3根据采样率的规则并结合目标View的所需大小计算出采样率inSampleSize。
4将BitmapFactory.Options的inJustDecodeBounds参数设为false,然后重新加载 图片。
代码实现
public static Bitmap decodeSampledBitmapFromResource(Resources
res, int resId, int reqWidth, int reqHeight){
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
//加载图片
BitmapFactory.decodeResource(res,resId,options);
//计算缩放比
options.inSampleSize = calculateInSampleSize(options,req Height,reqWidth);
//重新加载图片
options.inJustDecodeBounds =false;
return BitmapFactory.decodeResource(res,resId,options);
}
private static int calculateInSampleSize(BitmapFactory.Optio ns options, int reqHeight, int reqWidth) {
int height = options.outHeight;
int width = options.outWidth;
int inSampleSize = 1;
if(height>reqHeight||width>reqWidth){
int halfHeight = height/2;
int halfWidth = width/2;
//计算缩放比,是2的指数
while((halfHeight/inSampleSize)>=reqHeight&&(halfWidth/inSampleSize)>=reqWidth){
inSampleSize*=2;
}
}
return inSampleSize;
}
网友评论