以前使用UIWebview时,想截取整个页面,可以调整内部scrollView的frame,之后调用 scrollView的layer的 render 方法,很方便。

但是在WKWebView上,行不通。

我觉得以前的UIWebview其实是把整个页面都渲染在内存中,只是我们看不到。而WKWebView为了优化内存,只渲染WKWebView的Frame大小的内容。

所以想用WKWebview截取整个页面,必须放大WKWebview的frame。

 webView.frame = CGRect(x: , y: , width: webView.scrollView.frame.size.width, height: webView.scrollView.contentSize.height);

改变了frame之后,我们就可以利用scrollView.layer.render 去渲染整个页面了。

但是这时候又出现了另一个问题:  渲染网页是需要时间的,把webview的frame扩大后,我们不知道什么时候,系统完成了渲染。比如下面这个例子:

@IBAction func takeScreenshot(){

        webView.frame = CGRect(x: , y: , width: webView.scrollView.frame.size.width, height: webView.scrollView.contentSize.height);

            let scrollView = self.webView.scrollView

            UIGraphicsBeginImageContextWithOptions(self.webView.scrollView.contentSize,false, UIScreen.main.scale)

            scrollView.layer.render(in: UIGraphicsGetCurrentContext()!)

            let image = UIGraphicsGetImageFromCurrentImageContext()

            let pngData = UIImagePNGRepresentation(image!);

            let dstPath = NSHomeDirectory()+"/Documents/test.png"
let dstUrl = URL(fileURLWithPath: dstPath)
do{
try pngData?.write(to: dstUrl, options: .atomicWrite)
}catch{ } print("dest is %@",dstUrl); UIGraphicsEndImageContext()
}

由于立即调用了截图函数,webView没有足够的时间渲染,只多渲染了一小部分。

之后,我用下面的代码进行测试,注意,这里延时了0.3s,给了webview一定的渲染时间:

    @IBAction func takeScreenshot(){

        webView.frame = CGRect(x: , y: , width: webView.scrollView.frame.size.width, height: webView.scrollView.contentSize.height);

        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now()+0.3) {
let scrollView = self.webView.scrollView UIGraphicsBeginImageContextWithOptions(self.webView.scrollView.contentSize,false, UIScreen.main.scale) scrollView.layer.render(in: UIGraphicsGetCurrentContext()!) let image = UIGraphicsGetImageFromCurrentImageContext() let pngData = UIImagePNGRepresentation(image!); let dstPath = NSHomeDirectory()+"/Documents/test.png"
let dstUrl = URL(fileURLWithPath: dstPath)
do{
try pngData?.write(to: dstUrl, options: .atomicWrite)
}catch{ } print("dest is %@",dstUrl); UIGraphicsEndImageContext()
} }

下面是结果的截图,一切正常:

那么,如果网页更长,0.3秒一定也不够用,我们怎么知道该延时多少呢?

这时候我又发现了一个函数,是属于UIView的,drawHierarchy,根据api描述,第二个参数好像和渲染有关,能不能解决我们的问题呢,继续测试:

 @IBAction func takeScreenshot(){

        webView.frame = CGRect(x: , y: , width: webView.scrollView.frame.size.width, height: webView.scrollView.contentSize.height);

            let scrollView = self.webView.scrollView

            UIGraphicsBeginImageContextWithOptions(self.webView.scrollView.contentSize,false, UIScreen.main.scale)

            self.webView.drawHierarchy(in: CGRect(x: 0, y: 0, width: self.webView.scrollView.frame.size.width, height: self.webView.scrollView.contentSize.height), afterScreenUpdates: true)

            let image = UIGraphicsGetImageFromCurrentImageContext()

            let pngData = UIImagePNGRepresentation(image!);

            let dstPath = NSHomeDirectory()+"/Documents/test.png"
let dstUrl = URL(fileURLWithPath: dstPath)
do{
try pngData?.write(to: dstUrl, options: .atomicWrite)
}catch{ } print("dest is %@",dstUrl); UIGraphicsEndImageContext() }

结果还是不行,效果和使用layer的render方法一样!看来afterScreenUpdates这个参数跟网页的渲染无关了。

那么把Webview frame直接扩大为html内容的大小并截图的方式其实是很有问题的,截图时机不好掌握, 内存和cpu的占用也会很大。

这里要推荐一个github上的项目,https://github.com/startry/SwViewCapture, 它的解决思路如下:

1. 截图时机的掌握:每次通过调整视图frame,只渲染一屏的截图,速度很快,只需稍为延迟,即可保证完美截图。

2.内存和cpu:由于每次只处理一屏幕的截图,内容很少,对cpu和内存的冲击都很小。

