Android webview takes screenshot only from top of the page

帅比萌擦擦* 提交于 2020-02-24 03:59:09

问题


I am doing a very simple task of taking a screenshot from my webView into a Bitmap... I do it like this:

webView.setDrawingCacheEnabled(true);
Bitmap bitmap = Bitmap.createBitmap(webView.getDrawingCache(false));
webView.setDrawingCacheEnabled(false);
Canvas canvas = new Canvas(bitmap);
webView.draw(canvas);

The problem is that the final bitmap is always showing the top of my web page content! I actually need it to take the screenshot from where I have scrolled the content but this is not simply happening! I have been searching the net for two hours now but no one else seems to have a similar problem. any idea what could have gone wrong?


回答1:


I guess, this is on Lollipop? If so, make sure you call WebView.enableSlowWholeDocumentDraw() (doc) before your first call to setContentView() that inflates a layout with WebView.




回答2:


I came across the same problem and solved it the follwoing way:

First call WebView.enableSlowWholeDocumentDraw() before setContentView(). Then take the screenshot over the whole content of the webview and then crop the bitmap to the actual view size with the desired scroll offset:

// the minimum bitmap height needs to be the view height
int bitmapHeight = (webView.getMeasuredHeight() < webView.getContentHeight())
         ? webView.getContentHeight() : webView.getMeasuredHeight();

Bitmap bitmap = Bitmap.createBitmap(
         webView.getMeasuredWidth(), bitmapHeight, Bitmap.Config.ARGB_8888);

Canvas canvas = new Canvas(bitmap);
webView.draw(canvas);

// prevent IllegalArgumentException for createBitmap: 
// y + height must be <= bitmap.height()
int scrollOffset = (scrollTo + webView.getMeasuredHeight() > bitmap.getHeight())
         ? bitmap.getHeight() : scrollTo;

Bitmap resized = Bitmap.createBitmap(
         bitmap, 0, scrollOffset, bitmap.getWidth(), webView.getMeasuredHeight());


来源:https://stackoverflow.com/questions/31295237/android-webview-takes-screenshot-only-from-top-of-the-page

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