WKWebView获取网页图片并原生放大

1、WKWebView添加UITapGestureRecognizer
2、根据手势点击位置坐标获取网页图片资源
3、使用原生工具放大图片
上代码:

//定义tapGesture      
 lazy var tapGesture : UITapGestureRecognizer = {
        let tap = UITapGestureRecognizer.init(target: self, action:   #selector(handleSingleGesture))
        tap.cancelsTouchesInView = false
        return tap
    }()
    override func viewDidLoad() {
         .....
        self.webView.addGestureRecognizer(self.tapGesture)
        self.tapGesture.delegate = self
 
 }
//手势方法
     @objc func handleSingleGesture(gr:UITapGestureRecognizer) {
         let point = gr.location(in: self.webView)
         let imgURL = "document.elementFromPoint(\(point.x),\(point.y)).src"
        self.webView.evaluateJavaScript(imgURL) { [weak self](data, error) in
            guard self != nil else {return}
            let url = data as? String
           guard url != nil else {return}
            self!.browserImage(url: url! )
        }
    } 
//浏览图片,这里使用的SKPhoto框架
func browserImage(url:String) {
        var images = [SKPhoto]()
        let photo = SKPhoto.photoWithImageURL(url)
        photo.shouldCachePhotoURLImage = true // you can use image cache by true(NSCache)
        images.append(photo)
        
        // 2. create PhotoBrowser Instance, and present.
        let browser = SKPhotoBrowser(photos: images)
        browser.initializePageIndex(0)
        present(browser, animated: true, completion: {})
    }
//MARK:UIGestureRecognizerDelegate
 func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
        return true
    }
    



你可能感兴趣的:(WKWebView获取网页图片并原生放大)