Search code examples
iosswiftuiviewanimationarc4random

Rotate imageView random


I am trying to get the image view to rotate random degree between 360 and 720. So I want the image view to rotate once(360 degrees), and then again rotate a random degree(0 to 360)

func rotateRandom2(){
    let lower : UInt32 = 360
    let upper : UInt32 = 720
    let diceRoll = CGFloat(arc4random_uniform(upper - lower) + lower)
    let degree =  0.0174532925 as CGFloat
    let rotate = diceRoll
    UIView.animateWithDuration(1, delay: 0.0, options: UIViewAnimationOptions.CurveEaseOut,      animations: { () -> Void in
        self.bottleImageView.transform = CGAffineTransformRotate(self.bottleImageView.transform, rotate)
        }, completion: nil)
}

Solution

  • You can use CABasicAnimation to animate z rotation. You can do as follow:

    let rotateView = CABasicAnimation()
    let randonAngle = arc4random_uniform(361) + 360
    rotateView.fromValue = 0
    rotateView.toValue = Float(randonAngle) * Float(M_PI) / 180.0
    rotateView.duration = 1
    rotateView.repeatCount = 0
    rotateView.removedOnCompletion = false
    rotateView.fillMode = kCAFillModeForwards
    rotateView.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseOut)
    view.layer.addAnimation(rotateView, forKey: "transform.rotation.z")