在中心周围旋转NSView

时间:2015-03-21 11:08:18

标签: macos core-animation nsview

我有自定义NSView,它应该使用CoreAnimation(或osx sdk中提供的任何其他方式)绕中心旋转。我尝试了很多解决方案,但是nsview绕左下角而不是中心旋转,似乎总是忽略锚点。我做错了什么?

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")
}

1 个答案:

答案 0 :(得分:1)

由于在AppDelegate中使用了以下代码,它似乎无法正常工作,这使得NSWindow成为分层支持:

mainWindow.styleMask = mainWindow.styleMask | NSFullSizeContentViewWindowMask

在ViewController中添加以下代码有助于:

self.view.wantsLayer = true