在android项目的imageview中使用大图bitmap时会占据很大的内存,而且在很多时候我们并不需要显示原图那么大的图片,比如一个100*100的图片,我们只需要显示50*50,直接设置的话会造成大量的内存浪费。
所以我们需要对图片进行优化,减少内存开销。我们会使用BitmapFactory.Options的方法来进行图片缩放,先介绍几个重要的属性。
inJustDecodeBounds:这个属性当设置为true时,在bitmapfactory创建bitmap对象时,我们仍然可以获取到bitmap的属性,但是不会分配内存,这时我们就能对其操作进行缩小或者放大。
inSampleSize:设置图片缩放的比例,比如设为2时,长宽各缩放两倍,然后整个图片缩小了4倍。
private Bitmap swapBitmap(float imagew ,float imageh ,int id){
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true; //先设置为true再decode图片资源,节省内存
bitmap = BitmapFactory.decodeResource(getResources(), id, options);
int yRadio = (int) Math.ceil(options.outHeight / imageh);
int xRadio = (int) Math.ceil(options.outWidth / imagew);
if (yRadio > 1 || xRadio >1) {
if (yRadio > xRadio) {
options.inSampleSize = yRadio;
}else {
options.inSampleSize = xRadio;
}
}else {
Toast.makeText(this, "insimplesize的值 : 1" ,Toast.LENGTH_SHORT).show();
}
options.inJustDecodeBounds = false;
bitmap = BitmapFactory.decodeResource(getResources(),id, options);
return bitmap;
}
这个方法参数为预计缩放的宽,高,以及图片资源的id,宽高是px格式的。
调用如下:
Bitmap bitmap2 = swapBitmap(50, 50,R.drawable.ic_launcher);
view.setImageBitmap(bitmap2);
另外因为我们在上面设置的是px,在不同分辨率的手机上会显示出差异,所以需要将预先设置的dp转为px.
//dp convert to px
private int dp2px(float dipValue){
float scale = getResources().getDisplayMetrics().density;
Log.i("scale", String.valueOf(scale));
return (int) (dipValue*scale+0.5f);
}
//px convert to dp
private int px2dp(float pxValue){
float scale = getResources().getDisplayMetrics().density;
Log.i("scale", String.valueOf(scale));
return (int) (pxValue / scale +0.5f);
}