• 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;
        }
    }
    描述:方便在程序中管理图片资源
  • 相关阅读:
    Swift
    UIWindow 详解及使用场景
    点击状态栏回到顶部的功能失效的解决办法
    iOS
    从经典问题来看 Copy 方法
    从汇编层面深度剖析C++虚函数
    数值的整数次方
    求整数二进制中1的个数
    C++中的位运算总结
    嵌入在C++程序中的extern "C"
  • 原文地址:https://www.cnblogs.com/merryjd/p/2863177.html
Copyright © 2020-2023  润新知