Need algorithm for angle of WPF line
What is the "correct" algorithm to calculate the angle in 开发者_运维百科degrees from a WPF Line?
You need atan2
. This would however give you the angle in radians, converting to degrees must be easy :-) The angle is calculated as atan2(y2 - y1, x2 - x1)
, where (x1, y1)
and (x2, y2)
are your line ends.
Note that the constant pi
is available, too.
To convert to degrees you can use the multiplier (180 degrees / Math.PI radians). This conversion factor is obtained by noting that Math.PI radians is equivalent to 180 degrees. So if theta1 is in radians then theta2 = theta1 * (180/Math.PI) will be equivalent to theta1 except that it will have the unit of degrees.
To calculate the angle of a line you would use the standard formula for tangent from trigonometry and then take the arctangent of both sides to get theta
tan(theta) = opposite / adjacent -> theta = arctangent(opposite / adjacent)
This can be applied to your line by forming an appropriate triangle. To do this select any two points on the line (x1, y1) and (x2, y2). You can then form a unique right triangle with the hypotenuse being the line segment between (x1, y1) and (x2, y2), the opposite side being a vertical line segment of length (y2 - y1) and an adjacent side being a horizontal line segment of length (x2 - x1).
You can calculate the theta value by computing
Double theta = (180/Math.PI) * Math.Atan2(opposite, adjacent);
The function will automatically take care of the case when adjacent is zero (which would normally cause a divide by zero error) and will return the most appropriate angle (90 degrees or -90 degrees) except in the case when both opposite and adjacent are zero. In this case theta is zero, which doesn't make much sense. It really should throw an exception in this case because there is no way mathematically to determine the angle from a triangle with a hypotenuse having zero length.
精彩评论