为了避免在ImageView中加载的图片过大而导致程序出现OOM的现象,利用BitmapFactory.Option的有关方法来实现。
主要流程
- 创建BitmapFactorty.Options对象设置inJustDecodeBound属性为true并加载图片
- 从BitmapFactory.Options 中取出图片的宽高信息,它们对应于outWidth和outHeight参数。
- 根据采样率的规则并结合目标View的所需大小计算出采样率inSampleSize。
4.将BitmapFactory.Options的inJuseDecodeBounds设为false,然后重新加载图片
/**
* @return
* 压缩Bitmap
*/
private Bitmap compressBitmap() {
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeResource(getResources(), R.drawable.ic, options);
options.inSampleSize = calculateInSmapleSize(options, 200, 200);
options.inJustDecodeBounds = false;
return BitmapFactory.decodeResource(getResources(), R.drawable,.ic, options);
}
/**
* @param options
* @param reqWidth
* @param reqHeight 计算inSmapleSize(采样率)
*/
private int calculateInSmapleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
final int width = options.outWidth;
final int height = options.outHeight;
int inSampleSize = 1;
if (reqWidth < width || reqHeight < height) {
int halfWidth = width / 2;
int halfHeigth = height / 2;
while ((halfHeigth / inSampleSize > reqWidth) && (halfWidth / inSampleSize) > reqWidth) {
inSampleSize *= 2;
}
}
return inSampleSize;
}
网友评论