Here's a simple demo for rotating an image view with animation.
class ViewController: UIViewController {
@IBOutlet weak var imageView: UIImageView!
@IBAction func left() {
animateWithTransform(CATransform3DMakeRotation(CGFloat(M_PI_4), 0, 0, 1))
}
@IBAction func right() {
animateWithTransform(CATransform3DMakeRotation(CGFloat(-M_PI_4), 0, 0, 1))
}
func animateWithTransform(transform: CATransform3D) {
UIView.animateWithDuration(1) {
self.imageView.layer.transform = transform
}
}
}
The animation runs smoothly. Update right() to:
@IBAction func right() {
animateWithTransform(CATransform3DMakeRotation(CGFloat(-M_PI_4), 0, 1, 0))
}
Tap left then right, the animation is not smooth any more. The image view jumps to an angle before starting animation. Why's that?
Update animateWithTransform() to use CABasicAnimation instead:
func animateWithTransform(transform: CATransform3D) {
let animation = CABasicAnimation(keyPath: "transform")
animation.duration = 1
animation.fromValue = NSValue(CATransform3D: imageView.layer.transform)
animation.toValue = NSValue(CATransform3D: transform)
animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseIn)
imageView.layer.addAnimation(animation, forKey: nil)
imageView.layer.transform = transform
}
The animation is fine again.
So the question is why I can't use animateWithDuration here. Is this a bug? Thanks.
---- update ---------------------------------
BTW, the image view is centered by constraints. This could probably be a constraint issue, I'm not sure.