![](/img/trans.png)
[英]Calculating the angle between two lines without having to calculate the slope? (Java)
[英]Calculate angle between two lines
在查看此問題中提供的答案后,我創建了以下方法:
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);
}
通過使用上面我將獲得每行的角度,然后我將文本繪制到我的畫布,如下所示:
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);
以上工作正常,這是我的結果的一個例子:
我遇到的問題是角度是從x軸測量並逆時針增加的,如下圖所示:
當底線或頂線“交叉”0°(平行於x軸?)時,我會得到一個不正確的角度。
這是另一張展示此問題的圖片:
藍線之間的角度是90°,但我得到450°。 這是因為我使用的計算360 - bottomLine + topLine
。
有人可以建議解決這個問題。
謝謝。
你可以像這樣使用,輸出值是弧度坐標點(0,0)其他點(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);
}
使用此方法正確計算它:
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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.