Android Bitmap 管理器

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值