import UIKit

/* 참고자료
 https://netcanis.tistory.com/5
 */

extension WKWebView {
    
    // 화면에 보여지는 부분만 스크린샷 이미지 생성
    func screenshot(_ completionBlock: ((UIImage) -> Void)?) {
        if #available(iOS 11.0, *) {
            let config = WKSnapshotConfiguration()
            if #available(iOS 13.0, *) {
                config.afterScreenUpdates = false
            }
            
            config.rect = CGRect(x: 0, y: 0, width: self.frame.width, height: self.frame.height)//self.frame
            
            self.takeSnapshot(with: config) { image, error in
                if error != nil {
                    print("\(String(describing: error))")
                    return
                }
                guard let image = image else { return }
                completionBlock?(image)
            }
        } else {
            UIGraphicsBeginImageContextWithOptions(self.bounds.size, true, UIScreen.main.scale)
            self.drawHierarchy(in: self.bounds, afterScreenUpdates: true)
            
            guard let image = UIGraphicsGetImageFromCurrentImageContext() else { return }
            
            completionBlock?(image)
        }
    }
}

+ Recent posts