Android: 在 Nougat 中截取整个 WebView ( Android 7 )

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

我使用下面的代码从 WebView 截取屏幕截图。它在 Android 6 和更低版本中运行良好,但在 Android 7 中它只占用 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);

但是位图b不完整。如何在 Android 牛轧糖中截取整个 WebView 的屏幕截图?

编辑:
我发现 webView.getContentHeight 效果不佳。我对整个 webview 高度进行了硬编码,效果很好。所以问题是:如何在 Android 牛轧糖中获得整个 WebView 内容高度?

删除下面的代码块

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

禁用整个 HTML 文档会显着降低性能。

根据文档,

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.

可能值得研究 this

编辑 1 的答案: 渲染后检索 webview 高度

使用以下方法代替 getMeasuredWidth() 和 getContentHeight() 方法:

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

这两种方法将 return 整个可滚动 width/height 而不是实际 widht/height 屏幕上的 webview

要实现此目的,您需要使 WebViews getMeasuredWidth() 和 getContentHeight() 方法 public 如下所示

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();
    }

}

在其他解决方法中,您还可以使用视图树观察器来计算 webview 高度,如此 answer