8

I've tried rendering an offscreen WKWebView into an image using

  • func cacheDisplayInRect(rect: NSRect, toBitmapImageRep bitmapImageRep: NSBitmapImageRep)
  • and func drawLayer(layer: CALayer, inContext ctx: CGContext)

without success. The resulting image is always empty (white or transparent). Has anyone managed to do this on Yosemite?

Stefan Arentz
  • 34,311
  • 8
  • 67
  • 88

1 Answers1

2

You can do it using drawViewHierarchyInRect: none of the other methods seem to work, use it like so:

UIGraphicsBeginImageContextWithOptions(newRect.size, YES, 0);
BOOL ok = [view drawViewHierarchyInRect:newRect afterScreenUpdates:YES];
if (!ok) {
    NSLog(@"Problem with drawView...");
}
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

I'm doing the same in iOS, but unfortunately this method is slow, must also be run in the main thread and only works if afterScreenUpdates is set to yes. See this answer : How can I take a snapshot of a UIView that isn't rendered?

Also there's no way to tell, from what I can see, if any aspect of the webpage needs redrawing.

Community
  • 1
  • 1
George Brown
  • 1,134
  • 10
  • 25
  • I didn't know `UIKit` was available on macOS? ;) –  Oct 19 '16 at 08:35
  • Ah ha, yes, well spotted. I share a lot of code between iOS and MacOS but clearly forgot about the differences in UIView and NSView. I think I looked into at some point and the answer seemed to be in using chromium to do offscreen stuff, but 3rd party browser code is strictly disallowed in iOS. Perhaps it's worth looking into that. – George Brown Oct 19 '16 at 21:04