找到3个CGPoints的角度

Jos*_*osa 2 math cocoa-touch objective-c drawrect ios

在我的应用程序中,用户点击3次,并且点击的3个点将创建一个角度.它完美地绘制了角度.我想在第二次敲击时计算角度,但我认为我做错了(可能是数学错误).我还没有在我的微积分课程中介绍过这个,所以我将在维基百科上找到一个公式.

http://en.wikipedia.org/wiki/Law_of_cosines

这是我正在尝试的:

注意:CGPoints在用户点击时创建第一,第二和第三.

        CGFloat xDistA = (second.x - third.x);
        CGFloat yDistA = (second.y - third.y);
        CGFloat a = sqrt((xDistA * xDistA) + (yDistA * yDistA));

        CGFloat xDistB = (first.x - third.x);
        CGFloat yDistB = (first.y - third.y);
        CGFloat b = sqrt((xDistB * xDistB) + (yDistB * yDistB));

        CGFloat xDistC = (second.x - first.x);
        CGFloat yDistC = (second.y - first.y);
        CGFloat c = sqrt((xDistC * xDistC) + (yDistC * yDistC));

        CGFloat angle = acos(((a*a)+(b*b)-(c*c))/((2*(a)*(b))));

        NSLog(@"FULL ANGLE IS: %f, ANGLE IS: %.2f",angle, angle);
Run Code Online (Sandbox Code Playgroud)

有时,它将角度设为1,这对我来说没有意义.谁能解释为什么会这样,或者如何解决它?

Tyl*_*ler 12

不确定这是否是主要问题,但这是一个问题

你的答案给出了错误点的角度:

在此输入图像描述

要获得绿色角度(根据您的变量名称"first","second"和"third",可能是您想要的角度),请使用:

CGFloat angle = acos(((a*a)+(c*c)-(b*b))/((2*(a)*(c))));


Nik*_*uhe 5

这是一种绕过余弦定律,而是计算两个向量的角度的方法。角度之间的差是搜索值:

CGVector vec1 = { first.x - second.x, first.y - second.y };
CGVector vec2 = { third.x - second.x, third.y - second.y };

CGFloat theta1 = atan2f(vec1.dy, vec1.dx);
CGFloat theta2 = atan2f(vec2.dy, vec2.dx);

CGFloat angle = theta1 - theta2;
NSLog(@"angle: %.1f°, ", angle / M_PI * 180);
Run Code Online (Sandbox Code Playgroud)

请注意,该atan2函数将x和y分量作为单独的参数,从而避免了0/90/180/270°的歧义。

  • @NikolaiRuhe; 实际上,它仅来自iOS 7:https://developer.apple.com/library/ios/documentation/graphicsimaging/reference/CGGeometry/Reference/reference.html (2认同)