将弧度转换为度数

时间:2014-09-28 07:48:33

标签: ios cocoa-touch math swift

我有以下代码可以转换imageView并在触摸时在superview中旋转它:

override func touchesMoved(touches: NSSet, withEvent event: UIEvent) {                              
    var touch: AnyObject? = event.allTouches()?.anyObject()
    var location = touch!.locationInView(touch!.view)

    var dx: Float = Float(location.x - hsbWheel250ImageView.center.x)
    var dy: Float = Float(location.y - hsbWheel250ImageView.center.y)
    var radians = atan2f(dy, dx)

    //deltaAngle is set in touchesBegan
    var angleDiff = deltaAngle - radians
    hsbWheel250ImageView.layer.transform = CATransform3DMakeRotation(-angleDiffCGFloat, 0, 0, 1)

   //This is where my problem is

   var angleDiffCGFloat = CGFloat(deltaAngle - radians)
   var angleInDegrees = angleDiffCGFloat * (180.0 / Float(M_PI))
   println(angleInDegrees)

   //For the first 180 degrees of the rotation angleInDegrees returns the correct 
   //number i.e. 0-180. But then after 180, where it should return 181, 
   //it returns -179. Where it should return 270 it returns -90 and so on 
   //and so forth..

我一直在尝试google,但是人们给出的唯一解决方案(当从弧度转换为度数时)是上面的那个...我认为这只是一个数学问题,但我害怕我的大脑已经关闭了这个。

非常感谢任何帮助。

ANSWER 对于那些感兴趣的人,答案如下:

var angleInDegrees = fmodf(360.0 + -angleDiff * (180.0 / Float(M_PI)), 360.0)

1 个答案:

答案 0 :(得分:3)

atan2f返回主角,其范围从-π到+π(-180到+180度)。您可以明确处理负值,也可以使用fmodf强制角度达到所需范围,例如:改变:

var angleInDegrees = angleDiffCGFloat * (180.0 / Float(M_PI))

为:

var angleInDegrees = fmodf(360.0 + angleDiffCGFloat * (180.0 / Float(M_PI)), 360.0);