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);
This work only for a button, if you whand to do this on a more complicated Layout, use this code:CardView cardView = Your View ;//two important lines cardView.measure(150, 183); cardView.layout(0, 0, 150, 183); cardView.setDrawingCacheEnabled(true); Bitmap originalImage= cardView.getDrawingCache();
Yes, the bottom line is to manually resize the view or make the layout do it. Thanks for your comment.