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);
}
上一篇 Android原生WebView截图
下一篇 Android中DexClassLoader和PathClassLoader的区别
目录
文章列表
1 Android NDK基础18:C++_构造函数_析构函数_拷贝构造函数
Android NDK基础18:C++_构造函数_析构函数_拷贝构造函数
2
React Native学习之ActionSheetIOS API
React Native学习之ActionSheetIOS API
3
Android Activity启动模式简单总结
Android Activity启动模式简单总结
4
Python搭建HTTP服务器:Windows下使用virtualenv安装Flask
Python搭建HTTP服务器:Windows下使用virtualenv安装Flask
5
CompletableFuture 使用详解
CompletableFuture 使用详解
最新评论
一位WordPress评论者
一位WordPress评论者
2月12日
您好,这是一条评论。若需要审核、编辑或删除评论,请访问仪表盘的评论界面。评论者头像来自 Gravatar。