Reputation: 8020
I've got the following code that transforms a imageView and rotates it in its superview on touch:
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..
I've been trying to google my way around, but the only solution people are giving (when converting from radians to degrees) is the one above... I think this is simply a maths problem, but I'm afraid my brain has switched off for this one.
Any help is greatly appreciated.
Upvotes: 2
Views: 1675
Reputation: 212929
atan2f
returns the principal angle, which has a range from -π to +π (-180 to +180 degrees). You can either deal with the negative values explicitly or use fmodf
to force the angles into the required range, e.g. change:
var angleInDegrees = angleDiffCGFloat * (180.0 / Float(M_PI))
to:
var angleInDegrees = fmodf(360.0 + angleDiffCGFloat * (180.0 / Float(M_PI)), 360.0);
Upvotes: 7