Help calculate atan2 correctly

I need to calculate the angle between the lines. I need to calculate atan. Therefore, I use this code

static inline CGFloat angleBetweenLinesInRadians2(CGPoint line1Start, CGPoint line1End) { CGFloat dx = 0, dy = 0; dx = line1End.x - line1Start.x; dy = line1End.y - line1Start.y; NSLog(@"\ndx = %f\ndy = %f", dx, dy); CGFloat rads = fabs(atan2(dy, dx)); return rads; } 

But I can’t get more than 180 degrees ((After 179 degrees. Goes 178..160..150, etc.

I need to rotate 360 ​​degrees. How can I do it? What's wrong?

maby this helps:

 //Tells the receiver when one or more fingers associated with an event move within a view or window. - (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event { NSArray *Touches = [touches allObjects]; UITouch *first = [Touches objectAtIndex:0]; CGPoint b = [first previousLocationInView:[self imgView]]; //prewious position CGPoint c = [first locationInView:[self imgView]]; //current position CGFloat rad1 = angleBetweenLinesInRadians2(center, b); //first angel CGFloat rad2 = angleBetweenLinesInRadians2(center, c); //second angel CGFloat radAngle = fabs(rad2 - rad1); //angel between two lines if (tempCount <= gradus) { [imgView setTransform: CGAffineTransformRotate([imgView transform], radAngle)]; tempCount += radAngle; } } 
+7
objective-c image-rotation atan2
source share
3 answers

Remove the fabs call and just do it:

 CGFloat rads = atan2(dy, dx); 
+5
source share

atan2 returns results in [-180, 180] (or -pi, pi in radians). To get results from 0.360 use:

 float radians = atan2(dy, dx); if (radians < 0) { radians = TWO_PI + radians; } 

It should be noted that it is typical to express rotations in [-pi, pi], and therefore you can simply use the result of atan2 without worrying about the sign.

+7
source share

Use this function in Swift. This ensures that the angle from fromPoint to toPoint is between 0 and 360 (not including 360). Note that the following function assumes that CGPointZero is in the upper left corner.

 func getAngle(fromPoint: CGPoint, toPoint: CGPoint) -> CGFloat { let dx: CGFloat = fromPoint.x - toPoint.x let dy: CGFloat = fromPoint.y - toPoint.y let twoPi: CGFloat = 2 * CGFloat(M_PI) let radians: CGFloat = (atan2(dy, -dx) + twoPi) % twoPi return radians * 360 / twoPi } 

In the case when the origin is in the lower left corner

 let twoPi = 2 * Float(M_PI) let radians = (atan2(-dy, -dx) + twoPi) % twoPi let angle = radians * 360 / twoPi 
0
source share

All Articles