Android优化之bitmap图片

      在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);
    }



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值