码迷,mamicode.com
首页 > 移动开发 > 详细

Android开发之Bitmap的高效加载

时间:2016-08-14 23:54:40      阅读:224      评论:0      收藏:0      [点我收藏+]

标签:

BitmapFactory类提供了四类方法:decodeFile, decodeResource, decodeStream和decodeByteArray

分别用于支持从文件系统,资源,输入流以及字节数组中加载出一个Bitmap对象,前两者又间接调用了decodeStream

为了避免OOM,可以通过采样率有效的加载图片

如果获取采样率?

1.将BitmapFactory.Options的inJustDecodeBounds的参数设置为true并加载图片

2.从BitmapFactory.Options中取出图片的原始宽高,它们对应outWidth和outHeight参数

3.根据采样率的规则并结合目标View的所需大小计算采样率inSampleSize

4.将BitmapFactory.Options的inJustDecodeBounds的参数设置为false,并重新加载图片

上述步骤通过代码体现:

public static Bitmap decodeSampledBitmapFromResource(Resource res, int resId, int reqWidth, int reqHeight){
    final BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeResource(res, resId, options);
    
    options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
    options.inJustDecodeBounds = false;
    return BitmapFactory.decodeResource(res, resId, options);
}
public static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight){
    final int height = options.outHeight;
    final int width = options.outWidth;
    int inSampleSize = 1;
    if(height > reqHeight || width > reqWidth){
        final int halfHeight = height / 2;
        final int halfWidth = width / 2;
        
        while((halfHeight / inSampleSize) >= reqHeight && (halfWidth / inSampleSize) >= reqWidth){
            inSampleSize *= 2;            
        }
    }
    
    return inSampleSize;
}

 

Android开发之Bitmap的高效加载

标签:

原文地址:http://www.cnblogs.com/cxsy/p/5771270.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!