Convert UIWebview contents to a UIImage when the webview is larger than the screen

后端 未结 5 1168
孤城傲影
孤城傲影 2020-12-02 19:20

Very similar to this question (and also this answer), I\'m trying to make an UIImage out from a webview. So far I\'m using the code suggested in the answer, specifically: <

5条回答
  •  清歌不尽
    2020-12-02 20:20

    D R's answer is fine. The only thing missing is taking into account the scale of screen. I have it corrected in my Swift version and it works fine for me.

    extension UIWebView{
    func snapshotForCompletePage() -> UIImage {
        // tempframe to reset view size after image was created
        let tmpFrame: CGRect = self.frame
        // set full size Frame
        var fullSizeFrame: CGRect = self.frame
        fullSizeFrame.size.height = self.scrollView.contentSize.height
        self.frame = fullSizeFrame
    
        // here the image magic begins
        UIGraphicsBeginImageContextWithOptions(fullSizeFrame.size, false, UIScreen.mainScreen().scale)
        let resizedContext: CGContextRef = UIGraphicsGetCurrentContext()!
        self.layer.renderInContext(resizedContext)
        let image: UIImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        // reset Frame of view to origin
        self.frame = tmpFrame
        return image
          }
        }
    

提交回复
热议问题