您的位置:首页 > 其它

BitMap的高效加载

2017-04-01 22:23 204 查看

BitmapFactory类提供四种方法来实现图片资源的加载:

decodeFile:从文件系统加载

decodeResource:从资源中加载

decodeStream:从输入流中加载

decodeByByteArray:从字节数组中加载

其中,decodeFile和decodeResource间接使用decodeStream来实现加载

如何高效加载

核心思想是通过BimapFactory.Options来加载所需尺寸的图片,主要是通过设置inSampleSize参数,应该总是2的指数,缩放比例为inSampleSize的平方.

步骤:

1.将BimapFactory.Options的inJustDecodeBounds参数设置为true并加载图片(只是解析图片)

2.从BimapFactory.Options中取出图片的原始宽高信息,对应于onWidth和onHeight

3.根据采样率的规则并结合目标View的所需大小计算出采样率inSampleSize

4.将BimapFactory.Options的inJustDecodeBounds设置为false,然后重新加载.

上代码:

//通过采样率实现高效加载
public static Bitmap decodeSampleFromResource(Resources res, int resId, int reqWidth, int reqHeight){
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeResources(res,resId,options);
options.inSampleSize = calculateInSampleSize(options,reqWidth,reqHeight);
options.inJustBounds - false;
return BitmapFactory.decodeResource(res,resId,options);
}
//计算inSampleSize
public static int calculateInSampleSize(BitmapFactory.Options options,int reqWidth,int reqHeight){
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if(height > reqHeight || width > reqWidth){
final int halfHeight = height/2;
final int halfWidth = width/2;
while((halfHeight/inSampleSize) >= reqHeigth && (halfWidth/inSampleSize) >= reqWidth){
inSampleSize *= 2;
}
}
return inSampleSize;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: