package com.tszy.utils;
import java.util.HashMap;
import java.util.Map.Entry;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
/**
* 游戏用到的所有图片
*
* @author JianbinZhu
*
*/
public final class Bmps {
// 解析图片用得到类
private static Resources res;
/**
* 记录所有已初始化的位图的集合
*/
private static HashMap<Integer, Bitmap>
bitmaps;
private Bmps() {
// TODO Auto-generated constructor stub
}
private static void put(
int id, Bitmap bmp) {
bitmaps.put(id, bmp);
}
/**
* 通过ID获取位图
*
* @param resId
* @return
*/
public static final Bitmap getBmp(
int resId) {
Bitmap bmp =
bitmaps.get(resId);
if (bmp ==
null) {
//long m1 = Runtime.getRuntime().totalMemory();
bmp =
BitmapFactory.decodeResource(res, resId);
// long m2 = Runtime.getRuntime().totalMemory();
// Log.i("aaa", "解码图片消耗内存:" + (m2-m1));
put(resId, bmp);
}
return bmp;
}
///
/**
* 初始化
*
* @param res
*/
public static final void init(Resources resources) {
Bmps.res =
resources;
bitmaps =
new HashMap<Integer, Bitmap>
();
}
/**
* 释放指定资源
*/
public static final void freeBmp(
int resId) {
Bitmap bmp =
bitmaps.remove(resId);;
if (bmp !=
null) {
bmp.recycle();
}
}
/**
* 释放所有已解码的图片
* 退出时调用
*/
public static final void freeAll() {
//HashMap遍历(效率最高法)
for(Entry<Integer, Bitmap>
entry : bitmaps.entrySet()){
Bitmap bmp =
entry.getValue();
if (bmp !=
null)
bmp.recycle();
}
bitmaps.clear();
bitmaps =
null;
}
}
描述:方便在程序中管理图片资源
转载于:https://www.cnblogs.com/merryjd/archive/2013/01/16/2863177.html
转载请注明原文地址: https://mac.8miu.com/read-39176.html