Java Geometry Algorithm nearestPointOnLine(Line2D l, Point2D p, boolean clampToSegment, Point2D dest)

Here you can find the source of nearestPointOnLine(Line2D l, Point2D p, boolean clampToSegment, Point2D dest)

Description

nearest Point On Line

License

Apache License

Declaration

public static Point2D nearestPointOnLine(Line2D l, Point2D p, boolean clampToSegment, Point2D dest) 

Method Source Code


//package com.java2s;
//License from project: Apache License 

import java.awt.geom.Line2D;
import java.awt.geom.Point2D;

public class Main {
    public static Point2D nearestPointOnLine(Line2D l, Point2D p, boolean clampToSegment, Point2D dest) {
        if (dest == null) {
            dest = new Point2D.Double();
        }/*  w ww.  ja  v a 2 s .  c  o  m*/

        double apx = p.getX() - l.getX1();
        double apy = p.getY() - l.getY1();
        double abx = l.getX2() - l.getX1();
        double aby = l.getY2() - l.getY1();

        double ab2 = abx * abx + aby * aby;
        double ap_ab = apx * abx + apy * aby;
        double t = ap_ab / ab2;
        if (clampToSegment) {
            if (t < 0) {
                t = 0;
            } else if (t > 1) {
                t = 1;
            }
        }
        dest.setLocation(l.getX1() + abx * t, l.getY1() + aby * t);
        return dest;
    }
}

Related

  1. makeNeighbor(Point theHex, int direction)
  2. manhattanDistance(Point a, Point b)
  3. mirrorMoveVertically(Point move, int size)
  4. nearestColinearPoint(final double x1, final double y1, final double x2, final double y2, double x, double y)
  5. nearestColinearPoint(final Line2D segment, final Point2D point)
  6. newZeroPoint()
  7. oneThirdPoint(@Nonnull Point2D pA, @Nonnull Point2D pB)
  8. parabolaByFocusAndDirectrix(Point2D.Double focus, double directrix)
  9. parameterizeCurve(Point[] coefficients, Point startPoint, Point endPoint, Point controlPoint1, Point controlPoint2)