Game Development Reference
In-Depth Information
From Chapter 3, you should know what these values mean. If not, we strongly suggest that you
read the “Encoding Colors Digitally� section of Chapter 3 again.
Interestingly, there's no RGB888 color format. PNG only supports ARGB8888, RGB888, and
palletized colors. What color format would be used to load an RGB888 PNG? BitmapConfig.
RGB_565 is the answer. This happens automatically for any RGB888 PNG we load via the
BitmapFactory . The reason for this is that the actual framebuffer of most Android devices works
with that color format. It would be a waste of memory to load an image with a higher bit depth
per pixel, as the pixels would need to be converted to RGB565 anyway for final rendering.
So why is there the Config.ARGB_8888 configuration then? Because image composition can be
done on the CPU prior to drawing the final image to the framebuffer. In the case of the alpha
component, we also have a lot more bit depth than with Config.ARGB_4444 , which might be
necessary for some high-quality image processing.
An ARGB8888 PNG image would be loaded to a Bitmap with a Config.ARGB_8888 configuration.
The other two color formats are barely used. We can, however, tell the BitmapFactory to try to
load an image with a specific color format, even if its original format is different.
InputStream inputStream = assetManager.open("bob.png");
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_4444;
Bitmap bitmap = BitmapFactory.decodeStream(inputStream, null , options);
We use the overloaded BitmapFactory.decodeStream() method to pass a hint in the form of an
instance of the BitmapFactory.Options class to the image decoder. We can specify the desired
color format of the Bitmap instance via the BitmapFactory.Options.inPreferredConfig member,
as shown previously. In this hypothetical example, the bob.png file would be an ARGB8888 PNG,
and we want the BitmapFactory to load it and convert it to an ARGB4444 bitmap.
The BitmapFactory can ignore the hint, though.
This will free all the memory used by that Bitmap instance. Of course, you can no longer use the
bitmap for rendering after a call to this method.
You can also create an empty Bitmap with the following static method:
Bitmap bitmap = Bitmap.createBitmap( int width, int height, Bitmap.Config config);
This might come in handy if you want to do custom image compositing yourself on the fly. The
Canvas class also works on bitmaps:
Canvas canvas = new Canvas(bitmap);
You can then modify your bitmaps in the same way you modify the contents of a View .
Disposing of Bitmaps
The BitmapFactory can help us reduce our memory footprint when we load images. Bitmaps
take up a lot of memory, as discussed in Chapter 3. Reducing the bits per pixel by using a
smaller color format helps, but ultimately we will run out of memory if we keep on loading bitmap
Search WWH ::




Custom Search