直接在NSView中绘图,而不使用draw(_updateRect:NSRect)函数



我想直接在View中绘制CGImage图片,使用draw函数的常规方法,我在新的Mac Book Pro上一秒钟只能获得7张图片。所以我决定使用updateLayer函数。我已经定义了wantsUpdateLayer=true,并且我的新updateLayer函数会按预期调用。但这就开始了我的问题。当使用draw函数时;NSGraphicsContext.current?。cgContext";但是在我的updateLayer函数中;NSGraphicsContext.current?。cgContext";为零。所以我不知道把我的CGImage放在哪里,它会显示在我的屏幕上。此外;自我观点?。窗graphicsContext?。cgContext";以及";self-window?。graphicsContext?。cgContext";也为零。此视图中没有按钮或其他元素,在视图的窗口中,只有一张图片,填充了整个窗口。这张照片必须在一秒钟内改变30次。生成图片是由一个单独的线程完成的,一张图片大约需要1毫秒。我认为从";外部";NSView类不可能写图片,但我的updateLayer函数在该类中。

以下是函数的实际外观:

override func updateLayer ()
{
let updateRect: NSRect = NSRect(x: 0.0, y: 0.0, width: 1120.0, height: 768.0)
let context1 = self.view?.window?.graphicsContext?.cgContext
let context2 = self.window?.graphicsContext?.cgContext
let context3 = NSGraphicsContext.current?.cgContext
}

在我设置needsDisplay标志后自动调用函数时,这三个上下文都为零。

有什么想法在哪里画我的CGImages吗?

updateLayer函数由用户界面自动调用。我不会手动调用它。它由视图调用。我的问题是,在这个方法中,把我的照片放在屏幕上的什么地方。也许我必须添加一个图层或使用视图的默认图层,但我不知道如何做到这一点。

同时,我从一位好朋友那里找到了一些小费的解决方案:

override var wantsUpdateLayer: Bool
{ 
return (true)
}
override func updateLayer ()
{
let cgimage: CGImage? = picture // Here comes the picture
if cgimage != nil
{
let nsimage: NSImage? = NSImage(cgImage: cgimage!, size: NSZeroSize)
if nsimage != nil
{
let desiredScaleFactor: CGFloat? = self.window?.backingScaleFactor
if desiredScaleFactor != nil
{
let actualScaleFactor: CGFloat? = nsimage!.recommendedLayerContentsScale(desiredScaleFactor!)
if actualScaleFactor != nil
{
self.layer!.contents      = nsimage!.layerContents(forContentsScale: actualScaleFactor!)
self.layer!.contentsScale = actualScaleFactor!
}
}

}
}
}

这是直接写入图层的方法。根据格式(CGImage或NSImage(,您首先必须转换它。一旦func wantsUpdateLayer返回true,就会使用func updateLayer((而不是func draw((。仅此而已。

对于所有想看我的";"正常";绘图功能:

override func draw (_ updateRect: NSRect)
{
let cgimage: CGImage? = picture // Here comes the picture
if cgimage != nil
{
if #available(macOS 10.10, *)
{
NSGraphicsContext.current?.cgContext.draw(cgimage!, in: updateRect)
}
}
else
{
super.draw(updateRect)
}
}

额外的速度是2倍或更多,这取决于您使用的硬件。在现代的Mac Pro上,速度只有一点点提高,但在现代的MacBook Pro上,你会获得10倍或更多的速度。这适用于莫哈韦10.14.6和卡塔琳娜10.15.6。我没有用旧的macOS版本测试它。";"正常";draw函数适用于10.10.6到10.15.6。

最新更新