How to draw to a NSView from a Core Video DisplayLink thread?

I have a DLP-Link 3D projector which I'd like to make use of by means of a hand-made player.

So far in my project: A class MovieView : NSView within a NSWindow, with stub drawing codes.

I know that, if I place drawing codes in the func draw(...) function, then NSGraphicsContext.current will be set up for me to use. But I'm drawing from a high-priority thread (the DisplayLink), so I obviously have to set it up myself.

How should I do that in Swift?

Answered by DannyNiu-NJF in 719506022

Prepare all the graphical assets in the DisplayLink thread, and asynchronously mark the view as need updating with:

DispatchQueue.main.async {
    view.needsDisplay = true
}

Then do as little as possible and as much as necessary in draw to draw the contents.

Remarks

  • The context to which drawing commands are issued to is not static - it's instantiated on-demand.

  • NSView have the requirement that many of its interfaces be invoked only on the main thread.

Accepted Answer

Prepare all the graphical assets in the DisplayLink thread, and asynchronously mark the view as need updating with:

DispatchQueue.main.async {
    view.needsDisplay = true
}

Then do as little as possible and as much as necessary in draw to draw the contents.

Remarks

  • The context to which drawing commands are issued to is not static - it's instantiated on-demand.

  • NSView have the requirement that many of its interfaces be invoked only on the main thread.