Search code examples
iosuikituiimagescreenshot

ScreenShot of an UIWebView that is not currently on screen


I'm trying to generate thumbnails of several pages that will be displayed through a UIWebView. The problem is all of the images come out as gray or as the background color I set for the UIWebView. Could it be that I am not allowing the web view enough time to load the page?

I believe I want to do the following:

  1. Create a UIWebView that is not visible on the screen
  2. Setup graphics context
  3. For each page:
    • Call loadRequest on the web view
    • Render web view in graphics context
    • capture screenshot
  4. End graphic context

Here is the code I have for a single image:

UIWebView *screenWebView = _screenshotWebView;
UIView *screenView = _screenshotView;

if ([UIScreen instancesRespondToSelector:@selector(scale)] && [[UIScreen mainScreen] scale] == 2.0f) {
    UIGraphicsBeginImageContextWithOptions(screenView.bounds.size, NO, 2.0f);
} else {
    UIGraphicsBeginImageContext(screenView.bounds.size);
}

[screenWebView loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:path ofType:@"html"]isDirectory:NO]]];


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

I defined _screenshotWebView and _screenshotView within a XIB file because I thought I may not have been initializing them correctly.

Any thoughts? Thanks!

Edit: Here is some code that implements this functionality in case someone else needs it: https://github.com/rmcl/webview_screenshot


Solution

  • As you theorized, there isn't time for the UIWebView to load the page. That method will asynchronously start the page load; the UIWebView probably won't get a chance to do any work until you've returned to the run loop.

    Try implementing webViewDidFinishLoad: and do your rendering after it has completed.