Rendering a UIWebView into an ImageContext

前端 未结 6 1143
伪装坚强ぢ
伪装坚强ぢ 2020-12-14 12:33

I am trying to capture the contents of a UIWebView including that which is not visible to the user. i.e. The whole web page even though the user is only looking at the top.<

6条回答
  •  隐瞒了意图╮
    2020-12-14 13:14

    Resizing the Webview is the way I solved it. If you want a bigger image with more detail, you just have to zoom in before calling this method. Beware that large dimensions could infulence the performance.

    - (UIImage*) imageFromWebview:(UIWebView*) webview{
    
    //store the original framesize to put it back after the snapshot
    CGRect originalFrame = webview.frame;
    
    //get the width and height of webpage using js (you might need to use another call, this doesn't work always)
    int webViewHeight = [[webview stringByEvaluatingJavaScriptFromString:@"document.body.scrollHeight;"] integerValue];
    int webViewWidth = [[webview stringByEvaluatingJavaScriptFromString:@"document.body.scrollWidth;"] integerValue];
    
    //set the webview's frames to match the size of the page
    [webview setFrame:CGRectMake(0, 0, webViewWidth, webViewHeight)];
    
    //make the snapshot
    UIGraphicsBeginImageContextWithOptions(webview.frame.size, false, 0.0);
    [webview.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    //set the webview's frame to the original size
    [webview setFrame:originalFrame];
    
    //and VOILA :)
    return image;
    

    }

提交回复
热议问题