BitMap的高效加载

来源:互联网 发布:什么软件可以下载软件 编辑:程序博客网 时间:2024/04/30 21:05

BitmapFactory类提供四种方法来实现图片资源的加载:

decodeFile:从文件系统加载
decodeResource:从资源中加载
decodeStream:从输入流中加载
decodeByByteArray:从字节数组中加载
其中,decodeFile和decodeResource间接使用decodeStream来实现加载

如何高效加载

核心思想是通过BimapFactory.Options来加载所需尺寸的图片,主要是通过设置inSampleSize参数,应该总是2的指数,缩放比例为inSampleSize的平方.
步骤:
1.将BimapFactory.Options的inJustDecodeBounds参数设置为true并加载图片(只是解析图片)
2.从BimapFactory.Options中取出图片的原始宽高信息,对应于onWidth和onHeight
3.根据采样率的规则并结合目标View的所需大小计算出采样率inSampleSize
4.将BimapFactory.Options的inJustDecodeBounds设置为false,然后重新加载.
上代码:

//通过采样率实现高效加载public static Bitmap decodeSampleFromResource(Resources res, int resId, int reqWidth, int reqHeight){    final BitmapFactory.Options options = new BitmapFactory.Options();    options.inJustDecodeBounds = true;    BitmapFactory.decodeResources(res,resId,options);    options.inSampleSize = calculateInSampleSize(options,reqWidth,reqHeight);    options.inJustBounds - false;    return BitmapFactory.decodeResource(res,resId,options);}//计算inSampleSizepublic 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) >= reqHeigth && (halfWidth/inSampleSize) >= reqWidth){            inSampleSize *= 2;        }    }    return inSampleSize;}
0 0