Search code examples
macoscore-animationnsview

Rotate NSView Around center


I have custom NSView which should be rotated around center using CoreAnimation (or any other way available in osx sdk). I tried a lot of solutions, but nsview being rotated around bottom left point instead center and seems always ignoring anchor point. what I'm doing wrong?

override func awakeFromNib() {
  super.awakeFromNib()
  spinnerView = NSView(frame: self.bounds)
  spinnerView.layer = CALayer()
  spinnerView.wantsLayer = true
  addSubview(spinnerView)

  spinnerView.layer!.backgroundColor = NSColor.redColor().CGColor
  spinnerView.layer!.position = CGPointMake(CGRectGetMidX(spinnerView.frame), CGRectGetMidY(spinnerView.frame) )
  spinnerView.layer!.anchorPoint = CGPointMake(0.5, 0.5)
  startAnimation()
}

func startAnimation() {
  let rotation = CABasicAnimation(keyPath: "transform")
  rotation.duration = 10.0
  rotation.toValue = 20 * M_PI
  rotation.repeatCount = Float.infinity
  rotation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear)
  rotation.valueFunction = CAValueFunction(name: kCAValueFunctionRotateZ)

  spinnerView.layer!.addAnimation(rotation, forKey: "transform.rotation.z")
}

Solution

  • It seems not working because of following code in AppDelegate, which turns NSWindow to layer-backing:

    mainWindow.styleMask = mainWindow.styleMask | NSFullSizeContentViewWindowMask
    

    Adding the following code in ViewController helped:

    self.view.wantsLayer = true