【问题标题】:Calculate angle between two lines计算两条线之间的角度
【发布时间】:2019-07-09 08:07:18
【问题描述】:

查看this问题中提供的答案后,我创建了以下方法:

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 的计算。

有人可以建议解决这个问题吗?

谢谢。

【问题讨论】:

  • (360 - topLine + bottomLine) % 360 或类似的东西
  • @pskink ,您的评论将非常有效。
  • @KaranMer 我希望如此,因为我没有测试它;-)
  • 您正在计算通过(x1,y1)(x2, y2) 的线与x 轴之间的角度。我猜这不是你想要的。
  • %modulo operator,不是除法,例如36 % 10 == 6,不是3.6

标签: java android canvas trigonometry


【解决方案1】:

使用此方法正确计算:

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;
}

【讨论】:

    【解决方案2】:

    你可以这样使用,输出值为弧度 坐标点 (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);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-03-22
      • 1970-01-01
      • 1970-01-01
      • 2019-08-21
      • 1970-01-01
      • 2016-10-19
      • 1970-01-01
      相关资源
      最近更新 更多