Android WebView的位图为空 [英] Bitmap of Android WebView is blank

查看:57
本文介绍了Android WebView的位图为空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试截取Android WebView的屏幕截图,结果是空白图像.我知道对此有很多疑问,但是每个人似乎都已经以某种方式解决了它,但我做不到.

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.

我尝试过:

  • draw()方法
  • capturePicture()方法(现已弃用).
  • the draw() method
  • the capturePicture() method, now deprecated.

WebView会正确显示 ,但是当我共享图片时,它是空白的.

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;
        }
    }
}

推荐答案

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

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;
}

这篇关于Android WebView的位图为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