Given two points {(x1,y1),(x2,y2)} returns {m,b} from the equation y = mx + b for a line which passes through both points. - Java 2D Graphics

Java examples for 2D Graphics:Line

Description

Given two points {(x1,y1),(x2,y2)} returns {m,b} from the equation y = mx + b for a line which passes through both points.

Demo Code


//package com.java2s;

public class Main {
    /**/*from w w w.  j  ava 2s.co  m*/
     * Given two points {(x1,y1),(x2,y2)} returns {m,b} from the equation y = mx + b for a line
     * which passes through both points.
     * 
     * @param x1 First x coordinate
     * @param y1 First y coordinate
     * @param x2 Second x coordinate
     * @param y2 Second y coordinate
     * @return The slope and y intercept of the line passing through the points provided
     */
    public static double[] getLineEquation(double x1, double y1, double x2,
            double y2) {
        double coefficient = (y2 - y1) / (x2 - x1);
        double shift = -(coefficient * x1) + y1;
        return new double[] { coefficient, shift };
    }

    /**
     * Given a rotation (in radians) and a single point (x,y) returns {m,b} from the equation y = mx + b
     * for a line which passes through (x,y) and is oriented by rotation many radians clockwise from the
     * pointing straight up position.
     * 
     * @param rotation The rotated orientation of the line from the straight up position
     * @param x The x coordinate
     * @param y The y coordinate
     * @return The slope and y intercept of the line passing through the point provided with the provided rotation
     */
    public static double[] getLineEquation(double rotation, double x,
            double y) {
        double coefficient = -(Math.cos(rotation) / Math.sin(rotation));
        double shift = -(coefficient * x) + y;
        return new double[] { coefficient, shift };
    }
}

Related Tutorials