下面贴出其中的关键代码:

 fileprivate func swContentPageDraw (_ targetView: UIView, index: Int, maxIndex: Int, drawCallback: @escaping () -> Void) {

        // set up split frame of super view
let splitFrame = CGRect(x: , y: CGFloat(index) * targetView.frame.size.height, width: targetView.bounds.size.width, height: targetView.frame.size.height)
// set up webview frame
var myFrame = self.frame
myFrame.origin.y = -(CGFloat(index) * targetView.frame.size.height)
self.frame = myFrame DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + Double(Int64(0.3 * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)) { () -> Void in targetView.drawHierarchy(in: splitFrame, afterScreenUpdates: true) if index < maxIndex {
self.swContentPageDraw(targetView, index: index + , maxIndex: maxIndex, drawCallback: drawCallback)
}else{
drawCallback()
}
}
}

用WKWebView 截取整个Html页面的更多相关文章

  1. iOS开发WKWebView 返回H5上级页面

    #pragma mark ---- 点击事件 -(void)leftTapClick:(UITapGestureRecognizer *)sender{ //判断是否能返回到H5上级页面 if (se ...

  2. WKWebView与JavaScript交互基础

    login.html 代码 <!DOCTYPE html> <html> <head> <title>使用JavaScript</title> ...

  3. iOS-JavaScript向WKWebView传值

    一.本地代码所需操作 1.创建viewController并遵守协议 @interface ViewController ()<WKNavigationDelegate,WKScriptMess ...

  4. 微信iOS WKWebview 网页开发适配指南

    微信iOS客户端将于2017年3月1日前逐步升级为WKWebview内核,需要网页开发者提前做好网站的兼容检查和适配. 背景 WKWebView 是苹果在iOS 8中引入的新组件,目的是提供一个现代的 ...

  5. EL表达式处理字符串 是否 包含 某字符串 截取 拆分...............

    EL表达式处理字符串 是否 包含 某字符串 截取 拆分............... JSP页面页头添加<%@ taglib uri="/WEB-INF/taglib/c.tld&qu ...

  6. iOS WKWebview 网页开发适配指南【转】

    微信iOS客户端将于2017年3月1日前逐步升级为WKWebview内核,需要网页开发者提前做好网站的兼容检查和适配.如有问题,可参考文末联系方式,向我们咨询. 背景 WKWebView 是苹果在iO ...

  7. phantomJs页面截图

    因为phantomjs使用了一个真正的渲染引擎WebKit,它能截取一个web页面的真实影像,这是因为phantomjs能够折射出WEB页面上的任何东西,包括html,css,svg和Canvas等. ...

  8. iOS WKWebview 网页开发适配指南

    iOS WKWebview 网页开发适配指南 微信iOS客户端将于2017年3月1日前逐步升级为WKWebview内核,需要网页开发者提前做好网站的兼容检查和适配.如有问题,可参考文末联系方式,向我们 ...

  9. 网易严选的wkwebview测试之路

    本文来自网易云社区 作者:孙娇 UIWebView是苹果继承于UIView封装的一个加载web内容的类,它可以加载任何远端的web数据展示在你的页面上,你可以像浏览器一样前进后退刷新等操作.不过苹果在 ...

随机推荐

  1. LeetCode 613. Shortest Distance in a Line

    Table point holds the x coordinate of some points on x-axis in a plane, which are all integers. Writ ...

  2. JAVA获取计算机CPU、硬盘、主板、网络等信息

    通过使用第三方开源jar包sigar.jar我们可以获得本地的信息 1.下载sigar.jar sigar官方主页 sigar-1.6.4.zip 2.按照主页上的说明解压包后将相应的文件copy到j ...

  3. JS中的块级作用域,var、let、const三者的区别

    1. 块作用域{ } <script type="text/javascript"> { var a = 1; console.log(a); // 1 } conso ...

  4. DAY15、模块

    一.函数的补充 1.函数回调: 提前在另一个函数中写出函数的调用,再根据实际的需求去考虑函数体的实现 def download(fn=None): print('开始下载') my_sleep(1) ...

  5. webBrowser兼容

    using Microsoft.Win32; using System; using System.Collections.Generic; using System.ComponentModel; ...

  6. 在Magento 2中创建管理员菜单

    在Magento 2中创建管理员菜单 第1步:创建menu.xml 第2步:添加菜单项 第3步:刷新Magento缓存 第1步:创建menu.xml 创建名为:menu.xml文件的管理菜单文件 ap ...

  7. macOS 上编译 Dynamips

    Dynamips 是一个Cisco 路由器模拟软件. 安装过程: git clone git://github.com/GNS3/dynamips.git cd dynamips mkdir buil ...

  8. Lua语法基础(二)

    1. 函数 1.1 函数声明 默认为全局 局部函数使用local关键字声明 1.2 参数 ...等同于Python中*args三个点表示可变参数 1.3 获取参数长度的两种方式 (1)将传入的参数.. ...

  9. BZOJ2870 最长道路

    题意:给定树,有点权.求一条路径使得最小点权 * 总点数最大.只需输出这个最大值.5w. 解:树上路径问题,点分治. 考虑合并两个子树的时候,答案的形式是val1 * (d1 + d2),当1是新插入 ...

  10. SQL Server数据库中表的增、删、改

    通过SqlCommand对象的ExecuteNonQuery方法执行命令行,来实现数据库中表的增.删.改.主要有5步 using System.Data.SqlClient;//载入数据库命名空间 p ...