首先导入头文件
import WebKit
上代码初始化webView,和触发事件按钮
let webConfig = WKWebViewConfiguration()
webView = WKWebView.init(frame:self.view.bounds, configuration: webConfig)
webView.backgroundColor = .red
let urlRequest = URLRequest.init(url: URL.init(string: "https://www.baidu.com")!)
webView.load(urlRequest)
self.view.addSubview(webView)
let btn = UIButton.init(frame: CGRect.init(x:0, y: self.view.bounds.height-50, width: self.view.bounds.width, height: 50))
btn.setTitle("获取截图", for: .normal)
btn.backgroundColor = .red
btn.addTarget(self, action: #selector(ViewController.snapshot), for: .touchUpInside)
self.view.addSubview(btn)
事件
@objc func snapshot()->(){
let snapConfig = WKSnapshotConfiguration.init()
// 设置获取截图的范围
snapConfig.rect = self.view.bounds
//获取截图
webView.takeSnapshot(with: snapConfig) { (image, error) in
print(image as Any)
//保存到相册
//别忘了plist里面 添加NSPhotoLibraryAddUsageDescription字段
UIImageWriteToSavedPhotosAlbum(image!, nil, nil, nil)
let alert = UIAlertController.init(title: "提示", message: "截图已保存到相册", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
界面效果如下
赏个喜欢😍再走啊~~~
网友评论