Android缩放图片加载大图片

来源:互联网 发布:windows启动错误恢复 编辑:程序博客网 时间:2024/04/28 21:57

在android项目中导入图画时,如果图片过大,手机可能会加载不出来或者比例不合适,此时我们需要对图片进行缩放,然后放入应用。

public void click(View v){        //解析图片时需要使用到的参数都封装在这个对象里面        Options opt = new Options();        //不为像素申请内存,只获取图片的宽高        opt.inJustDecodeBounds = true;        BitmapFactory.decodeFile("data/data/com.example.loadimage/cache/dog.jpg",opt);        //拿到图片宽高        int imageWidth = opt.outWidth;        int imageHeight = opt.outHeight;        //拿到屏幕的宽高        Display dp = getWindowManager().getDefaultDisplay();        int screenWidth = dp.getWidth();        int screenHeight = dp.getHeight();        //计算缩放比例        int scale = 1;        int scaleWidth = imageWidth / screenWidth;        int scaleHeight = imageHeight / screenHeight;        //比较缩放比例,选择合适的比例,一般取大的        if(scaleWidth > scaleHeight && scaleWidth >= 1){            scale = scaleWidth;        }else if(scaleWidth <= scaleHeight && scaleHeight >= 1){            scale = scaleHeight;        }        //设置缩放比例        opt.inSampleSize = scale;        //这里就需要申请内存了,所以改变inJustDecodeBounds的值        opt.inJustDecodeBounds = false;        Bitmap bm = BitmapFactory.decodeFile("data/data/com.example.loadimage/cache/dog.jpg",opt);        ImageView iv = (ImageView) findViewById(R.id.iv);        iv.setImageBitmap(bm);    }
0 0
原创粉丝点击