distance To Line Segment - Android java.lang

Android examples for java.lang:Math Geometry

Description

distance To Line Segment

Demo Code

/*******************************************************************************
 * Copyright (c) 2011 MadRobot.//from w  w  w  . j a va 2s.  co  m
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the GNU Lesser Public License v2.1
 * which accompanies this distribution, and is available at
 * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
 * 
 * Contributors:
 *  Elton Kent - initial API and implementation
 ******************************************************************************/
//package com.java2s;

import android.graphics.PointF;

public class Main {
    /**
     * @param ax
     * @param ay
     * @param bx
     * @param by
     * @param px
     * @param py
     * @return The distance from p to the line segment a-b
     */
    public static float distanceToSegment(float ax, float ay, float bx,
            float by, float px, float py) {
        float vx = bx - ax;
        float vy = by - ay;
        float wx = px - ax;
        float wy = py - ay;

        double c1 = wx * vx + wy * vy;
        double c2 = vx * vx + vy * vy;

        if (c1 <= 0) {
            return (float) Math.hypot((ax - px), (ay - py));
        }
        if (c1 >= c2) {
            return (float) Math.hypot(bx - px, (by - py));
        }

        double b = c1 / c2;
        vx *= b;
        vy *= b;

        vx += ax;
        vy += ay;

        return (float) Math.hypot((vx - px), (vy - py));
    }

    public static float distanceToSegment(PointF pointStart,
            PointF pointEnd, PointF point) {
        return distanceToSegment(pointStart.x, pointStart.y, pointEnd.x,
                pointEnd.y, point.x, point.y);

    }
}

Related Tutorials