Android自助餐之大图片加载

Android自助餐之大图片加载

原理

  1. 使用BitmapFactory.decodeStreeam()方法,该方法会调用native层代码来创建bitmap(两个重载都会调用)
  2. 使用带BitmapFactory.Options参数的方法,改参数可指定生成bitmap的大小

思路

  1. 根据View尺寸或Window尺寸来确定bitmap的尺寸
  2. 将确定好的尺寸放入BitmapFactory.Options
  3. 调用BitmapFactory.decodeStreeam()生成bitmap

步骤

  1. 根据图片路径或URI打开输入流

    InputStream is = getContentResolver().openInputStream(imageUri);
  2. 获取屏幕或View尺寸
    如果能确定View尺寸则使用View尺寸,如果不能(比如动态调整的View、自适应的View等)则获取最接近该View的尺寸,实在不行就获取当前Activity的Window尺寸(比屏幕尺寸小)

    • 获取Window尺寸

      WindowManager windowManager = getWindowManager();
      Display defaultDisplay = windowManager.getDefaultDisplay();
      defaultDisplay.getHeight();
      defaultDisplay.getWidth();
    • 获取View尺寸

      view.getMeasuredWidth();
      view.getMeasuredHeight();
  3. 根据目标尺寸生成BitmapFactory.Options

    BitmapFactory.Options option = new BitmapFactory.Options();
    option.inSampleSize = dstSize;
  4. 使用options调用BitmapFactory.decodeStream()生成bitmap

    Bitmap bitmap = BitmapFactory.decodeStream(is, null, option);

完整代码

InputStream is = null;
try {

    int screenWidth=getWindowManager().getDefaultDisplay().getWidth();
    int screenHeight=getWindowManager().getDefaultDisplay().getHeight();
    int maxSize=Math.max(screenWidth,screenHeight);//以长边为准

    is = getContentResolver().openInputStream(imageUri);
    BitmapFactory.Options option = new BitmapFactory.Options();
    option.inSampleSize = maxSize;
    Bitmap bitmap = BitmapFactory.decodeStream(is, null, option);
    imageView.setImageBitmap(bitmap);
} catch (Exception e) {
    e.printStackTrace();
} 
try{
    if(is!=null)is.close();
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值