使用 x, y 坐标计算角度

Calculate degrees of angle using x, y coordinates

我的目标是计算用户手指围绕屏幕中心点的拖动,我使用 Math.Atan2() 尝试了几次错误的尝试。仅供参考,我在 Xamarin 应用程序中使用 SkiaSharp,但为了简单起见,我只需要以下场景的帮助。

有人可以使用下面的屏幕截图告诉我生成以下结果的最佳方法吗?

A = 0 度

B = 90 度

C = 180 度

D = 270 度

向我们展示返回错误结果的代码,向我们展示问题出在哪里,并允许我们为您提供更具体的建议。

  1. 因为你想要相对于中心的角度,你必须从你的点中减去中心坐标。

  2. Math.Atan2 产生弧度。使用 degrees = radians * 180 / pi.

  3. 将它们转换为度数
  4. 你的零角度不是像往常一样在x轴上,而是在y轴上。添加 90 度进行校正。

使用矢量类型使事情变得更容易。在这里,我将使用 System.Numerics.Vector2 结构。

正如 Patrick McDonald 指出的那样,Atan2 在某些情况下可能会产生负面结果。通过将结果加上 450 度(360 + 我们的 90 度校正)并取模 360 度,您总是得到 0 到 360 之间的值。

public static float GetAngle(Vector2 point, Vector2 center)
{
    Vector2 relPoint = point - center;
    return (ToDegrees(MathF.Atan2(relPoint.Y, relPoint.X)) + 450f) % 360f;
}

public static float ToDegrees(float radians) => radians * 180f / MathF.PI;

测试

var a = new Vector2(7, 3);
var b = new Vector2(20, 7);
var c = new Vector2(7, 10);
var d = new Vector2(3, 7);
var e = new Vector2(6.9f, 3); // Test for more than 270 deg.
var f = new Vector2(7.1f, 3); // Test for small angle.

var center = new Vector2(7, 7);

PrintAngle(a); // ==>   0
PrintAngle(b); // ==>  90
PrintAngle(c); // ==> 180
PrintAngle(d); // ==> 270
PrintAngle(e); // ==> 358.5679
PrintAngle(f); // ==>   1.432098


void PrintAngle(Vector2 point)
{
    Console.WriteLine(GetAngle(point, center));
}