Beg*_*ner 3 android photo image bitmap
我的应用程序使用位图,每次用户进入特定活动时,它会在第二次停止工作时显示图像.
Bitmap bm = BitmapFactory.decodeFile(Environment.getExternalStorageDirectory()+"//Pics/"Image.jpg");
Run Code Online (Sandbox Code Playgroud)
我尝试过使用像......这样的东西
BitmapFactory.Options options = new BitmapFactory.Options();
options.inTempStorage = new byte[16*1024];
Run Code Online (Sandbox Code Playgroud)
不知道该怎么设置它.但这没有帮助.一旦用户离开此活动,是否有办法清除位图等?谢谢
除了按照建议使用Bitmap.recycle()之外(它不适合所有情况,并且要问:" 我还需要这个位图吗? "),我总是使用这种技术非常好:
// 1. create a cache map
private WeakHashMap<String, SoftReference<Bitmap>> mCache;
Run Code Online (Sandbox Code Playgroud)
正如您所看到的,它是WeakReferences 的哈希映射,其中a SoftReference为值.
//2. when you need a bitmap, ask for it:
public Bitmap get(String key){
if( key == null ){
return null;
}
if( mCache.containsKey(key) ){
SoftReference<Bitmap> reference = mCache.get(key);
Bitmap bitmap = reference.get();
if( bitmap != null ){
return bitmap;
}
return decodeFile(key);
}
// the key does not exists so it could be that the
// file is not downloaded or decoded yet...
File file = new File(Environment.getExternalStorageDirectory(), key);
if( file.exists() ){
return decodeFile(key);
} else{
throw new RuntimeException("Boooom!");
}
}
Run Code Online (Sandbox Code Playgroud)
这将检查缓存映射.如果文件已经解码,则会返回; 否则它将被解码和缓存.
//3. the decode file will look like this in your case
private Bitmap decodeFile(String key) {
Bitmap bitmap = BitmapFactory.decodeFile(Environment.getExternalStorageDirectory()+"//Pics/"+key);
mCache.put(key, new SoftReference<Bitmap>(bitmap));
return bitmap;
}
Run Code Online (Sandbox Code Playgroud)
使用软引用很好,因为您将位图从内存中删除的责任转移到操作系统.
| 归档时间: |
|
| 查看次数: |
3830 次 |
| 最近记录: |