WebView截取长图

现在好多APP的分享多了个“长图文分享”,自己在开发中也遇到了这个需求,正好作个记录吧

1. Android5.0以下版本

通过google提供的Api就可以轻易实现需求:

private static Bitmap captureWebViewKitKat(WebView webView) {
        Picture picture = webView.capturePicture();
        int width = picture.getWidth();
        int height = picture.getHeight();
        if (width > 0 && height > 0) {
            Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_888);
            Canvas canvas = new Canvas(bitmap);
            picture.draw(canvas);
            return bitmap;
        }
        return null;
    }
}

2. Android5.0以上版本

依然使用上面的方法就会遇到一个问题——只截取到可见部分的内容,其他的全部为空白。原来,在Android5.0及以上版本,Android对WebView进行了优化,为了减少内存使用和提高性能,使用WebView加载网页时只绘制显示部分。Google也提供了关闭这个优化的方法,请看:

//在webview实例化前调用
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
    android.webkit.WebView.enableSlowWholeDocumentDraw();
}

//示例代码,没做异步处理
private void captureWebView(WebView webView) {
    float scale = webView.getScale();
    int width = webView.getWidth();
    int height = (int) (webView.getContentHeight() * scale + 0.5);
    Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_888);
    Canvas canvas = new Canvas(bitmap);
    webView.draw(canvas);
    File f = new File(Environment.getExternalStorageDirectory(),"capture.jpg");
    try {
         if(!f.createNewFile()) {
             System.out.println("File already exists");
         }
     } catch (IOException ex) {

     }
     writeBitmapToFile(bitmap,f);

}



public static boolean writeBitmapToFile(Bitmap bitmap, File path) {
        boolean isCompress = false;
        FileOutputStream out = null;
        try {
            out = new FileOutputStream(path);
            if (path.getName().toLowerCase().endsWith(".jpg")) {
                isCompress = bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
            } else {
                isCompress = bitmap.compress(Bitmap.CompressFormat.PNG, 90, out);
            }
            out.flush();
            out.close();
        } catch (Exception e) {

        } finally {
            try {
                if (out != null) {
                    out.close();
                }
            } catch (IOException ioe) {
                // ignore
            }
        }
        return isCompress;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值