如何高效加载bitmap

来源:互联网 发布:蔚来汽车发展前景知乎 编辑:程序博客网 时间:2024/06/06 03:13

对于如何高效加载bitmap,就是采用BitmapFactory.Options来加载所需的图片大小。

通过BitmapFactory.Options来对图片进行缩放,主要利用其inSampleSize参数,即采样率。

获取采样率的步骤一般如下:

(1)将BitmapFactory.Options的inJustDecodeBounds参数设置为true并加载图片

(2)获取原始图片的宽高信息,即options的outwidth和outheight

(3)计算出所需采样率的大小,即inSampleSize的值

(4)将BitmapFactory.Options的inJustDecodeBounds参数设置为false并加载图片


相关代码如下

//reqWidth 期望的图片的宽,单位像素

//reqHeight 期望的图片的高,单位像素

public static Bitmap getBitmapFromRes(Resources res,int resId,int reqWidth,int reqHeight) {

final BitmapFactory.Options options = new BitmapFactory.Options();

options.inJustDecodeBounds = true;

BitmapFactory.decodeResource(res,resId,options);

options.inSampleSize = getSampleSize(options,reqWidth,reqHeight);

options.inJustDecodeBounds = false;

BitmapFactory.decodeResource(res,resId,options);

}


public static int getSampleSize(BitmapFactory.Options options,int reqWidth,int reqHeight) {

final int width = options.outWidth;

final int height = options.outHeight;

int inSampleSize = 1;

if (width > reqWidth || height > reqHeight) {

final int halfWidth = width / 2;

final int halfHeight = height / 2;

while ((halfWidth / inSampleSize) >= reqWidth &&  (halfHeight / inSampleSize) >= reqHeight) {

inSampleSize *= 2;

}

}

return inSampleSize;

}




0 0
原创粉丝点击