0

我正在创建一个类似于Bubble Pop的 Android 棋盘游戏,我需要多次使用多个位图。

我有一个石头列表(10x10),其中每个石头都是一个对象,其中包含其位图和一些其他值。很多位图(石头颜色)是相同的。

现在我对列表中的每块石头都使用这样的东西:

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());
    }
  }

我发现了几个类似的问题,但都是关于大位图的。我还找到了一些关于缓存图像的 Android 文档,但我不确定它是否能解决我的问题以及如何在我所有的石头之间共享这个缓存。

获得良好性能并避免 OutofMemoryError 的最佳做法是什么?

4

2 回答 2

2

您可能不需要缓存。由于您应该拥有有限数量的石头颜色(因此是位图),您可以考虑将这些图形资源保存在一个类中(可能是static全局类或通过单例模式

在您的Stone课程中,您只需要持有石头的颜色 ID 并drawable从您的资产类别中获取。(您可以保存位图,但 drawable 效率更高,您可以轻松更改它以允许稍后制作一些动画)

例如:

// 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;
    }

}
于 2012-05-21T01:27:49.180 回答
1

你可以使位图变量静态或静态最终

于 2012-05-21T01:46:48.907 回答