Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to capture a webview to bitmap in Android?

I have a webview, and I need to scroll down to view all the content. Now, I want to capture the entire of the webview to a bitmap.

I looked for many times. People suggested me use the function capturePicture(). However, this function is deprecated. So, what other methods I can use to do to reach my goal?

Thanks all.

like image 610
lolyoshi Avatar asked Jan 03 '14 09:01

lolyoshi


2 Answers

Android L, you need to call WebView.enableSlowWholeDocumentDraw() before creating any WebViews. That is, if you have any WebViews in your layout, make sure you call this method before calling setContentView() in your onCreate().
linked Mikhail Naganov:https://stackoverflow.com/a/30084485/703225

@Override
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        WebView.enableSlowWholeDocumentDraw();
    }
    ...
    setContentView(layout);
    ...
    ...
}

then:

/**
 * WevView screenshot
 * 
 * @param webView
 * @return
 */
public static Bitmap screenshot(WebView webView, float scale11) {
    try {
        float scale = webView.getScale();
        int height = (int) (webView.getContentHeight() * scale + 0.5);
        Bitmap bitmap = Bitmap.createBitmap(webView.getWidth(), height, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        webView.draw(canvas);
        return bitmap;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

if you don't use webView.getScale(), also:

public static Bitmap screenshot2(WebView webView) {
    webView.measure(MeasureSpec.makeMeasureSpec(
                    MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED),
            MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
    webView.layout(0, 0, webView.getMeasuredWidth(), webView.getMeasuredHeight());
    webView.setDrawingCacheEnabled(true);
    webView.buildDrawingCache();
    Bitmap bitmap = Bitmap.createBitmap(webView.getMeasuredWidth(),
            webView.getMeasuredHeight(), Bitmap.Config.ARGB_8888);

    Canvas canvas = new Canvas(bitmap);
    Paint paint = new Paint();
    int iHeight = bitmap.getHeight();
    canvas.drawBitmap(bitmap, 0, iHeight, paint);
    webView.draw(canvas);
    return bitmap;
}
like image 104
qinmiao Avatar answered Oct 16 '22 17:10

qinmiao


I found out the solution. Take a look of this.

I used the onDraw to replace the capturePicture functon which is deprecated in API 19. If you have any better solutions, please tell me and I appreciate that. Thanks!

Which can replace capturePicture function

like image 36
lolyoshi Avatar answered Oct 16 '22 17:10

lolyoshi