我需要计算两点之间的角度,其中一个固定点与给定的两点相连一行。
这是一张图片,展示了我的需求:
这是我到目前为止所尝试的内容:
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));
}
毫无意义地说,它没有提供正确答案。
答案 0 :(得分:14)
您可以使用以下方法使用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的标准Point
或Line2D
类。这只是为了证明它有效。
答案 1 :(得分:6)
以下是我的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)
答案 2 :(得分:1)
我不知道@ 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);
}
}