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:
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
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.