Animate Rotating UIImageView

前端 未结 5 1672
予麋鹿
予麋鹿 2021-02-08 03:07

I want to rotate a UIImageView by roughly 10 degrees left/right but have a smooth animation, rather than a sudden turn which I see using:

play         


        
5条回答
  •  别跟我提以往
    2021-02-08 03:25

    A modern Swift solution, using NSTimer and CGAffineTransformMakeRotation:

    class Rotation: UIViewController {
        var timer = NSTimer()
        var rotAngle: CGFloat = 0.0
    
        @IBOutlet weak var rotationImage: UIImageView!
    
        override func viewDidLoad() {
          super.viewDidLoad()
          activateTimer()
        }
    
        func activateTimer() {
          //(1)
          timer = NSTimer.scheduledTimerWithTimeInterval(1.0, target:self, selector:#selector(Rotation.updateCounter), userInfo: nil, repeats: true) 
        }
    
        func updateCounter() {
          //(2)
          var rotateLeft: Bool = true
          if rotateLeft {
            rotAngle -= 30.0
          } else {
            rotAngle += 30.0
          }
          //(3)
          UIView.animateWithDuration(2.0, animations: {
            self.rotationImage.transform = CGAffineTransformMakeRotation((self.rotAngle * CGFloat(M_PI)) / 180.0)
          })
        }
    }
    

    Things to notice:

    • Connect the outlet the the UIImageView

    • Play with the (1)timer pace, (2)animation pace and (3)rotation angle to get the desired results. This set of variables worked for me.

提交回复
热议问题