随机旋转imageview

时间:2015-04-24 16:51:07

标签: xcode swift xcode6

如何将ImageView随机旋转0到360?

这段代码让我把它旋转180度:

func rotateTimes(){
        UIView.animateWithDuration(5, delay: 0.0, options: UIViewAnimationOptions.CurveLinear,      animations: { () -> Void in
            self.imageView.transform = CGAffineTransformRotate(self.imageView.transform, 180 * 0.0174532925)
            }, completion: nil)
    }

但我想旋转随机度,不仅仅是180度。

我试过了:

func rotateTimes(){
        let diceRoll = Int(arc4random_uniform(7))
        UIView.animateWithDuration(5, delay: 0.0, options: UIViewAnimationOptions.CurveLinear,      animations: { () -> Void in
            self.imageView.transform = CGAffineTransformRotate(self.imageView.transform, self.diceRoll * 0.0174532925)
            }, completion: nil)
    }

但那不起作用..

2 个答案:

答案 0 :(得分:0)

试试这个:

let random = arc4random_uniform(1000)
let angle = Double(2*pi*1000)/ Double(random)
UIView.animateWithDuration(5, 
  delay: 0.0, 
  options: UIViewAnimationOptions.CurveLinear,      
  animations: 
  { () -> Void in
    self.imageView.transform = 
      CGAffineTransformRotate(angle)
  }, 
  completion: nil)

(你需要定义pi。如果我没记错,你必须导入Darwin,然后M_PI常量可用。)

答案 1 :(得分:0)

您在0到6度之间旋转。这几乎不可察觉。尝试使用60的倍数。

0.0174532925表示360度圆上的单度。记住回到代数的方式和圈子的圆周是2 * pi * r。由于我们不关心周长,我们可以放弃r。围绕圆圈的旋转是2 * pi。 2 * pi / 360为您提供上面的数字。

因此,要旋转视图,您可以决定旋转多少度并乘以0.0174532925

我在下方添加了60因子,以使旋转更加明显。 0不会改变位置。 1将围绕圆圈的1/6旋转,2将旋转2/6左右,依此类推。 (6也不会改变位置。)

此外,它将从当前位置旋转,而不是从起始位置旋转。因此,连续两次调用该函数并且两次都假设diceRoll为3,视图将最终返回到原始位置。

func rotateTimes(){
    let diceRoll = CGFloat(arc4random_uniform(7))
    let degree =  0.0174532925 as CGFloat
    let sixthOfCircle : CGFloat = 60
    let rotate = diceRoll * degree * sixthOfCircle
    UIView.animateWithDuration(5, delay: 0.0, options: UIViewAnimationOptions.CurveLinear,      animations: { () -> Void in
        self.rotateView.transform = CGAffineTransformRotate(self.rotateView.transform, rotate)
        }, completion: nil)
}