Yesterday I was wondering how to render a view to a bitmap.
It turns out to be pretty easy, you can use the View.buildDrawingCache() and related methods for that. The only gotcha I ran in to that you’ll have to layout the view yourself if you are instantiating the view outside of an activity.

Here is my working code:


Button b = new Button(context);
b.setText("Hello World");
b.setDrawingCacheEnabled(true);
// this is the important line :)
// Without it the button will have a dimension of 0,0
// and the bitmap will be null
b.layout(0, 0, 100, 100);
b.buildDrawingCache();
Bitmap bitmap = Bitmap.createBitmap(b.getDrawingCache());
b.setDrawingCacheEnabled(false);