Created
April 19, 2017 02:56
-
-
Save Hexfire/b2cc9b225b0ae14698c6179163d8d29a to your computer and use it in GitHub Desktop.
Rotate NSImageView (UIImageView) around its center
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
extension NSView { // UIView | |
// Set source/destination angle. | |
// Angle is set in radians (0..2π), hence 360* rotation = 2π/-2π | |
func spinClockwise(timeToRotate: Double) { | |
startRotation(angle: -1 * CGFloat.pi * 2.0, timeToRotate: timeToRotate) | |
} | |
func spinAntiClockwise(timeToRotate: Double) { | |
startRotation(angle: CGFloat.pi * 2.0, timeToRotate: timeToRotate) | |
} | |
func startRotation(angle: CGFloat, timeToRotate: Double) { | |
let rotateAnimation = CABasicAnimation(keyPath: "transform.rotation") | |
rotateAnimation.fromValue = 0.0 | |
rotateAnimation.toValue = angle | |
rotateAnimation.duration = timeToRotate | |
rotateAnimation.speed = 4 | |
rotateAnimation.repeatCount = .infinity | |
self.layer?.add(rotateAnimation, forKey: nil) | |
Swift.print("Start rotating") | |
} | |
func stopAnimations() { | |
self.layer?.removeAllAnimations() | |
Swift.print("Stop rotating") | |
} | |
} | |
// Usage: | |
imageView.wantsLayer = true | |
imageView.layer!.anchorPoint = CGPoint(x: 0.5, y: 0.5) // 0.5x0.5 means center | |
// Start spinning | |
imageView.spinClockwise(timeToRotate: 60) | |
// Stop spinning | |
imageView.stopAnimations() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment