温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

iOS如何实现对当前webView进行截屏

发布时间:2021-07-09 09:23:33 来源:亿速云 阅读:147 作者:小新 栏目:移动开发

这篇文章给大家分享的是有关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提供了一种解决思路是使用UIView的drawViewHierarchyInRect方法去截取屏幕视图。通过直接调用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! 
  }

感谢各位的阅读!关于“iOS如何实现对当前webView进行截屏”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,让大家可以学到更多知识,如果觉得文章不错,可以把它分享出去让更多的人看到吧!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI