截取Android任意View的图像

最近开发中遇到了将webview截图并分享的需求,研究了webview的几个截图方法都没成功,最后用一个View通用的截图方法成功了,这里记录下来,以便今后查阅

 private Uri captureWebView(WebView webView){
        Uri uri=null;
        webView.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
        webView.layout(0,0,webView.getWidth(),webView.getHeight());
        Bitmap bm=webView.getDrawingCache();
        try {
            File file=new File("/sdcard/capture.jpg");
            FileOutputStream outputStream=new FileOutputStream(file);
            bm.compress(Bitmap.CompressFormat.JPEG,80,outputStream);
            uri= Uri.fromFile(file);
            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return uri;
    }


这个方法实际上对所有可视的View都通用,一般方法是:

  1. 从布局中得到View的对象;
  2. 打开图像缓存;
  3. 测量view的大小——view.measure();
  4. 发送位置和尺寸给自己及所有子view——view.layout();
  5. 从图像缓存中得到bitmap;
  6. 将图片处理成自己想要的格式;
后来经过查阅其他的资料,可以用view.buildDrawingCache();来完成第3、4步的工作了,所以更新后的截图的核心方法是这样的:
 view.setDrawingCacheEnabled(true);
        view.buildDrawingCache();
        Bitmap bitmap=view.getDrawingCache();



发布了41 篇原创文章 · 获赞 1 · 访问量 3万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章