效果图
//利用UIWebViewDelegate实现截取网页中的图片
extension ViewController:UIWebViewDelegate{
func webViewDidFinishLoad(_ webView: UIWebView) {
//这个方法是获取网页中的所有图片
//这里是js,主要目的实现对url的获取
let getImg = "function getImages(){ " +
"var objs = document.getElementsByTagName(\"img\");" +
"var imgScr = '';" +
"for(var i=0;i<objs.length;i++){" +
"imgScr = imgScr + objs[i].src + '+';" +
"};" +
"return imgScr;" +
"};"
self.articleWebView.stringByEvaluatingJavaScript(from: getImg)
let urlResurlt:String = webView.stringByEvaluatingJavaScript(from: "getImages()")!
let arr = NSMutableArray.init(array: urlResurlt.components(separatedBy: "+"))
// print(arr)
// 在H5页面加载完成时,注入图片点击的JS代码
let js = "function addImgClickEvent() { " +
"var imgs = document.getElementsByTagName('img');" +
// 遍历所有的img标签,统一加上点击事件
"for (var i = 0; i < imgs.length; ++i) {" +
"var img = imgs[i];" +
"img.onclick = function () {" +
// 给图片添加URL scheme,以便在拦截时可能识别跳转
"window.location.href = 'hyb-image-preview:' + this.src;" +
"}" +
"}" +
"}"
// 注入JS代码
self.articleWebView.stringByEvaluatingJavaScript(from: js)
// 执行所注入的JS
self.articleWebView.stringByEvaluatingJavaScript(from: "addImgClickEvent();")
}
func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
let requestString:String = (request.url?.absoluteString)!
let scheme = "hyb-image-preview:"
if requestString.hasPrefix(scheme) {
// 获取原始图片的URL
let path:String = (request.url?.absoluteString.substring(from: scheme.endIndex))!
// let src = request.url?.absoluteString.replacingOccurrences(of: scheme, with: "")
//
// print(src)
showBigImage(imageUrl: path)
return false
}
return true
}
//接收并展示图片
func showBigImage(imageUrl:String) {
//一定要写这一句,不然只能预览一次图片
self.bgView.isHidden = false
self.view.addSubview(self.bgView)
bgView.backgroundColor = UIColor(red:0.3 , green: 0.3, blue: 0.3, alpha: 0.7)
let imageView = UIImageView(frame: CGRect(x: 0, y: SCREENW/2, width: SCREENW, height: 240))
imageView.isUserInteractionEnabled = true
imageView.cz_setImage(urlString:imageUrl, placeholderImage: nil)
self.bgView.addSubview(imageView)
self.bgView.addOnClickListener(target: self, action: #selector(closeClick))
bgView.addSubview(closeBtn)
}
//关闭图片
func closeClick() {
self.bgView.isHidden = true
}
}
网友评论