简体   繁体   English

多次加载多个位图的最佳实践

[英]Best practices to load several bitmaps multiple times

I am creating an Android board game similar to, for example, Bubble Pop where I need to use several bitmaps multiple times. 我正在创建一个类似于例如Bubble Pop的Android棋盘游戏,在该游戏中我需要多次使用多个位图。

I have a list of Stones (10x10), where each Stone is an object which holds its bitmap and some other values. 我有一个Stones(10x10)列表,其中每个Stone是一个保存其位图和一些其他值的对象。 Lot of bitmaps (stone colors) are same. 许多位图(石头颜色)是相同的。

Right now i am using something like this for every Stone in the list: 现在,我在列表中的每块石头都使用这样的东西:

public class Stone extends Point{

  private Bitmap mImg;

  public Stone (int x, int y, Resources res, Stones mStone) {
    ...
    mImg = BitmapFactory.decodeResource(mRes, mStone.getId());
  }

  protected void changeColor(Stones newD){
      mStone = newD;
      mImg = BitmapFactory.decodeResource(mRes, mStone.getId());
    }
  }

I found several similar questions, but it is all about big bitmaps. 我发现了几个类似的问题,但这都是关于大位图的。 Also i found some Android documentation about caching images , but i am not sure if it solves my problem and how to share this cache between all my stones. 我也找到了一些有关缓存图像的Android文档 ,但不确定它是否解决了我的问题以及如何在所有石头之间共享此缓存。

What is the best practice, to achive good performance and avoid OutofMemoryError? 什么是最佳实践,以获得良好的性能并避免OutofMemoryError?

You probably don't need cache. 您可能不需要缓存。 Since you should have a limited number of stone colors (thus bitmaps) you can consider holding those graphic assets in one single class (probably static global class or through singleton pattern . 由于您应该具有有限数量的石头颜色(因此位图),因此可以考虑将这些图形资产保存在一个单一的类中(可能是static全局类,也可以通过singleton模式)

In your Stone class, you just need to hold the stone's color Id and get the drawable from your assets class. 在您的Stone类中,您只需要保留石头的颜色ID并从资产类中获取drawable (you can save bitmap, but drawable is much more efficient and you may easily change it to allow some animation later) (您可以保存位图,但drawable效率更高,您可以轻松地对其进行更改以在以后允许一些动画)

For example: 例如:

// Singleton - look at the link for the suggested pattern
public class GraphicAssets {
    private Context mContext;
    private Hashtable<Integer, Drawable> assets;

    public Drawable getStone(int id){
        if (assets.containsKey(id)) return assets.get(id);

        // Create stone if not already load - lazy loading, you may load everything in constructor
        Drawable d = new BitmapDrawable(BitmapFactory.decodeResource(mContext.getResources(), id));
        assets.put(id, d);
        return d;
    }

}

您可以将Bitmap变量设置为static或static final

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM