Search code examples
iosswiftautolayout

Continuous rotation is not centered


Using this code:

    UIView.animate(withDuration: 0.5, delay: 0, options: [.repeat], animations: {
        self.star.transform = self.star.transform.rotated(by: CGFloat(M_PI_2))
    })

My view is doing this: enter image description here

Using this code:

extension UIView {
    func rotate360Degrees(duration: CFTimeInterval = 3) {
        let rotateAnimation = CABasicAnimation(keyPath: "transform.rotation")
        rotateAnimation.fromValue = 0.0
        rotateAnimation.toValue = CGFloat(M_PI * 2)
        rotateAnimation.isRemovedOnCompletion = false
        rotateAnimation.duration = duration
        rotateAnimation.repeatCount=Float.infinity
        self.layer.add(rotateAnimation, forKey: nil)
    }
}

My view is doing this: enter image description here

Well both are not doing what I want. The view that is rotating is an UIImageView with scale to fill. I want the image to stay exactly in the middle. How can I accomplish that? The functions are executed in viewDidAppear. The last gif looks way better, but notice the star is not perfectly centered... This is the image.


Solution

  • Problem

    The center of your image is not the center of your star.

    Solutions

    There are two possible solutions

    • Edit the image so that center of the star is at the center of the image.
    • Set the anchor of the rotating layer to the center of the star (x: 1004px, y: 761px).