Bitmap of Android WebView is blank

2019-07-22 04:40发布

问题:

I'm trying to take a screenshot of an Android WebView and the result is a blank image. I know there are lots of questions about this but everyone seems to have resolved it in a way or another and I can't.

I tried:

  • the draw() method
  • the capturePicture() method, now deprecated.

The WebView renders properly, but when I share the picture it's blank.

This is my screenshot class:

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:

WebView can be capture with the getDrawingCache() method:

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