簡體   English   中英

如何在Android中捕獲webview到位圖?

[英]How to capture a webview to bitmap in Android?

我有一個webview,我需要向下滾動才能查看所有內容。 現在,我想將整個webview捕獲到位圖。

我找了好幾次。 人們建議我使用函數capturePicture() 但是, 不推薦使用此功能。 那么,我可以用什么方法來實現我的目標呢?

謝謝大家。

在Android L中,您需要在創建任何WebView之前調用WebView.enableSlowWholeDocumentDraw()。 也就是說,如果布局中有任何WebView,請確保在onCreate()中調用setContentView()之前調用此方法。
鏈接Mikhail Naganovhttps//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);
    ...
    ...
}

然后:

/**
 * 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;
}

如果你不使用webView.getScale(),還:

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

我找到了解決方案。 看看這個。

我使用onDraw來替換API 19中不推薦使用的capturePicture功能。如果你有更好的解決方案,請告訴我,我很感激。 謝謝!

哪個可以取代capturePicture功能

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM