Java Geometry Algorithm projectPointOntoLine(Point2D pt, Line2D ln)

Here you can find the source of projectPointOntoLine(Point2D pt, Line2D ln)

Description

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.

License

Open Source License

Parameter

Parameter Description
pt point lying somewhere next to or on the line.
ln line onto which the pt should be projected

Return

the given point projected onto the line

Declaration

public static Point2D projectPointOntoLine(Point2D pt, Line2D ln) 

Method Source Code

//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));
        }
    }
}

Related

  1. prodEscalar(Point2D p1, Point2D p2)
  2. project(Point2D sourceLocation, double angle, double length)
  3. project(Point2D.Double sourceLocation, double angle, double length)
  4. projectionFactor(Point pt, Point start, Point stop)
  5. projectPoint(float x, float y, Line2D ray, float distance)
  6. quantisePoint(Point2D.Double dpos, Point gpos)
  7. relTo(final Point2D from, final Point2D to, final Point2D rel)
  8. resample(Vector points, int n, Vector newPoints)
  9. setPathAnchor(Shape s, Point2D pt)