2019独角兽企业重金招聘Python工程师标准>>>
发现android 加载res图片如果过多也会崩溃
android 也是使用
Bitmap bm = BitmapFactory.decodeResourceStream(res, value, is, pad, opts);
来加载图片,不同他一般不会释放,如果图片太多就崩溃了
不过解决方法就更简单了,做个缓存,以后如果app 有很多图片还是要自己管理图片啊
这个类同样适用 sd卡的图片
package com.example.iqtest.util;import java.io.InputStream;
import java.lang.ref.SoftReference;
import java.util.HashMap;import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.widget.ImageView;public class BitmapManager { private static HashMap<String, SoftReference<Bitmap>> cache; //如果是 int object的键值 对 应该是使用 SparseArray<E>的 但是这里考虑更多的还是加载sd卡的图片!static { cache = new HashMap<String, SoftReference<Bitmap>>(); } /*** 加载图片-可指定显示图片的高宽* @param path* @param imageView* @param width* @param height*/public void loadBitmap(int resId, ImageView imageView , Context context) { Bitmap bitmap = getBitmapFromCache(resId + ""); if (bitmap != null) { imageView.setImageBitmap(bitmap); } else { Bitmap bmp = getBitmap(resId , context);imageView.setImageBitmap(bmp);} } /*** 从缓存中获取图片* @param path*/private Bitmap getBitmapFromCache(String path) { Bitmap bitmap = null;if (cache.containsKey(path)) { bitmap = cache.get(path).get(); } return bitmap; } /*从res中加载图片*/private Bitmap getBitmap(int resId , Context context){Bitmap bitmap = null;BitmapFactory.Options opt = new BitmapFactory.Options(); opt.inPreferredConfig = Bitmap.Config.RGB_565; opt.inPurgeable = true; opt.inInputShareable = true; //获取资源图片 InputStream is = context.getResources().openRawResource(resId); bitmap =BitmapFactory.decodeStream(is,null,opt); if (bitmap != null) {cache.put(resId + "", new SoftReference<Bitmap>(bitmap));}return bitmap;}
}