首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >帮助正确计算atan2

帮助正确计算atan2
EN

Stack Overflow用户
提问于 2010-11-03 00:54:23
回答 4查看 14.1K关注 0票数 9

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

代码语言:javascript
复制
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度旋转。我该怎么做呢?怎么了?

maby这是有帮助的:

代码语言:javascript
复制
//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;
    }

}
EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2010-11-03 00:59:30

删除fabs调用,并简单地执行以下操作:

代码语言:javascript
复制
CGFloat rads = atan2(dy, dx);
票数 7
EN

Stack Overflow用户

发布于 2010-11-03 00:58:37

atan2-180,180格式返回结果。要从0,360获得结果,请使用:

代码语言:javascript
复制
float radians = atan2(dy, dx);
if (radians < 0) {
    radians += M_PI*2.0f;
}

应该注意的是,这是典型的用-pi,pi来表达旋转,因此你可以只使用atan2的结果,而不用担心符号。

票数 9
EN

Stack Overflow用户

发布于 2015-02-15 09:57:18

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

代码语言:javascript
复制
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
}

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

代码语言:javascript
复制
let twoPi = 2 * Float(M_PI)
let radians = (atan2(-dy, -dx) + twoPi) % twoPi
let angle = radians * 360 / twoPi
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/4080070

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档