Reputation: 16280
The WebView has 2 deprecated methods that were used for capturing the content as an Image:
capturePicture()
setPictureListener()
As these are deprecated, what is now available to capture the webview content as an image?
Is this the correct way now:
public void takePicture() {
WebView webView = new WebView(context);
webView.setWebViewClient(new WebViewClient() {
@Override
public void onPageFinished(WebView view, String url) {
Bitmap b = Bitmap.createBitmap(view.getWidth(), view.getContentHeight(), Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(b);
view.draw(c);
}
});
}
Upvotes: 2
Views: 1183
Reputation: 6861
Yes, using WebView.draw()
is the correct way. However, doing that from onPageFinished
does not guarantee that there is anything actually displayed, as this event is fired when the page resources have been loaded, and the page can use some JS code which actually displays stuff.
The right approach is to use PictureListener.onNewPicture()
callback (despite its deprecated status). This event is still fired when WebView has drawn something, but as the documentation says, doesn't actually provide the picture -- for that, you have to call WebView.draw()
.
Also, be aware that if your app is targeting L API level or above, you need to call WebView.enableSlowWholeDocumentDraw()
prior to creating any WebViews in order to make it to draw the entire contents of WebView onto the canvas, see this.
Things will got better with the M release, where a new callback called VisualStateListener
is added (see this doc). You can check it out in the preview SDK.
Upvotes: 3