Given the coordinates of the start and end of a line, returns the angle in radians of the line - Java 2D Graphics

Java examples for 2D Graphics:Line

Description

Given the coordinates of the start and end of a line, returns the angle in radians of the line

Demo Code

/* Mesquite source code.  Copyright 1997 and onward, W. Maddison and D. Maddison. 


Disclaimer:  The Mesquite source code is lengthy and we are few.  There are no doubt inefficiencies and goofs in this code. 
The commenting leaves much to be desired. Please approach this source code with the spirit of helping out.
Perhaps with your help we can be more than a few, and make Mesquite better.

Mesquite is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY.
Mesquite's web site is http://mesquiteproject.org

This source code and its compiled class files are free and modifiable under the terms of 
GNU Lesser General Public License.  (http://www.gnu.org/copyleft/lesser.html)
 *//*from  w w  w .ja  v  a2  s  .c  om*/
//package com.java2s;

public class Main {
    /** Given the coordinates of the start and end of a line, returns the angle in radians of the line */
    public static double angleOfLine(int x1, int y1, int x2, int y2) {
        if (y1 == y2) //it's a horizontal line or a single point
            if (x2 >= x1)
                return 0.0;
            else
                return Math.PI;
        if (x1 == x2) //it's a vertical line or a single point
            if (y2 >= y1)
                return Math.PI / 2.0;
            else
                return -Math.PI / 2.0;
        double a = Math.PI - Math.atan(-(y2 - y1) * 1.0 / (x2 - x1));
        if (x2 > x1)
            a = Math.PI + a;
        return a;
    }
}

Related Tutorials