m b m b - 1 year ago 76
iOS Question

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:

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

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?

Answer Source

I got the answer:

You have to set the frame of the Webview to the full content size just before you create the image. After this just set the size back to origin:

+ (UIImage *) imageFromWebView:(UIWebView *)view
    // tempframe to reset view size after image was created
    CGRect tmpFrame         = view.frame;

    // set new Frame
    CGRect aFrame               = view.frame;
    aFrame.size.height  = [view sizeThatFits:[[UIScreen mainScreen] bounds].size].height;
    view.frame              = aFrame;

    // do image magic
    UIGraphicsBeginImageContext([view sizeThatFits:[[UIScreen mainScreen] bounds].size]);

    CGContextRef resizedContext = UIGraphicsGetCurrentContext();
    [view.layer renderInContext:resizedContext];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();


    // reset Frame of view to origin
    view.frame = tmpFrame;
    return image;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download