Search code examples
swiftcocoacore-graphicsnsview

Creating simple animation loop on NSView


I try coding simple stuff related to canvas animations. My goal is to create some animations manually on NSView (for example continuously rotating rectangle, no Core Animation framework allowed with between states transitions).

My approach is:

  1. Get current CGContext
  2. Clear context and draw some path on with rotation angle depending on time
  3. Schedule timer to force NSView to redraw (by calling .display() each 1/30 sec

The problem is I'm not quite sure that it's the right approach as it creates too much overhead on CPU. I wonder if there is any other right way to reach the same result?

Found some information about needsDisplay and setNeedsDisplay to schedule draw call but it doesn't work when I call it like this "tick" message printed only once and it means that draw function is called only once

class GraphView: NSView {
    ...
    override func draw(_ dirtyRect: NSRect) {
        print("tick")
        super.draw(dirtyRect)

        let ctx = NSGraphicsContext.current?.cgContext
        self.drawdrawPrimitive(context: ctx!)

        // tried both but none of them works
        self.needsDisplay = true
        self.setNeedsDisplay(dirtyRect)
    }
}

Solution

  • Found a solution: Apple's SpriteKit handles all updates and does exactly the thing I needed