android: 缓存异步加载Bitmap

step1:创建内存缓存

//采用内存缓存,速度快,占用内存

public class MemoryCache {
private static LruCache<String, Bitmap> cache;
private MemoryCache(){};
public static LruCache<String, Bitmap> getInstance(){
if(cache == null){
final int _maxMemory = (int)(Runtime.getRuntime().maxMemory()/1024);
final int _cacheSize = _maxMemory/8;
cache = new LruCache<String, Bitmap>(_cacheSize);
}
return cache;
}

public static void addBitmapToMemoryCache(String key,Bitmap bmp){
if(cache.get(key) == null)
cache.put(key, bmp);
}

public static Bitmap getBitmapFromCache(String key){
return cache.get(key);
}
}

step2:压缩Bitmap

public class BitmapCompress {
public static Bitmap Comperss(Resources res,int resId,int requestWidth,int requestHeight){
BitmapFactory.Options _options = new BitmapFactory.Options();
_options.inJustDecodeBounds = true; //不加载进内存
BitmapFactory.decodeResource(res, resId, _options);
int outWidth = _options.outWidth;
int outHeight = _options.outHeight;

int inSampleSize =1;
//计算压缩比例
while(outWidth/requestWidth >inSampleSize
&&outHeight/requestHeight>inSampleSize){
inSampleSize*=2;
}
_options.inSampleSize = inSampleSize;
//加载进内存
_options.inJustDecodeBounds = false;
return BitmapFactory.decodeResource(res, resId, _options);
}
}

step3:异步加载Bitmap

public class LoadImageTask extends AsyncTask<Integer,Integer,Bitmap>{
private final WeakReference<ImageView> mImageViewReference;
private Context mContext;

public LoadImageTask(Context pContext,ImageView pImageView){
mContext = pContext;
mImageViewReference = new WeakReference<ImageView>(pImageView);
}

@Override
protected Bitmap doInBackground(Integer... params) {
Bitmap _bitmap = BitmapCompress.Comperss(mContext.getResources(), params[0], 200, 200);
//将_bitmap加入缓存中
MemoryCache.getInstance().put(String.valueOf(params[0]), _bitmap);
return _bitmap;
}

@Override
protected void onPostExecute(Bitmap result) {
super.onPostExecute(result);
if(mImageViewReference != null && result != null){
ImageView _imageview = mImageViewReference.get();
if(_imageview != null)
_imageview.setImageBitmap(result);
}
}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值