Skip to content

Instantly share code, notes, and snippets.

@Hexfire
Created April 19, 2017 02:56
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Hexfire/b2cc9b225b0ae14698c6179163d8d29a to your computer and use it in GitHub Desktop.
Save Hexfire/b2cc9b225b0ae14698c6179163d8d29a to your computer and use it in GitHub Desktop.
Rotate NSImageView (UIImageView) around its center
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