帮助正确计算atan2

yoz*_*hik 8 objective-c image-rotation atan2

我需要计算线之间的角度.我需要计算atan.所以我正在使用这样的代码

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;
}
Run Code Online (Sandbox Code Playgroud)

但是我不能超过180度((在179度之后178-160 ...... 150等等).

我需要旋转360度.我该怎么做?怎么了?

maby这有助于:

//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;
    }

}
Run Code Online (Sandbox Code Playgroud)

Ron*_*lic 8

atan2以[-180,180](或-pi,以弧度表示的pi)返回结果.要从0,360获得结果,请使用:

float radians = atan2(dy, dx);
if (radians < 0) {
    radians += M_PI*2.0f;
}
Run Code Online (Sandbox Code Playgroud)

应该注意的是,通常用[-pi,pi]表示旋转,因此你可以使用结果而atan2不用担心符号.

  • 没有理由我可以看到你的角度不正确.具体生成什么值不正确? (2认同)

cas*_*nca 6

删除fabs电话,然后简单地:

CGFloat rads = atan2(dy, dx);
Run Code Online (Sandbox Code Playgroud)