0

Here's a simple demo for rotating an image view with animation.

enter image description here

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.

Ken Zhang
  • 1,454
  • 2
  • 13
  • 27
  • I had the same problem, the reason is that you are animating a `CATransform`, that is done on the layer not on the view, that is why `UIView.animateWithDuration` does not respond to it – sken3r.MI Oct 30 '15 at 08:32
  • @sken3r.MI I think you are right! Can you post it as an answer, then I can accept it? – Ken Zhang Nov 08 '15 at 13:36

1 Answers1

0

I had the same problem, the reason is that you are animating a CATransform, that is done on the layer not on the view, that is why UIView.animateWithDuration does not respond to it

sken3r.MI
  • 478
  • 3
  • 11