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

4 回答 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不用担心符号。

于 2010-11-02T16:58:37.033 回答
7

删除fabs呼叫并简单地进行:

CGFloat rads = atan2(dy, dx);
于 2010-11-02T16:59:29.563 回答
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
于 2015-02-15T01:57:18.460 回答
0

你的问题是 atan2 的结果在 -180 到 +180 度之间。如果您希望它在 0 到 360 之间,则移动结果以确保为正值,然后进行取模。例如:

let angle = fmod(atan2(dx,dy) + .pi * 2, .pi * 2)
于 2020-05-19T00:44:23.730 回答