Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: take screenshot of whole WebView in Nougat ( Android 7 )

Tags:

I use below code to take screenshot from a WebView. it works well in Android 6 and lower versions but in Android 7 it takes only the visible part of the webview.

// before setContentView
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            WebView.enableSlowWholeDocumentDraw();
        }
...
// before set webview url
webView.setDrawingCacheEnabled(true);
// after html load complete
final Bitmap b = Bitmap.createBitmap(webView.getMeasuredWidth(),
                webView.getContentHeight(), Bitmap.Config.ARGB_8888);
        Canvas bitmapHolder = new Canvas(b);
        webView.draw(bitmapHolder);

but bitmap b is not complete. How can I take screenshot of whole WebView in Android Nougat?

Edit:
I found out the webView.getContentHeight doesn't works well. I hard coded the whole webview height and it works well. So the Question is : How can I get the Whole WebView Content Height in Android Nougat?

like image 475
Mneckoee Avatar asked Jul 21 '17 06:07

Mneckoee


1 Answers

Use the following methods instead of getMeasuredWidth() & getContentHeight() method:

computeHorizontalScrollRange(); -> for width 
computeVerticalScrollRange(); -> for height

these two methods will return the entire scrollable width/height rather than the actual widht/height of the webview on screen

To achieve this you need to make WebViews getMeasuredWidth() & getContentHeight() methods public like below

public class MyWebView extends WebView
{
    public MyWebView(Context context)
    {
        super(context);
    }

    public MyWebView(Context context, AttributeSet attrs)
    {
        super(context, attrs);
    }

    public MyWebView(Context context, AttributeSet attrs, int defStyle)
    {
        super(context, attrs, defStyle);
    }

    @Override
    public int computeVerticalScrollRange()
    {
        return super.computeVerticalScrollRange();
    }

}

in other work around you can also use a view tree observer to calculate the webview height as shown in this answer

like image 55
King of Masses Avatar answered Sep 23 '22 11:09

King of Masses