Android Snippet: Draw layout to a Bitmap
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
// 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); layout.setDrawingCacheEnabled(true); // 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!







Cool thing, I made a small project from that some time ago
https://github.com/p47/ScreenShoter
Using the same technique, right?
greetings.
I love this library and I added one of my projects. the problem is that when viewing the interface under OS Ice Cream Sandwich looks like the picture shows. Can you tell me a way to correct it and make the correction. I am willing to work on it but can not find the way to make it compatible for minor API.
http://imageshack.us/photo/my-images/820/cardsengingerbread.png/
Leave a Reply
Want to join the discussion?Feel free to contribute!