In a previous post I talked about loading bitmaps. In this post I will tell something about caching the loaded resources. For this I created a little util class. To give you an example how to use it here is the code. I will explain it step by step.
private Matrix scaleMatrix; public UICard build(Card c, int color) { if (getBitmap(c, color) == null) { this.loadBitmap(c, color); } if (getBitmap(Card.Front, color) == null) { this.loadBitmap(Card.Front, color); } UICard card = new UICard(c, color); card.setBackImage(getBitmap(c, color)); card.setFrontImage(getBitmap(Card.Front, color)); return card; } private Bitmap getBitmap(Card c, int color) { LruCache<Card, Bitmap> cache = this.imageCacheRed; if (color == UICard.BLUE) { cache = this.imageCacheBlue; } return cache.get(c); } private void loadBitmap(Card c, int color) { int drawable = getRedDrawable(c); if (color == UICard.BLUE) { drawable = getBlueDrawable(c); } Bitmap cardImage = BitmapFactory.decodeResource(context.gtResources(),drawable); cardImage = Bitmap.createBitmap(cardImage, 0, 0, cardImage.getWidth(),cardImage.getHeight(), scaleMatrix, true); if (color == UICard.RED) { this.imageCacheRed.put(c, cardImage); } else { this.imageCacheBlue.put(c, cardImage); } } private void init() { final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024); final int cacheSize = maxMemory / 4; this.imageCacheBlue = new LruCache<Card, Bitmap>(cacheSize) { @Override protected int sizeOf(Card key, Bitmap bitmap) { return (bitmap.getRowBytes() * bitmap.getHeight()) / 1024; } }; this.imageCacheRed = new LruCache<Card, Bitmap>(cacheSize) { @Override protected int sizeOf(Card key, Bitmap bitmap) { return (bitmap.getRowBytes() * bitmap.getHeight()) / 1024 } }; Matrix m = new Matrix(); m.preScale(0.1f, 0.1f); this.scaleMatrix = m; } }
When the View needs an image it calls the method ‘build’ (3).
It passes a Card object that specifies which card we want to load. We also need to tell the builder which color we need ( two sides in this game remember? )
It will first check if bitmap belonging to the card specified already has been loaded in the past (20-26). It therefore will get the correct cache (21-24) ( Yes I have 2 cache’s one for each side ). When the card has not been found in the cache it should be loaded ( 5 and 6). Therefore we find the correct drawable (from the R object ) (29-32) and create a bitmap out of it (33-35). We scale it down using a scale matrix and we put the image back in the correct cache (37-41). After that we try to load it again (line 15-16).
By using this approach we asure the app that it will always be using the same instance of a particular bitmap.
I hope this will help you a bit developing your own game apps.