计算两点之间的角度 – java

我需要计算两点之间的角度,其中一个固定点通过一条线与给定的两点相连。

这是一张图片,说明了我的需求:

在此处输入图像描述

这是我到目前为止所尝试的:

public static float GetAngleOfLineBetweenTwoPoints(float x1, float x2, float y1, float y2) { float xDiff = x2 - x1; float yDiff = y2 - y1; return (float) (Math.atan2(yDiff, xDiff) * (180 / Math.PI)); } 

毫无意义地说,它没有提供正确的答案。

您可以使用以下方法使用Math.atan2方法以弧度计算角度:

 public static double angleBetweenTwoPointsWithFixedPoint(double point1X, double point1Y, double point2X, double point2Y, double fixedX, double fixedY) { double angle1 = Math.atan2(point1Y - fixedY, point1X - fixedX); double angle2 = Math.atan2(point2Y - fixedY, point2X - fixedX); return angle1 - angle2; } 

并用三个点调用它(使用Math.toDregrees将结果角度从弧度转换为度数):

 System.out.println(Math.toDegrees( angleBetweenTwoPointsWithFixedPoint(0, 0, // point 1's x and y 1, 1, // point 2 1, 0 // fixed point ))); 

输出:90.0

尽管如此,请随意使用Java的标准PointLine2D类。 这只是为了certificate它有效。

这是我的Android Gesture库中的代码段。 它的工作原理和经过全面测试。

 public double getAngleFromPoint(Point firstPoint, Point secondPoint) { if((secondPoint.x > firstPoint.x)) {//above 0 to 180 degrees return (Math.atan2((secondPoint.x - firstPoint.x), (firstPoint.y - secondPoint.y)) * 180 / Math.PI); } else if((secondPoint.x < firstPoint.x)) {//above 180 degrees to 360/0 return 360 - (Math.atan2((firstPoint.x - secondPoint.x), (firstPoint.y - secondPoint.y)) * 180 / Math.PI); }//End if((secondPoint.x > firstPoint.x) && (secondPoint.y <= firstPoint.y)) return Math.atan2(0 ,0); }//End public float getAngleFromPoint(Point firstPoint, Point secondPoint) 

我不知道@ user2288580,但即使对于简单的测试用例,您的代码也会失败。

firstPoint =(0,0)secondPoint =(0,5),(5,5),(5,0),(5,-5)(0,-5)( – 5,-5),( – -5 ,0)

请查看这是否适合您@David –

 public double angleBetween2CartesianPoints(double firstX, double firstY, double secondX, double secondY) { double angle = Math.atan2((secondX - firstX), (secondY - firstY)) * 180 / Math.PI; if (angle < 0) { return (360 + angle); } else { return (angle); } }