I'm trying to take a screenshot of the contents of a LinearLayout. The layout contains a scrollview that can be of variable height/width. This code works fine when the layout is not too big (i.e. you don't need to scroll very much off screen to see everything):
View v1 = (LinearLayout)theLayout;
v1.setDrawingCacheEnabled(true);
Bitmap bitmap = Bitmap.createBitmap(v1.getDrawingCache());
v1.setDrawingCacheEnabled(false);
However, if the LinearLayout that I'm trying to capture is large, then the application crashes with a null pointer on v1.getDrawingCache().
There is an error in logcat:
05-11 13:16:20.999: W/View(17218): View too large to fit into drawing cache, needs 4784400 bytes, only 3932160 available
How can I properly take a screenshot of this layout? Is there another way to go about it that doesn't use so much memory?
Here's what ended up working for me to capture a large off-screen view in it's entirety:
public static Bitmap loadBitmapFromView(View v)
{
Bitmap b = Bitmap.createBitmap(v.getWidth(), v.getHeight(), Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(b);
v.layout(0, 0, v.getLayoutParams().width, v.getLayoutParams().height);
v.draw(c);
return b;
}
It's similar to the answer here, except that I use the view's width/height to create the bitmap
As the original question is talking about a ScrollView I just though I would add the following for anyone that was having problems getting the full height. To get the height of the ScrollView, the v.getHeight doesn't work, you need to use:
v.getChildAt(0).getHeight()
so the full thing would be:
ScrollView scrollView = (ScrollView) result.findViewById(R.id.ScrlView);
loadBitmapFromView(scrollView);
public static Bitmap loadBitmapFromView(View v)
{
int height = v.getChildAt(0).getHeight()
int width = v.getWidth()
Bitmap b = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(b);
v.layout(0, 0, v.getLayoutParams().width, v.getLayoutParams().height);
v.draw(c);
return b;
}
Just using v.getHeight just gets the screen height, not the full height of the ScrollView.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With