原生WebView长截图 和 Tencent x5webview截长图

前言: 之前项目用的是原生webview,最近使用公司新框架使用的是x5的webview;正好有需求需要做长截图,踩坑之路开始。


1、原生WebView长截图

Android5.0及以上版本,Android对WebView进行了优化,为了减少内存使用和提高性能,使用WebView加载网页时只绘制显示部分。如果我们不做处理,仍然使用上述代码截图的话,就会出现只截到屏幕内显示的WebView内容,其它部分是空白的情况。
这时候,我们通过调用WebView.enableSlowWholeDocumentDraw()方法可以关闭这种优化,但要注意的是,该方法需要在WebView实例被创建前就要调用,否则没有效果。

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        android.webkit.WebView.enableSlowWholeDocumentDraw();
    }
/**
     * 原生WebView长截图
     *
     * @param webView
     * @return
     */
    public static Bitmap getWebViewBtpBase64Str(WebView webView) {
        Bitmap bitmap = null;
        try {
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
                Picture snapShot = webView.capturePicture();
                bitmap = Bitmap.createBitmap(snapShot.getWidth(), snapShot.getHeight(), Bitmap.Config.RGB_565);
                Canvas canvas = new Canvas(bitmap);
                snapShot.draw(canvas);
            } else {
                float scale = webView.getScale();
                //得到缩放后webview内容的高度
                int webViewHeight = (int) (webView.getContentHeight() * scale);
                bitmap = Bitmap.createBitmap(webView.getWidth(), webViewHeight, Bitmap.Config.RGB_565);
                Canvas canvas = new Canvas(bitmap);
                //绘制
                webView.draw(canvas);
            }
            return bitmap;
        } catch (OutOfMemoryError e) {
            LogEx.e("ScreenUtils", e.getMessage(), e);
        } catch (Exception e) {
            LogEx.e("ScreenUtils", e.getMessage(), e);
        } finally {
        }
        return "";
    }

2、Tencent x5webview截长图

/**
     * Tencent x5webview截长图
     *
     * @param webView
     * @return
     */
    public static Bitmap getX5WebViewBtpBase64Str(WebView webView) {
        if (webView == null) {
            return null;
        }
        int wholeWidth = webView.getContentWidth();
        int wholeHeight = webView.getContentHeight();
        Bitmap x5bitmap = Bitmap.createBitmap(wholeWidth, wholeHeight, Bitmap.Config.RGB_565);
        Canvas x5canvas = new Canvas(x5bitmap);
//        x5canvas.scale((float) wholeWidth / (float) webView.getContentWidth(), (float) wholeHeight / (float)webView.getContentHeight());
        if (webView.getX5WebViewExtension() == null) {
            return null;
        }
        IX5WebViewExtension ix5WebViewExtension = webView.getX5WebViewExtension();
        ix5WebViewExtension.snapshotWholePage(x5canvas, false, false);
        Bitmap bitmap = Bitmap.createBitmap(x5bitmap);
        return bitmap;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值