Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Render off-screen WKWebView into NSImage

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?

like image 381
Era Avatar asked May 10 '15 08:05

Era


1 Answers

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.

like image 80
George Brown Avatar answered Oct 01 '22 18:10

George Brown