有谁知道如何使用swift中的代码(不是屏幕,因为webview很长,我们必须滚动查看所有内容)并通过{{1}分享我的所有网页视图的完整屏幕截图}?
答案 0 :(得分:7)
加载网页视图后尝试以下代码:
已编辑:在模拟器中运行此代码,然后检查文档应用程序目录中的screenshot.jpeg文件
class ViewController: UIViewController,UIWebViewDelegate {
let fileDirectory = NSSearchPathForDirectoriesInDomains(
.DocumentDirectory, .UserDomainMask, true)
@IBOutlet weak var webView: UIWebView!
override func viewDidLoad() {
var urlPath = "http://www.bbc.com/"
let requestUrl = NSURL(string: urlPath)
let request = NSURLRequest(URL: requestUrl!)
webView.loadRequest(request)
webView.delegate = self
}
func webViewDidFinishLoad(webView: UIWebView) {
if (!webView.loading){
var webViewFrame = webView.frame
webView.frame = CGRectMake(webViewFrame.origin.x, webViewFrame.origin.y, webView.scrollView.contentSize.width, webView.scrollView.contentSize.height)
UIGraphicsBeginImageContextWithOptions(webView.scrollView.contentSize, false, 0);
self.webView.layer.renderInContext(UIGraphicsGetCurrentContext())
var image:UIImage = UIGraphicsGetImageFromCurrentImageContext();
var imageData = UIImageJPEGRepresentation(image, 0.7)
var currentFileName = "screenshot.jpeg"
var imageFilePath = fileDirectory[0].stringByAppendingPathComponent(currentFileName)
var imageFileURL = NSURL(fileURLWithPath: imageFilePath)
imageData.writeToURL(imageFileURL!, atomically: false)
webView.frame = webViewFrame
}
}
}
答案 1 :(得分:0)
在Swift 5中使用WKWebView
解决方案
extension ViewController: WKNavigationDelegate {
func webView(_ webView: WKWebView,didFinish navigation: WKNavigation!) {
let configuration = WKSnapshotConfiguration()
configuration.rect = CGRect(origin: .zero, size: (self.webView.scrollView.contentSize))
webView.takeSnapshot(with: configuration) {image, error in
if let image = image {
self.saveImage(imageName: "snapshot.jpg", image: image)
}
}
}
}