get Perpendicular Point To Line - Java java.lang

Java examples for java.lang:Math Geometry Line

Description

get Perpendicular Point To Line

Demo Code


//package com.java2s;

import java.awt.geom.Line2D;

import java.awt.geom.Point2D;

public class Main {
    /**//w  ww  . ja va  2  s .c  o  m
     * @return
     */
    public static Point2D.Double getPerpendicularPointToLine(Point2D ptA,
            Point2D ptB, Point2D ptC) {
        if (ptA == null || ptB == null || ptA.equals(ptB) || ptC == null) {
            return null;
        }

        double ax = ptA.getX(), ay = ptA.getY();
        double bx = ptB.getX(), by = ptB.getY();
        double cx = ptC.getX(), cy = ptC.getY();

        double r = ((ay - cy) * (ay - by) + (ax - cx) * (ax - bx))
                / Point2D.distanceSq(ax, ay, bx, by);

        return new Point2D.Double(ax + r * (bx - ax), ay + r * (by - ay));
    }

    public static Point2D.Double getPerpendicularPointToLine(Line2D line,
            Point2D ptC) {
        if (line == null || ptC == null) {
            return null;
        }
        return getPerpendicularPointToLine(line.getP1(), line.getP2(), ptC);
    }
}

Related Tutorials