将屏幕外WKWebView渲染到NSImage中

Eri*_*ner 6 macos cocoa wkwebview

我已经尝试过将屏幕外渲染WKWebView成图像

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

没有成功.生成的图像始终为空(白色或透明).有没有人设法在优胜美地上做到这一点?

Geo*_*own 2

您可以使用 drawViewHierarchyInRect 来完成此操作:其他方法似乎都不起作用,请像这样使用它:

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

我在 iOS 中做了同样的事情,但不幸的是这个方法很慢,也必须在主线程中运行,并且只有当 afterScreenUpdates 设置为 yes 时才有效。请参阅此答案:How can I take a snapshot of a UIView that isn't rendered?

此外,从我所看到的情况来看,无法判断网页的任何方面是否需要重新绘制。