Finds the distance between point c and a line segment from a to b. - Android java.lang

Android examples for java.lang:Math Geometry

Description

Finds the distance between point c and a line segment from a to b.

Demo Code


import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import android.graphics.Point;
import android.util.FloatMath;

public class Main{
    /**//from  w w w.  ja va 2 s .  c  o m
     * Finds the distance between point c and a line segment from a to b.
     * @param a
     * @param b
     * @param c
     * @return
     */
    public static float pointLineDistance(Point a, Point b, Point c) {
        int px = b.x - a.x;
        int py = b.y - a.y;

        float denom = px * px + py * py;

        float u = ((c.x - a.x) * px + (c.y - a.y) * py) / denom;

        // limit between 0 and 1
        u = Math.min(u, 1);
        u = Math.max(u, 0);

        float x = Math.round(a.x + u * px);
        float y = Math.round(a.y + u * py);

        float dx = x - c.x;
        float dy = y - c.y;

        float dist = FloatMath.sqrt(dx * dx + dy * dy);

        return dist;
    }
}

Related Tutorials