The Bitmap is the last member of the four essentials for drawing: something to draw (a String, Rect, etc.), Paint with which to draw, a Canvas on which to draw, and the Bitmap to hold the bits. Most of the time, you don't have to deal directly with a Bitmap, because the Canvas provided as an argument to the onDraw method already has one behind it. However, there are circumstances under which you may want to use a Bitmap directly.

A common use for a Bitmap is as a way to cache a drawing that is time-consuming to draw but unlikely to change frequently. Consider, for example, a drawing program that allows the user to draw in multiple layers. The layers act as transparent overlays on a base image, and the user turns them off and on at will. It might be very expensive to actually draw each individual layer every time onDraw gets called. Instead, it might be faster to render the entire drawing with all visible layers once, and only update it when the user changes which are visible.

The implementation of such an application might look something like Example 12-9.

Example 12-9. Bitmap caching private class CachingWidget extends View { private Bitmap cache;

public CachingWidget(Context context) { super(context); setMinimumWidth(200); setMinimumHeight(200);

public void invalidateCache() { cache = null; invalidate();

^Override protected void onDraw(Canvas canvas) { if (null == cache) {

cache = Bitmap.createBitmap( getMeasuredWidth(), getMeasuredHeight(), Bitmap.Config.ARGB_8888);

drawCachedBitmap(new Canvas(cache));

canvas.drawBitmap(cache, 0, 0, new Paint());

// ... definition of drawCachedBitmap

This widget normally just copies the cached Bitmap, cache, to the Canvas passed to onDraw. If the cache is marked stale (by calling invalidateCache), only then will drawCachedBitmap be called to actually render the widget.

The most common way to encounter a Bitmap is as the programmatic representation of a graphics resource. Resources.getDrawable returns a BitmapDrawable when the resource is an image.

Combining these two ideas—caching an image and wrapping it in a Drawable—opens yet another interesting window. It means that anything that can be drawn can also be postprocessed. An application that used all of the techniques demonstrated in this chapter could allow a user to draw furniture in a room (creating a bitmap) and then to walk around it (using the matrix transforms).

0 0

Post a comment