方法一: html 在從網絡或本地加載圖片的時候,只加載縮略圖。 緩存
- * 按照路徑加載圖片
- * @param path 圖片資源的存放路徑
- * @param scalSize 縮小的倍數
- * @return
- */
- public static Bitmap loadResBitmap(String path, int scalSize) {
- BitmapFactory.Options options = new BitmapFactory.Options();
- options.inJustDecodeBounds = false;
- options.inSampleSize = scalSize;
- Bitmap bmp = BitmapFactory.decodeFile(path, options);
- return bmp;
- }
這個方法的確可以少佔用很多內存,但是它的致命的缺點就是,由於加載的是縮略圖,因此圖片失真比較嚴重,對於對圖片質量要求很高的應用,能夠採用下面的方法。 網絡 方法二: 工具 運用JAVA的軟引用,進行圖片緩存,將常常須要加載的圖片,存放在緩存裏,避免反覆加載。 this 關於軟引用(SoftReference)的詳細說明,請參看http://www.auyou.cn/club/clubbbsinfo-9255.html。下面是我寫的一個圖片緩存的工具類。 spa
- *
- * @author larson.liu
- * 該類用於圖片緩存,防止內存溢出
- */
- public class BitmapCache {
- static * BitmapCache cache;
- /** 用於Chche內容的存儲*/
- * Hashtable bitmapRefs;
- /** 垃圾Reference的隊列(所引用的對象已經被回收,則將該引用存入隊列中)*/
- * ReferenceQueue q;
-
- /**
- * 繼承SoftReference,使得每個實例都具備可識別的標識。
- */
- * class BtimapRef extends SoftReference {
- * Integer _key = 0;
-
- public BtimapRef(Bitmap bmp, ReferenceQueue q, int key) {
- super(bmp, q);
- _key = key;
- }
- }
-
- * BitmapCache() {
- bitmapRefs = new Hashtable();
- q = new ReferenceQueue();
-
- }
-
- /**
- * 取得緩存器實例
- */
- public static BitmapCache getInstance() {
- if (cache == null) {
- cache = new BitmapCache();
- }
- return cache;
-
- }
-
- /**
- * 以軟引用的方式對一個Bitmap對象的實例進行引用並保存該引用
- */
- * void addCacheBitmap(Bitmap bmp, Integer key) {
- cleanCache();// 清除垃圾引用
- BtimapRef ref = new BtimapRef(bmp, q, key);
- bitmapRefs.put(key, ref);
- }
-
- /**
- * 依據所指定的drawable下的圖片資源ID號(能夠根據本身的須要從網絡或本地path下獲取),從新獲取相應Bitmap對象的實例
- */
- public Bitmap getBitmap(int resId, Context context) {
- Bitmap bmp = null;
- // 緩存中是否有該Bitmap實例的軟引用,若是有,從軟引用中取得。
- if (bitmapRefs.containsKey(resId)) {
- BtimapRef ref = (BtimapRef) bitmapRefs.get(resId);
- bmp = (Bitmap) ref.get();
- }
- // 若是沒有軟引用,或者從軟引用中獲得的實例是null,從新構建一個實例,
- // 並保存對這個新建實例的軟引用
- if (bmp == null) {
- bmp = BitmapFactory.decodeResource(context.getResources(), resId);
- this.addCacheBitmap(bmp, resId);
- }
- return bmp;
- }
-
- * void cleanCache() {
- BtimapRef ref = null;
- while ((ref = (BtimapRef) q.poll()) != null) {
- bitmapRefs.remove(ref._key);
- }
- }
-
- // 清除Cache內的所有內容
- public void clearCache() {
- cleanCache();
- bitmapRefs.clear();
- System.gc();
- System.runFinalization();
- }
-
- }
在程序代碼中調用該類: .net imageView.setImageBitmap(bmpCache.getBitmap(R.drawable.kind01, this)); code 這樣當你的imageView須要來回變換背景圖片時,就不須要再重複加載。 htm 方法三: 對象 及時銷燬再也不使用的Bitmap對象。 if (bitmap != null && b!itmap.isRecycled()){ bitmap.recycle(); bitmap = null; // recycle()是個比較漫長的過程,設爲null,而後在最後調用System.gc(),效果能好不少 } System.gc(); |