Here you can find the source of projectPointOntoLine(Point2D pt, Line2D ln)
Parameter | Description |
---|---|
pt | point lying somewhere next to or on the line. |
ln | line onto which the pt should be projected |
public static Point2D projectPointOntoLine(Point2D pt, Line2D ln)
//package com.java2s; /*//from w w w .ja va2 s . com * GraphicsUtil.java * Eisenkraut * * Copyright (c) 2004-2015 Hanns Holger Rutz. All rights reserved. * * This software is published under the GNU General Public License v3+ * * * For further information, please contact Hanns Holger Rutz at * contact@sciss.de */ import java.awt.geom.Line2D; import java.awt.geom.Point2D; public class Main { /** * Calculates the one point on a line which is * nearest to a given point, such that a line * between the given and the returned point will * be orthogonal to the line. * * @param pt point lying somewhere next to or on the line. * @param ln line onto which the pt should be projected * @return the given point projected onto the line */ public static Point2D projectPointOntoLine(Point2D pt, Line2D ln) { double dx = ln.getX2() - ln.getX1(); double dy = ln.getY2() - ln.getY1(); double lineLenSq = dx * dx + dy * dy; double d1; if (lineLenSq == 0.0) { return (new Point2D.Double(ln.getX1(), ln.getY1())); } else { d1 = ((pt.getX() - ln.getX1()) * dx + (pt.getY() - ln.getY1()) * dy) / lineLenSq; return (new Point2D.Double(ln.getX1() + d1 * dx, ln.getY1() + d1 * dy)); } } }