I am creating an Android board game similar to, for example, Bubble Pop where I need to use several bitmaps multiple times.
I have a list of Stones (10×10), where each Stone is an object which holds its bitmap and some other values. 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.
What is the best practice, to achive good performance and avoid 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
staticglobal class or through singleton pattern.In your
Stoneclass, you just need to hold the stone’s color Id and get thedrawablefrom your assets class. (you can save bitmap, but drawable is much more efficient and you may easily change it to allow some animation later)For example: