您的位置:首页 > 移动开发 > Android开发

四步实现根据View大小压缩加载Bitmap

2016-11-15 00:32 302 查看
根据View大小压缩加载Bitmap:
1.将BitmapFactory.Options的inJustDecodeBounds设置为:true,并加载图片
2.从BitmapFactory.Options取出图片的原始尺寸信息,它们应对与outWidth和outHeigth参数
3.根据采样率的规则并结合目标View的所需大小计算出采样率inSampleSize
4.将BitmapFactory.Options的inJustDecodeBounds参数设置成false,然后重新加载图片

*注意:这里inJustDecodeBounds设置为:true时,BitmapFactory并不会真正的去加载Bitmap,只是去解析Bitmap的宽高信息,所以这个操作是轻量级的

根据上面4步流程来实现,就产生了如下代码:
package com.example.administrator.myapplication.utils;

import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;

/**
* Created by Administrator on 2016/11/14 0014.
*/

public class BitmapUtil {
public static Bitmap decodeSampledbitmapFromResource(Resources resources, int resID, int reqWidth, int reqHeight) {
final BitmapFactory.Options option = new BitmapFactory.Options();
//设置inJustDecodeBounds为:ture,预先加载Bitmap的宽高参数
option.inJustDecodeBounds = true;
BitmapFactory.decodeResource(resources, resID, option);
//计算图片的采样率
option.inSampleSize = calcuteInSapmleSize(option, reqWidth, reqHeight);
//根据图片采样率加载图片
option.inJustDecodeBounds = false;

return BitmapFactory.decodeResource(resources, resID, option);
}

private static int calcuteInSapmleSize(BitmapFactory.Options option, int reqWidth, int reqHeight) {
final int height = option.outHeight;
final int width = option.outWidth;
Log.e("info", "width======" + width+"\n"+"height======"+height);
Log.e("info", "reqWidth======" + reqWidth+"\n"+"reqHeight======"+reqHeight);
int inSample = 1;
if (height > reqHeight || width > reqWidth) {
final int halfHeight = height / 2;
final int halfWidth = width / 2;
while ((halfHeight / inSample) >= reqHeight && (halfWidth / inSample) >= reqWidth) {
inSample *= 2;
}
}
Log.e("info", "inSample======" + inSample);
return inSample;
}

}

具体使用方法:
mImageView.setImageBitmap(BitmapUtil.decodeSampledbitmapFromResource(this.getResources(), R.mipmap.ic_launcher, 70, 70));
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  android 压缩 图片