iOS 对当前webView进行截屏

UIWebView和WKWebView的截屏有所区别:

UIWebView:

func getImage(context: ServiceExecuteContext) -> UIImage {
        //创建一个基于位图的图形上下文并指定大小
        UIGraphicsBeginImageContextWithOptions(context.fromViewController.webView.bounds.size, true, 0)
        //renderInContext呈现接受者及其子范围到指定的上下文
        context.fromViewController.webView.layer.renderInContext(UIGraphicsGetCurrentContext()!)
        //返回一个基于当前图形上下文的图片
        let image = UIGraphicsGetImageFromCurrentImageContext()
        //移除栈顶的基于当前位图的图形上下文
        UIGraphicsEndImageContext()
        
        //let imagRef = CGImageCreateWithImageInRect((image?.CGImage)!, context.fromViewController.webView.bounds)
        //let newImage = UIImage.init(CGImage: imagRef!)
        //UIImageWriteToSavedPhotosAlbum(newImage, nil, nil, nil);//保存图片到照片库
        return image!
    }

    UIGraphicsBeginImageContext()方法传入唯一参数,是一个CGSize变量,用来指定图形context的大小,所以获取屏幕截图的时候这个size该是屏幕的大小。其实了解了这个过程,就知道这个方法可以获取任意区域的截图,当然是必须当前页面的一部分。你需要截取哪个view的图像,就让这个view的layer调用renderInContext把图形渲染进当前图形context。

 

 

 WKWebView:

    当我尝试去截取WKWebView的图。截图的结果返回给我的就仅仅只是一张背景图, 显然截图失败。通过搜索StackOverflow和Google, 我发现WKWebView并不能简单的使用layer.renderInContext的方法去绘制图形。如果直接调用layer.renderInContext需要获取对应的Context, 但是在WKWebView中执行UIGraphicsGetCurrentContext()的返回结果是nil

     StackOverflow提供了一种解决思路是使用UIViewdrawViewHierarchyInRect方法去截取屏幕视图。通过直接调用WKWebView的drawViewHierarchyInRect方法(afterScreenUpdates参数必须为true), 可以成功的截取WKWebView的屏幕内容

func getImage(context: ServiceExecuteContext) -> UIImage {
        
        UIGraphicsBeginImageContextWithOptions(context.fromViewController.webView.bounds.size, true, 0)
        for subView: UIView in context.fromViewController.webView.subviews {
            subView.drawViewHierarchyInRect(subView.bounds, afterScreenUpdates: true)
        }
        //UIApplication.sharedApplication().keyWindow?.layer.renderInContext(UIGraphicsGetCurrentContext()!)
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        
        //let imagRef = CGImageCreateWithImageInRect((image?.CGImage)!, context.fromViewController.webView.bounds)
        //let newImage = UIImage.init(CGImage: imagRef!)
        
        return image!
    }

  

http://blog.csdn.net/haoziy1989511/article/details/50856178

 

 

转载于:https://www.cnblogs.com/Walking-Jin/p/6626425.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值