Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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:

UIGraphicsBeginImageContext(webview.bounds.size);
[webview.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

However, when the contents of the webview are larger than the screen, the resulting images are not complete and have missing patches. Any ideas on how to fix this?

like image 205
Matt Blackmon Avatar asked Dec 17 '10 22:12

Matt Blackmon


2 Answers

@Jibeex's answer worked for me. But I had to add the following code

    fullSizeFrame.size.width = self.scrollView.contentSize.width

below

    fullSizeFrame.size.height = self.scrollView.contentSize.height

for it to fully work. Writing as answer because I don't have enough reputation to comment.

like image 77
arun Avatar answered Oct 14 '22 01:10

arun


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
      }
    }
like image 44
Jibeex Avatar answered Oct 14 '22 03:10

Jibeex