BitmapFactory.Options加载图片<备忘录>
2018-11-11 本文已影响0人
SimpleGk
如何高效的加载Bitmap?可以使用BitmapFactory.Options来加载图片。
通过BitmapFactory.Options可以加载按一定的采d样率加载缩小后的图片。
缩放图片,主要用到了inSampleSize,使用options.inSampleSize对它进行设置。当inSampleSize为1时,图片为原始大小,当inSampleSize为2时,一个1980x1024像素的图片被缩小为990x512,即长宽缩小为原来1/2,像素和图片大小缩小为原来的1/4,以此类推。
通过使用inJustDecodeBounds来获取图片的采样率,inJustDecodeBounds为false时,BitmapFactory只会解析图片的宽高,不会真正的去加载图片,当获取采样率后将inJustDecodeBounds设置为true后就可以加载图片。
public static int calculateInSampleSize(BitmapFactory.Options options,int rWidth,int rHeight){
final int width=options.outWidth;
final int height=options.outHeight;
int inSampleSize=1;
if(height>rHeight||width>rWidth){
final int tempHeight=height;
final int tempWidth=width;
inSampleSize*=2;
while((tempHeight/inSampleSize)>=rHeight&&(tempWidth/inSampleSize)>=rWidth){
inSampleSize*=2;
}
}
return inSampleSize;
}
获取采样率的算法,采样率最好使用2的指数。
final BitmapFactory.Options options=new BitmapFactory.Options();
options.inJustDecodeBounds=true;
BitmapFactory.decodeResource(resources,resId,options);
options.inSampleSize=calculateInSampleSize(options,rWidth,rHeight);
options.inJustDecodeBounds=false;
return BitmapFactory.decodeResource(resources,resId,options);
效果如下:

