一个bitmap缓存的工具类

项目中用到了很多图片,所以写了个bitmap缓存的工具类

package cn.com.shine.pdi.hptv.util;

import android.graphics.Bitmap;
import android.support.v4.util.LruCache;

public class BitmapCache {
	private static LruCache<String, Bitmap> mMemoryCache;
	private static int MAXMEMONRY = (int) (Runtime.getRuntime() .maxMemory() / 1024);
	private static BitmapCache instance;
	
	public static BitmapCache getInstance(){
		if (instance == null) {
			instance = new BitmapCache();
		}
		initCache();
		return instance;
	}
	
	private static void initCache() {
        if (mMemoryCache == null){
            mMemoryCache = new LruCache<String, Bitmap>(
                    MAXMEMONRY / 8) {
                @Override
                protected int sizeOf(String key, Bitmap bitmap) {
                    // 重写此方法来衡量每张图片的大小,默认返回图片数量。
                    return bitmap.getRowBytes() * bitmap.getHeight() / 1024;
                }

                @Override
                protected void entryRemoved(boolean evicted, String key,
                        Bitmap oldValue, Bitmap newValue) {
                	LogUtil.i("hard cache is full , push to soft cache");
                   
                }
            };
        }
    }
		
		
	public void clearCache() {
        if (mMemoryCache != null) {
            if (mMemoryCache.size() > 0) {
            	LogUtil.i(
                        "mMemoryCache.size() " + mMemoryCache.size());
                mMemoryCache.evictAll();
                LogUtil.i( "mMemoryCache.size()" + mMemoryCache.size());
            }
            mMemoryCache = null;
        }
    }

	public synchronized void addBitmapToMemoryCache(String key, Bitmap bitmap) {
        if (mMemoryCache.get(key) == null) {
            if (key != null && bitmap != null)
                mMemoryCache.put(key, bitmap);
        } else
            LogUtil.i("the res is aready exits");
    }

	public synchronized Bitmap getBitmapFromMemCache(String key) {
        Bitmap bm = mMemoryCache.get(key);
        if (bm != null) {
            return bm;
        }
        return null;
    }

    /**
     * 移除缓存
     * 
     * @param key
     */
	public synchronized void removeImageCache(String key) {
        if (key != null) {
            if (mMemoryCache != null) {
                Bitmap bm = mMemoryCache.remove(key);
                if (bm != null)
                    bm.recycle();
            }
        }
    }
}

在项目里面就可以使用了,例如:

Bitmap bm = mCache.getBitmapFromMemCache(path);
if (bm == null) {
<span style="white-space:pre">	</span>bm = ImageUtils.getBitmap(path, width, height);
<span style="white-space:pre">	</span>mCache.addBitmapToMemoryCache(path, bm);
		}
	bm = mCache.getBitmapFromMemCache(path);
	imageView.setImageBitmap(bm);


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值