Android LruCache用于Bitmap
2015-07-23 12:37
411 查看
package com.stone.util; import android.graphics.Bitmap; import android.support.v4.util.LruCache; /** * author : stone * email : aa86799@163.com * time : 15/7/23 11 27 */ public class LruCacheUtil { private final long MAX_MEMORY = Runtime.getRuntime().maxMemory(); //以字节为单位 byte private LruCache<String, Bitmap> mLruCache; public LruCacheUtil() { mLruCache = new LruCache<String, Bitmap>((int) (MAX_MEMORY / 8)) {//1/8 作缓存区 @Override //必须重写 计算图片占用的内存大小 单位需要与 构造方法参数单位一致 protected int sizeOf(String key, Bitmap value) { //三种计算size方法 System.out.println(value.getByteCount() + "..."); System.out.println(value.getRowBytes() * value.getHeight() + "..."); System.out.println(value.getWidth() * value.getHeight() * getBytesForConfig(value .getConfig()) + "..."); return value.getByteCount(); } }; } private int getBytesForConfig(Bitmap.Config config) { switch (config) { case ALPHA_8: System.out.println("...ALPHA_8..."); return 1; case ARGB_4444: case RGB_565: System.out.println("...4444-565..."); return 2; case ARGB_8888: System.out.println("...8888..."); return 4; } return 0; } public synchronized void addBitmapToMemoryCache(String key, Bitmap bitmap) { if (mLruCache.get(key) == null) { if (key != null && bitmap != null) mLruCache.put(key, bitmap); } else // Log.w("LruCache", "the res is already exists"); ; } public synchronized Bitmap getBitmapFromLruCache(String key) { return mLruCache.get(key); } public synchronized void removeImageCache(String key) { if (key != null) { Bitmap bm = mLruCache.remove(key); if (bm != null) bm.recycle(); } } public void clearCache() { if (mLruCache.size() > 0) { mLruCache.evictAll(); // mLruCache.trimToSize(-1); } } }
测试:
Bitmap bitmap = Bitmap.createBitmap(100, 100, Bitmap.Config.ALPHA_8); new LruCacheUtil().addBitmapToMemoryCache("abc", bitmap);
相关文章推荐
- android开发——camera类拍照指定图片大小
- Android studio 编译出现非法字符: \65279解决办法
- GitHub 优秀的 Android 开源项目
- Android Studio 活动的最佳实践 知晓当前是在哪一个活动 随时随地地进入程序 启动活动的最佳写法 第一行代码
- 快捷方式连同程序一起卸载
- GitHub上最火的74个Android开源项目(三)
- GitHub上最火的40个Android开源项目(二)
- GitHub上最火的40个Android开源项目(一)
- androidStudio自动黑盒测试
- Android APK反编译就这么简单 详解
- Android设置EditText中字体颜色不一致以及光标移至到字后边
- android 分享到QQ空间的所有操作
- Android SDK Manager国内下载缓慢的问题
- Android 导入v7包常见错误,以及项目引用v7包错误解决,androidv7
- Android中Toast的用法简 4000 介
- 悬浮窗与Home Back事件
- 还原反编译后AndroidManifest.xml乱码为明文
- 关于android AVD 虚拟机调试出现的问题
- Android luhn算法 银行卡号校验
- Java和Android注释规范