Calculating the angle between two lines without having to calculate the slope? (Java)

后端 未结 8 1220
夕颜
夕颜 2020-11-28 07:27

I have two Lines: L1 and L2. I want to calculate the angle between the two lines. L1 has points: {(x1, y1), (x2, y2)} and L2 has points: {(x3, y3), (x4, y

8条回答
  •  温柔的废话
    2020-11-28 07:34

    Maybe my approach for Android coordinates system will be useful for someone (used Android PointF class to store points)

    /**
     * Calculate angle between two lines with two given points
     *
     * @param A1 First point first line
     * @param A2 Second point first line
     * @param B1 First point second line
     * @param B2 Second point second line
     * @return Angle between two lines in degrees
     */
    
    public static float angleBetween2Lines(PointF A1, PointF A2, PointF B1, PointF B2) {
        float angle1 = (float) Math.atan2(A2.y - A1.y, A1.x - A2.x);
        float angle2 = (float) Math.atan2(B2.y - B1.y, B1.x - B2.x);
        float calculatedAngle = (float) Math.toDegrees(angle1 - angle2);
        if (calculatedAngle < 0) calculatedAngle += 360;
        return calculatedAngle;
    }
    

    It return positive value in degrees for any quadrant: 0 <= x < 360

    You can checkout my utility class here

提交回复
热议问题