I needed this code for a project, where I needed to capture a certain list item I was rendering into a Bitmap and upload it using Facebook’s SDK.
This snippet basically “screen captures” and draws a certain view and saves it as a Bitmap and is the right way to do this.
Another solution to this is trying to draw everything on Canvas* “manually”, but taking the time to figure out all the bounds and text sizes, and getting the exact positions of things on a canvas sound like a real inconvenience. This makes it the wrong way to do this.
// Create a new bitmap and a new canvas using that bitmap
Bitmap bmp = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bmp);
// Get LayoutInflater reference
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// Inflate the View
View layout = inflater.inflate(R.layout.layout_name, null);
// Supply measurements
layout.measure(MeasureSpec.makeMeasureSpec(canvas.getWidth(), MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(canvas.getHeight(), MeasureSpec.EXACTLY));
// Apply the measures so the layout would resize before drawing.
layout.layout(0, 0, layout.getMeasuredWidth(), layout.getMeasuredHeight());
// and now the bmp object will actually contain the requested layout
canvas.drawBitmap(layout.getDrawingCache(), 0, 0, new Paint());
And you’re done!