正确计算atan2的帮助

9
我需要计算两条线之间的夹角。我需要计算反正切函数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;
}

但是我无法旋转超过180度(在179度之后变成178、160、150等等)。

我需要360度旋转。该怎么做?有什么问题吗?

也许这可以帮助:

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

}
4个回答

9

atan2 返回的结果在 [-180, 180](以弧度表示为 -pi 到 pi)。若要获得 0-360 的结果,请使用以下方法:

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

需要注意的是,在旋转中通常使用[-pi,pi]来表示,因此您可以直接使用atan2的结果而不必担心符号问题。


什么没有起作用?我假设你也替换了一个适当的常量来代替TWO_PI - Ron Warholic
2
我看不出为什么它不能起作用以获得正确的角度。具体生成了哪些错误的值? - Ron Warholic

7

移除 fabs 函数的调用,直接将其改为:

CGFloat rads = atan2(dy, dx);

1
@yozhik:也许你应该解释一下哪里出了问题。期望的结果是什么,你看到了什么? - casablanca
我有一个笛卡尔坐标系,在上面投影图片。有一个图像零点。当我将图片向上移动180度时,一切都正常。但是当我尝试向下移动180度以下的角度,例如190度时,它会显示170度。我需要它显示190度。你看... - yozhik
@yozhik:尝试同时删除fabs(rad2 - rad1)中的其他fabs - casablanca

1
你的问题在于atan2的结果在-180度到+180度之间。 如果你想要它在0到360之间,那么将结果移动到正值,然后取模。例如:
let angle = fmod(atan2(dx,dy) + .pi * 2, .pi * 2)

0

在Swift中使用此函数。这将确保从“fromPoint”到“toPoint”的角度落在0到<360之间(不包括360)。请注意,以下函数假定CGPointZero位于左上角。

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
}

对于原点位于左下角的情况

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接