Android原生WebView截图(支持缩放)

Android原生WebView截图,支持Android 5.0及以上,支持缩放

/**
 * 缩放图
 * @param context
 * @param webView
 */
public static void captureScaleWebViewLollipop(final Context context, final WebView webView) {
    final float scale = webView.getScale();
    final int height = (int) (webView.getContentHeight() * scale);
    final int width = (int) (webView.getWidth() * scale);
    if (scale > 3) {
        NToasty.shortToastError(context, context.getResources().getString(R.string.webview_scale_too_large));
        return;
    }
    new Handler().postDelayed(new Runnable() {
        @Override
        public void run() {
            Log.i("yezhou", "width: " + width + ", height: " + height + ", scale: " + scale);
            int pH = webView.getHeight();
            int pW = webView.getWidth();
            final Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
            Canvas canvas = new Canvas(bitmap);
            int top = 0;
            int left = 0;
            while (top < height) {
                left = 0;
                while (left < width) {
                    canvas.save();
                    if (left + pW < width && top + pH < height) {
                        canvas.clipRect(left, top, left + pW, top + pH);
                        //因缩放后内容宽高大概率不是WebView宽高的整数倍,导致末端无法滑动至此位置
                        webView.scrollTo(left, top);
                    } else if (left + pW > width && top + pH < height) {
                        canvas.clipRect(width - pW, top, width, top + pH);
                        webView.scrollTo(width - pW, top);
                    } else if (left + pW < width && top + pH > height) {
                        canvas.clipRect(left, height - pH, left + pW, height);
                        webView.scrollTo(left, height - pH);
                    } else {
                        canvas.clipRect(width - pW, height - pH, width, height);
                        webView.scrollTo(width - pW, height - pH);
                    }
                    webView.draw(canvas);
                    canvas.restore();
                    left += pW;
                }
                top += pH;
            }
            saveWebViewBitmap(context, bitmap);
        }
    }, 100);
}

版权声明:
作者:Joe.Ye
链接:https://www.appblog.cn/index.php/2023/03/11/android-native-webview-screenshot-supports-scaling/
来源:APP全栈技术分享
文章版权归作者所有,未经允许请勿转载。

THE END
分享
二维码
打赏
海报
Android原生WebView截图(支持缩放)
Android原生WebView截图,支持Android 5.0及以上,支持缩放 /** * 缩放图 * @param context * @param webView */ public static void captureScaleWebVie……
<<上一篇
下一篇>>
文章目录
关闭
目 录