Bitmap高效加载
BitmapFactory四个方法
decodeFile
decodeResource
decodeStream
decodeByteArray
高效的加载Bitmap才有BitmapFactory.Options 可以很方便的对一个图片进行缩放
inSampleSize:采样率 缩放大小是2的次方形式递减
加载图片遵循的4个步骤代码如下:
public static Bitmap decodeSampledBitmapFormResource(
Resources resources,int resId,int reqWidth,int reqHeight){
final BitmapFactory.Options options=
new BitmapFactory.Options();
//第一步:设置inJuestDecodeBounds为true并加载图片
options.inJustDecodeBounds=true;//为ture时只会解析图片的原始宽/高信息,并不会真正的加载图片
BitmapFactory.decodeResource(resources,resId,options);
//第二步:从BitmapFactory.Options中获取原始宽高信息应用于outWidth/outHeigth参数
//第三步:结合目标View大小计算 inSampleSize
options.inSampleSize=calculateInSampleSize(options,reqWidth,reqHeight);
//第四步:设置inJuestDecodeBounds为false并加载图片
options.inJustDecodeBounds=false;
return BitmapFactory.decodeResource(resources,resId,options);
}
public static int calculateInSampleSize(
BitmapFactory.Options options,int reqWidth,int reqHeight){
//图片的原始的宽高信息
final int heigth=options.outHeight; //
final int width =options.outWidth;
int inSampleSize=1;
if (heigth>reqHeight||width>reqWidth){
final int halfHeigth=heigth/2;
final int halfWidth=width/2;
while ((halfHeigth/inSampleSize)>=reqHeight&&
(halfWidth/inSampleSize)>=reqWidth){
inSampleSize*=2;
}
}
return inSampleSize;
}
Android缓存策略
LruCache
内部采用了一个LinkHashMap以强引用的方式储存外界的缓存对象
//LruCache初始化过程
int maxMemory= (int) (Runtime.getRuntime().maxMemory()/1024);
int cacheSize=maxMemory/8;
mMemoryCache =new LruCache<String ,Bitmap>(cacheSize){
//计算缓存对象大小
@Override
protected int sizeOf(String key, Bitmap bitmap) {
return bitmap.getRowBytes()*bitmap.getHeight()/1024;
}
};
//缓存的获取
mMemoryCache.get(key);
//缓存的添加
mMemoryCache.put(key,bitmap);
DiskLruCache
/**
* @param directory 缓存的文件夹
* @param appVersion 应用版本号 一般设置为1
* @param valueCount 单个字节所对应的数据的个数 一般设置为1
* @param maxSize 缓存的总大小
* @return
*/
public static DiskLruCache open(File directory,int appVersion,int valueCount,long maxSize){
}