多次加载多个位图的最佳做法

时间:2012-05-21 01:06:44

标签: android caching bitmap android-bitmap

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

我有一个Stones列表(10x10),其中每个Stone都是一个保存其位图和其他值的对象。许多位图(石头颜色)是相同的。

现在我正在为列表中的每个Stone使用类似的东西:

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 documentation about caching images,但我不确定它是否解决了我的问题,以及如何在我的所有宝石之间共享这个缓存。

为达到良好的性能并避免OutofMemoryError,最佳做法是什么?

2 个答案:

答案 0 :(得分:2)

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

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

}

答案 1 :(得分:1)

你可以使Bitmap变量为static或static final

相关问题