5

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?

mmBs
  • 8,421
  • 6
  • 38
  • 46
DiscDev
  • 38,652
  • 20
  • 117
  • 133
  • 1
    http://stackoverflow.com/questions/9791714/take-a-screenshot-of-a-whole-view. check the answer by kameltreiber – Raghunandan May 11 '13 at 18:27
  • I tried the accepted answer here, but there were some problems with the generated output. The answer here is what worked for me: https://stackoverflow.com/a/44129753/5987223 – drishit96 Dec 15 '19 at 08:53

2 Answers2

13

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

Community
  • 1
  • 1
DiscDev
  • 38,652
  • 20
  • 117
  • 133
1

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.

BlueJam
  • 43
  • 1
  • 7