Android: Take a screenshot of the entire WebView in Nugat (Android 7)

I am using below code to take screenshot from WebView

. it works fine in Android 6 and lower, but in Android 7 it only takes up the visible portion of the web browser.

// 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 do I take a screenshot of everything WebView

in Android Nougat?

Edit:
I found out that webView.getContentHeight

doesn't work very well. I have hardcoded the entire height WebView

and it works well. So the question is, how can I get the whole WebView

Content Height in Android Nougat?

+3


source to share


2 answers


Use the following methods instead of getMeasuredWidth () and getContentHeight () methods:

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

      

these two methods will return the entire scroll width / height, not the actual web screen width / height on the screen.



To achieve this, you need to create the getMeasuredWidth () and getContentHeight () methods of the WebView as shown 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, you can also use the view tree observer to calculate the height of the webview as shown in this.

+2


source


Remove the bottom block of code

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        WebView.enableSlowWholeDocumentDraw();
    }

      

Disabling the entire HTML document has a significant work cost.

According to the documentation,



For applications targeting the L release, WebView has a new default behavior that reduces memory and improves performance by judiciously choosing the portion of the HTML document to draw.

Maybe worth a look

Answer for edit 1: To get the height of the webview after rendering fooobar.com/questions/412388 / ...

0


source







All Articles