Android WebView的位图为空白

时间:2014-07-04 13:03:20

标签: android webview bitmap screenshot

我试图截取Android WebView的截图,结果是一张空白图片。我知道有很多关于这方面的问题,但是每个人似乎都以这样或那样的方式解决了这个问题而我无法解决。

我试过了:

  • draw()方法
  • capturePicture()方法,现已弃用。

WebView正确呈现 ,但当我分享图片时,它是空白的。

这是我的截图类:

public class Screenshot {
    private final View view;

    /** Create snapshots based on the view and its children. */
    public Screenshot(View root) {
        this.view = root;
    }

    /** Create snapshot handler that captures the root of the whole activity. */
    public Screenshot(Activity activity) {
        final View contentView = activity.findViewById(android.R.id.content);
        this.view = contentView.getRootView();
    }

    /** Take a snapshot of the view. */
    public Bitmap snap() {
        Bitmap bitmap = Bitmap.createBitmap(this.view.getWidth(),
                this.view.getHeight(), Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        view.draw(canvas);

        return bitmap;
    }

    public Uri snapAndSave(File cacheDir) {
        File outputFile;
        try {
            outputFile = File.createTempFile("myfile", ".png", cacheDir);
            if (savePic(snap(), outputFile)) {
                return Uri.fromFile(outputFile);
            } else {
                return null;
            }

        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }

    }

    public static boolean savePic(Bitmap b, File outputFile) {
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(outputFile);
            if (null != fos) {
                b.compress(Bitmap.CompressFormat.PNG, 90, fos);
                fos.flush();
                fos.close();
            }
            return true;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return false;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }
}

1 个答案:

答案 0 :(得分:1)

可以使用getDrawingCache()方法捕获WebView:

public Bitmap getBitmapFromWebView(WebView webView) {
    webView.setDrawingCacheEnabled(true);
    webView.buildDrawingCache(true);
    Bitmap bitmap = Bitmap.createBitmap(webview.getDrawingCache());
    webView.setDrawingCacheEnabled(false);
    return bitmap;
}