Android - Drawable to Bitmap

     Android developers often come across non-bitmap drawable like NinePatchDrawable, ColorDrawable etc and would need a bitmap representation of the same. Typically, custom views based on android's View end up with such needs. Fortunately, it is trivial with android's Canvas API.
In fact, the UI Toolkits like Button, ImageView etc eventually use the very same Canvas in its onDraw callback.

        if (drawable instanceof BitmapDrawable) {
            return ((BitmapDrawable) drawable).getBitmap();
        }

        final int width = drawable.getIntrinsicWidth();
        final int height = drawable.getIntrinsicHeight();

        final Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        final Canvas canvas = new Canvas(bitmap);
        drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
        drawable.draw(canvas);

   At this point, the bitmap has the drawable representation. The only catch is to use an appropriate createBitmap API as few of those return immutable bitmap.

No comments: