Rotate animation for NSImageView (MacOS)

I have a NSImageView which I want to add it a rotation animation.

I tried a lot of things, but the rotation always start from the corner of the image, and I want it to start from the center.

I've added a layer to the image, and tried to set the anchor point, but nothing helped.


For example, what's wrong at this code?

(this is just one example, I tried many things, but the rotation is always from the corner)




// Create red NSImageView
        let imageView = NSImageView(frame: NSRect(x: 100, y: 100, width: 100, height: 100))
        imageView.wantsLayer = true
        imageView.layer?.backgroundColor = NSColor.red.cgColor
      
        view.addSubview(imageView)
      
        // Before animate, reset the anchor point
        imageView.setAnchorPoint(anchorPoint: CGPoint(x: 0.5, y: 0.5))
        // Start animation
        if imageView.layer?.animationKeys()?.count == 0 || imageView.layer?.animationKeys() == nil {
            let rotate = CABasicAnimation(keyPath: "transform.rotation")
            rotate.fromValue = 0
            rotate.toValue = CGFloat(-1 * .pi * 2.0)
            rotate.duration = 2
            rotate.repeatCount = Float.infinity
          
            imageView.layer?.add(rotate, forKey: "rotation")
        }



extension NSView {
    func setAnchorPoint(anchorPoint:CGPoint) {
        if let layer = self.layer {
            var newPoint = NSPoint(x: self.bounds.size.width * anchorPoint.x, y: self.bounds.size.height * anchorPoint.y)
            var oldPoint = NSPoint(x: self.bounds.size.width * layer.anchorPoint.x, y: self.bounds.size.height * layer.anchorPoint.y)
           
            newPoint = newPoint.applying(layer.affineTransform())
            oldPoint = oldPoint.applying(layer.affineTransform())
           
            var position = layer.position
           
            position.x -= oldPoint.x
            position.x += newPoint.x
           
            position.y -= oldPoint.y
            position.y += newPoint.y
           
            layer.position = position
            layer.anchorPoint = anchorPoint
        }
    }
}