您的位置:首页 > 其它

Bitmap位图采样及LurCache缓存

2016-06-03 22:06 417 查看
通过位图采样,来缩小图片占用内存大小

通过缓存加载图片时来缓存中拿

public class MainActivity extends Activity {
private ImageView iv;
private LruCache<String, Bitmap> lc;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

// 获取当前内存大小
ActivityManager am = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
int memoryClass = am.getMemoryClass();
// 定义缓存的大小(内存的八分之一)
int cachesize = memoryClass / 8 * 1024 * 1024;
// 添加到缓存
lc = new LruCache<String, Bitmap>(cachesize);
}

// 从缓存中获取bitmap
public Bitmap getBitmapFormCache(String key) {
return lc.get(key);
}

// 将图片添加到缓存
public void addBitmptoCache(String key, Bitmap bt) {
if (getBitmapFormCache(key) == null) {
lc.put(key, bt);
}
}

//通过ImageView监听加载
public void show(View view) {
String key = String.valueOf(R.drawable.ic_launcher);
Bitmap bitmap = getBitmapFormCache(key);
if (bitmap == null) {// 如果是空
// 100指目标
bitmap = setBiamap(getResources(), R.drawable.ic_launcher, 100, 100);
addBitmptoCache(key, bitmap);// 如果没有添加到缓存中
}
iv.setImageBitmap(bitmap);
}

// 返回缩小以后的位图
public Bitmap setBiamap(Resources res, int resid, int weighe, int height) {
BitmapFactory.Options options = new BitmapFactory.Options();
// 只解析边界不加载内存
options.inJustDecodeBounds = true;
// 得到图片资源
BitmapFactory.decodeResource(res, resid, options);
// 设置采样比例
options.inSampleSize = setsize(options, weighe, height);
// 得到缩小后的图片加载到内存
options.inJustDecodeBounds = false;
Bitmap bitmap = BitmapFactory.decodeResource(res, resid);
return bitmap;
}

// 根据大小来设置采样比例
private int setsize(BitmapFactory.Options options, int resultwieght,
int resuktheight) {
int w = options.outWidth;
int h = options.outHeight;
int round = 1;
if (w > resuktheight || h > resultwieght) {
if (w > h) {
// 取小的进行设置比例
round = Math.round((float) h / (float) resuktheight);
} else {
round = Math.round((float) w / (float) resultwieght);
}
}
return round;
}
}


《Android版本更新、热更新》系列课程视频

版本更新6.0,7.0统统搞定!!

热修复不在麻烦,再也不用担心上线后出bug!!

http://edu.csdn.net/course/detail/6523

http://edu.csdn.net/course/play/6523/131198

《Kotlin语法基础到实战开发》系列课程视频

http://edu.csdn.net/course/detail/6409?locationNum=7&fps=1&ref=srch&loc=1

http://edu.csdn.net/course/play/6409/123752
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: