您可以添加這樣的UIView或的UIImageView的擴展:
extension UIView {
///The less is the timeToRotate, the more fast the animation is !
func spinClockwise(timeToRotate: Double) {
startRotate(CGFloat(M_PI_2), timeToRotate: timeToRotate)
}
///The less is the timeToRotate, the more fast the animation is !
func spinAntiClockwise(timeToRotate: Double) {
startRotate(CGFloat(-M_PI_2), timeToRotate: timeToRotate)
}
func startRotate(angle: CGFloat, timeToRotate: Double) {
UIView.animateWithDuration(timeToRotate, delay: 0.0, options:[UIViewAnimationOptions.CurveLinear, UIViewAnimationOptions.Repeat], animations: {
self.transform = CGAffineTransformMakeRotation(angle)
}, completion: nil)
print("Start rotating")
}
func stopAnimations() {
self.layer.removeAllAnimations()
print("Stop rotating")
}
}
所以,當你想旋轉你的myImg
,你只需要調用:
myImg.spinClockwise(3)
而且當你想停止它:
myImg.stopAnimations()
注: 我加了playground只是讓你可以測試一下;)
乾杯!
編輯:
我的壞,這是一個NSView的例子:
extension NSView {
///The less is the timeToRotate, the more fast the animation is !
func spinClockwise(timeToRotate: Double) {
startRotate(CGFloat(-1 * M_PI * 2.0), timeToRotate: timeToRotate)
}
///The less is the timeToRotate, the more fast the animation is !
func spinAntiClockwise(timeToRotate: Double) {
startRotate(CGFloat(M_PI * 2.0), timeToRotate: timeToRotate)
}
func startRotate(angle: CGFloat, timeToRotate: Double) {
let rotateAnimation = CABasicAnimation(keyPath: "transform.rotation")
rotateAnimation.fromValue = 0.0
rotateAnimation.toValue = angle
rotateAnimation.duration = timeToRotate
rotateAnimation.repeatCount = .infinity
self.layer?.addAnimation(rotateAnimation, forKey: nil)
Swift.print("Start rotating")
}
func stopAnimations() {
self.layer?.removeAllAnimations()
Swift.print("Stop rotating")
}
}
重要提示:現在,經過我的測試中,我注意到,你必須設置你的NSView的錨點在中間,以便它可以圍繞其中心旋轉:
view.layer?.anchorPoint = CGPointMake(0.5, 0.5)
我增加了一個新的平臺,與OSX example
啊是的,這是我後面的事情,除了它需要是NSView,雖然NSView沒有'animateWithDuration'。有任何想法嗎? – Steve
@Steve:我更新了我的答案,讓我知道它是否適合你! – Mindhavok
ohhh soo close,圖像正在旋轉,但我無法將它放到最初放置的框架的中心,'myImg.layer?.anchorPoint = CGPointMake(0.5,0.5)',但它的類型移動到了左下角 – Steve