Reputation: 4226
After looking at the answers provided in this question, I created the following method:
private int angleOf(float x1, float x2, float y1, float y2) {
final double deltaY = (y1 - y2);
final double deltaX = (x2 - x1);
final double result = Math.toDegrees(Math.atan2(deltaY, deltaX));
return (int) ((result < 0) ? (360d + result) : result);
}
by using the above I will get the angle of each line , then I draw the text to my canvas, as shown below:
int topLine = angleOf(this.mPoints[5].x, this.mPoints[4].x, this.mPoints[5].y, this.mPoints[4].y);
int bottomLine = angleOf(this.mPoints[5].x, this.mPoints[6].x, this.mPoints[5].y, this.mPoints[6].y);
canvas.drawText(String.valueOf(360 - bottomLine + topLine)+"°", this.mPoints[5].x - 80.0f, this.mPoints[5].y, this.mTextPaint);
The above works fine, here is a example of my result:
The problem I have is that the angle is measured from the x-axis and increasing anti-clockwise, as shown below:
When the bottom line or the top line "crosses" the 0° (parallel to the x-axis), I would then get an incorrect angle.
Here is another image to demonstrate this issue:
The angle between the blue lines are 90°, but instead I get 450°. This happens because of the calculation I used 360 - bottomLine + topLine
.
Can someone please suggest a solution to this issue.
Thank you.
Upvotes: 4
Views: 1854
Reputation: 10707
Use this method to calculate it properly:
private double angleOfDegrees(float x0, float y0, float x1, float y1) {
double angle2 = Math.atan2(y1,x1);
double angle1 = Math.atan2(y0,x0);
return Math.toDegrees(angle2 - angle1) + 360) % 360;
}
Upvotes: 0
Reputation: 1416
You can use like this,out put value is radian coordinate point (0,0) other points (x1,y1) ,(x2,y2)
atan()
= tan invers
private double angleOfRadian(float x1, float x2, float y1, float y2) {
return java.lang.Math.atan(y2/x2)-java.lang.Math.atan(y1/x1);
}
Upvotes: 1