Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

View too large to fit into drawing cache when calling getDrawingCache()

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?

like image 551
DiscDev Avatar asked May 11 '13 18:05

DiscDev


2 Answers

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

like image 145
DiscDev Avatar answered Nov 15 '22 13:11

DiscDev


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.

like image 24
BlueJam Avatar answered Nov 15 '22 13:11

BlueJam