用WKWebView 截取整个Html页面
以前使用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页面的更多相关文章
- iOS开发WKWebView 返回H5上级页面
#pragma mark ---- 点击事件 -(void)leftTapClick:(UITapGestureRecognizer *)sender{ //判断是否能返回到H5上级页面 if (se ...
- WKWebView与JavaScript交互基础
login.html 代码 <!DOCTYPE html> <html> <head> <title>使用JavaScript</title> ...
- iOS-JavaScript向WKWebView传值
一.本地代码所需操作 1.创建viewController并遵守协议 @interface ViewController ()<WKNavigationDelegate,WKScriptMess ...
- 微信iOS WKWebview 网页开发适配指南
微信iOS客户端将于2017年3月1日前逐步升级为WKWebview内核,需要网页开发者提前做好网站的兼容检查和适配. 背景 WKWebView 是苹果在iOS 8中引入的新组件,目的是提供一个现代的 ...
- EL表达式处理字符串 是否 包含 某字符串 截取 拆分...............
EL表达式处理字符串 是否 包含 某字符串 截取 拆分............... JSP页面页头添加<%@ taglib uri="/WEB-INF/taglib/c.tld&qu ...
- iOS WKWebview 网页开发适配指南【转】
微信iOS客户端将于2017年3月1日前逐步升级为WKWebview内核,需要网页开发者提前做好网站的兼容检查和适配.如有问题,可参考文末联系方式,向我们咨询. 背景 WKWebView 是苹果在iO ...
- phantomJs页面截图
因为phantomjs使用了一个真正的渲染引擎WebKit,它能截取一个web页面的真实影像,这是因为phantomjs能够折射出WEB页面上的任何东西,包括html,css,svg和Canvas等. ...
- iOS WKWebview 网页开发适配指南
iOS WKWebview 网页开发适配指南 微信iOS客户端将于2017年3月1日前逐步升级为WKWebview内核,需要网页开发者提前做好网站的兼容检查和适配.如有问题,可参考文末联系方式,向我们 ...
- 网易严选的wkwebview测试之路
本文来自网易云社区 作者:孙娇 UIWebView是苹果继承于UIView封装的一个加载web内容的类,它可以加载任何远端的web数据展示在你的页面上,你可以像浏览器一样前进后退刷新等操作.不过苹果在 ...
随机推荐
- 通过sort()方法实现升序和降序排列
数组 升序:Arrays.sort(arr); 降序: 方法一:Arrays.sort(arr,Collections.reverseOrder()); 方法二: package com.yh.sor ...
- 复杂度定义 The Definition of Complexity
The upper bound Big-O: Definition: f(n) is in O(g(n)) if there are constants c0 and N0 such that f ...
- System.nanoTime与System.currentTimeMillis的区别(转)
原文地址:http://blog.csdn.net/dliyuedong/article/details/8806868 平时产生随机数时我们经常拿时间做种子,比如用System.currentTim ...
- RPC----Hadoop核心协议
什么是RPC RPC设计的目的 RPC的作用 远程过程调用(RPC)是一个协议,程序可以使用这个协议请求网络中另一台计算机上某程序的服务而不需要知道网络细节. 必备知识: 网络七层模型 网络四层模型 ...
- 《Effective C++》继承与面对对象设计:条款32-条款40
条款32:确定你的public继承塑模出is-a关系 public继承意味着is-a.适用于base class身上的每一个函数也一定适用于derived class. 条款33:避免遮掩继承而来的名 ...
- JDBC数据库连接池之dbcp
一.连接池的作用 数据库的连接是一种很重要的资源,如果一个项目比较小,连接数据库的次数比较少,我们可以采取直连的方式:“获取连接----使用----关闭连接”.但是如果一个网站访问量很大,假如同时有几 ...
- golang函数
一.函数语法 func 函数名(形参列表) (返回值列表){ ...... return 返回值 } 例如: package main import "fmt" func test ...
- block,inline,inline-block区别
block:多個元素豎直排列,每個元素單獨占一行,寬高可以設置,padding.margin可以設置: inline:多個元素占一行,一行放不下了,才轉入下一行,寬高不能設置,水平的padding.m ...
- Python——collections模块(扩展数据类型)
1.namedtuple:利用坐标.空间坐标,扑克牌等指定空间位置 # namedtuple('名字',[list列表属性])from collections import namedtuple Po ...
- magento 2 Check https://getcomposer.org/doc/articles/troubleshooting.md#memory-limit-errors for more info on how to handle out of memory errors.%
Check https://getcomposer.org/doc/articles/troubleshooting.md#memory-limit-errors for more info on h ...