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

為{幸葍}努か 提交于 2019-12-12 10:48:39

问题


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?


回答1:


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




回答2:


Remove the below code block

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

Disabling the entire HTML document has a significant performance cost.

As per the documentation,

For apps targeting the L release, WebView has a new default behaviour that reduces memory footprint and increases performance by intelligently choosing the portion of the HTML document that needs to be drawn.

Might be worth looking into this

Answer for Edit 1: To retrieve the webview height after rendering https://stackoverflow.com/a/22878558/2700586



来源:https://stackoverflow.com/questions/45230181/android-take-screenshot-of-whole-webview-in-nougat-android-7

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!