WebView截取长图

一、在腾讯X5 webView中截取长图
实现代码如下:

/**
     * 腾讯X5 WebView截取长图
     *
     * @param context  上下文
     * @param mWebView 腾讯X5 WebView
     * @return 截取的长图
     */
    public static Bitmap webViewShot(Context context, WebView mWebView) {
        // 这里的 mWebView 就是 X5 内核的 WebView ,代码中的 longImage 就是最后生成的长图
        mWebView.measure(MeasureSpec.makeMeasureSpec(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED),
                MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
        mWebView.layout(0, 0, mWebView.getMeasuredWidth(), mWebView.getMeasuredHeight());
        mWebView.setDrawingCacheEnabled(true);
        mWebView.buildDrawingCache();
        Bitmap longImage = Bitmap.createBitmap(mWebView.getMeasuredWidth(),
                mWebView.getMeasuredHeight(), Bitmap.Config.ARGB_8888);
        // 画布的宽高和 WebView 的网页保持一致
        Canvas canvas = new Canvas(longImage);
        Paint paint = new Paint();
        canvas.drawBitmap(longImage, 0, mWebView.getMeasuredHeight(), paint);
        float scale = context.getResources().getDisplayMetrics().density;
        Bitmap x5Bitmap = Bitmap.createBitmap(mWebView.getWidth(), mWebView.getHeight(), Bitmap.Config.ARGB_8888);
        Canvas x5Canvas = new Canvas(x5Bitmap);
        x5Canvas.drawColor(Color.WHITE);
        // 少了这行代码就无法正常生成长图
        mWebView.getX5WebViewExtension().snapshotWholePage(x5Canvas, false, false);
        Matrix matrix = new Matrix();
        matrix.setScale(scale, scale);
        canvas.drawBitmap(x5Bitmap, matrix, paint);
        return longImage;
    }

二、更加通用的方法,但是影响性能
通过JS注入“document.body.offsetHeight”命令,获取网页高度
然后将webView的高度设置为此高度
自然webview就会将所有内容渲染出来
最后使用View.draw()即可

参考链接:Android截屏与WebView长图分享经验总结

猜你喜欢

转载自blog.csdn.net/a987687115/article/details/73917428