C# calculates the azimuth of a line segment and converts the angle

1. Calculate the azimuth of the line segment

You can use the function in C# System.Math.Atan2to find the azimuth of the line segment.

The Atan2 function accepts two parameters, which respectively represent the difference between the abscissa of the end point of the line segment and the abscissa of the starting point (i.e. the horizontal length of the line segment) and the difference between the ordinate of the end point of the line segment and the ordinate of the starting point (i.e. the longitudinal length of the line segment). length).

The Atan2 function returns the azimuth of the line segment in radians. If you want to express in degrees, you can multiply the returned value by 180/π (ie 57.295779513082320876798154814105).

Here is a sample code:

double x1,y1; //起点坐标
double x2,y2; //终点坐标
double angle = Math.Atan2(y2 - y1, x2 - x1);
double degrees = angle * 180 / Math.PI;

注意:Atan2 函数返回的角度的正方向是从 x 轴正方向开始按逆时针方向计算的。

2. Convert angle

Angles can be converted between -90 and 90 degrees using the modulo operator (%). Use the following code to convert the angle to a value in this range:

double angle = 120;// 角度的原始值

// 将角度转换到 -90 到 90 度之间
double normalizedAngle = angle % 180;
if (normalizedAngle > 90)
{
    
    
    normalizedAngle -= 180;
}
else if (normalizedAngle < -90)
{
    
    
    normalizedAngle += 180;
}

Guess you like

Origin blog.csdn.net/qq_29242649/article/details/128339624