Search code examples
iosswiftanimationimage-rotation

Funky behavior when animating rotation of UIImageView


I'm trying to rotate an UIImageView with the following code:

var x = -((self.needleImage.frame.size.width/2) - 15) //x for rotation point

UIView.animateWithDuration(5.0, delay: 10.0, options: nil, animations: {
    var transform = CGAffineTransformMakeTranslation(x, 0)
    transform = CGAffineTransformRotate(transform, CGFloat(-M_PI_2))
    transform = CGAffineTransformTranslate(transform, -x, 0)
    self.needleImage.transform = transformm

The end position is right, but during the animation/rotation, the image is shifted a little to the left before settling at the right place.

I tried the same code with a UIView from this and it doesn't do that.

Then I tried wrapping the Imageview inside a View and rotating that, but that didn't help either.

I have drawn a cicle ontop of the rotation point to check if it isn't in the right place, but it seems alright.


Solution

  • I've used this code snippet in the past to rotate a view perpetually, but by removing the last closure it should work to rotate an image 360 degrees. This can be adjusted, or course. Right now it's set to 2PI. You'll have to convert your rotation angle to radians.

    func animateRotator() {
            UIView.animateWithDuration(0.5, delay: 0, options: .CurveLinear, animations: { () -> Void in
                self.rotator.transform = CGAffineTransformRotate(self.rotator.transform, CGFloat(M_PI_2))
                }) { (finished) -> Void in
                    self.animateRotator()
            }
        }