Advertisement
ulfben

BitmapPool

Feb 26th, 2018
484
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.31 KB | None | 0 0
  1. import android.graphics.Bitmap;
  2. import java.util.HashMap;
  3. public class BitmapPool {
  4.     private static final String TAG = "BitmapPool";
  5.     private static final HashMap<String, Bitmap> mBitmaps = new HashMap<>();
  6.     private BitmapPool(){super();}
  7.  
  8.     public static Bitmap createBitmap(final Game engine, final String sprite, float widthMeters, float heightMeters){
  9.         final String key = BitmapPool.makeKey(sprite, widthMeters, heightMeters);
  10.         Bitmap bmp = BitmapPool.getBitmap(key);
  11.         if(bmp != null){
  12.             return bmp;
  13.         }
  14.         try {
  15.             bmp = BitmapUtils.loadScaledBitmap(engine.getContext(), sprite, (int)engine.worldToScreenX(widthMeters), (int)engine.worldToScreenY(heightMeters));
  16.             BitmapPool.put(key, bmp);
  17.         }catch(final Exception e){         
  18.             throw AssertionError(e.toString);
  19.         }  
  20.         return bmp;
  21.     }
  22.  
  23.     public static int size(){ return mBitmaps.size(); }
  24.     public static String makeKey(final String name, final float width, final float height){
  25.         return name+"_"+width+"_"+height;
  26.     }
  27.     public static void put(final String key, final Bitmap bmp){
  28.         if(mBitmaps.containsKey(key)) {
  29.             return;
  30.         }
  31.         mBitmaps.put(key, bmp);
  32.     }
  33.     public static boolean contains(final String key){
  34.         return mBitmaps.containsKey(key);
  35.     }
  36.     public static boolean contains(final Bitmap bmp){ return mBitmaps.containsValue(bmp); }
  37.     public static Bitmap getBitmap(final String key){
  38.         return mBitmaps.get(key);
  39.     }
  40.     private static String getKey(final Bitmap bmp){
  41.         if(bmp != null) {
  42.             for (HashMap.Entry<String, Bitmap> entry : mBitmaps.entrySet()) {
  43.                 if (bmp == entry.getValue()) {
  44.                     return entry.getKey();
  45.                 }
  46.             }
  47.         }
  48.         return "";
  49.     }
  50.     private static void remove(final String key){
  51.         Bitmap tmp = mBitmaps.get(key);
  52.         if(tmp != null){
  53.             mBitmaps.remove(key);
  54.             tmp.recycle();
  55.         }
  56.     }
  57.     public static void remove(Bitmap bmp){
  58.         if(bmp == null){return;}
  59.         remove(getKey(bmp));
  60.     }
  61.     public static void empty(){
  62.         for (final HashMap.Entry<String, Bitmap> entry : mBitmaps.entrySet()) {
  63.             entry.getValue().recycle();
  64.         }
  65.         mBitmaps.clear();
  66.     }
  67. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement