Return the x,y position at distance "length" into the given polyline. - Android Graphics

Android examples for Graphics:Path

Description

Return the x,y position at distance "length" into the given polyline.

Demo Code

/*******************************************************************************
 * Copyright (c) 2011 MadRobot.//from w  w w.ja va 2  s.c o 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
 ******************************************************************************/
import android.graphics.PointF;

public class Main{
    /**
     * Return the x,y position at distance "length" into the given polyline.
     * 
     * @param x
     *            X coordinates of polyline
     * @param y
     *            Y coordinates of polyline
     * @param length
     *            Requested position
     * @param position
     *            Preallocated to int[2]
     * @return True if point is within polyline, false otherwise
     */
    public static boolean findPolygonPosition(int[] x, int[] y,
            double length, int[] position) {
        if (length < 0) {
            return false;
        }

        double accumulatedLength = 0.0;
        for (int i = 1; i < x.length; i++) {
            double legLength = LineUtils.length(new PointF(x[i - 1],
                    y[i - 1]), new PointF(x[i], y[i]));
            if (legLength + accumulatedLength >= length) {
                double part = length - accumulatedLength;
                double fraction = part / legLength;
                position[0] = (int) Math.round(x[i - 1] + fraction
                        * (x[i] - x[i - 1]));
                position[1] = (int) Math.round(y[i - 1] + fraction
                        * (y[i] - y[i - 1]));
                return true;
            }

            accumulatedLength += legLength;
        }

        // Length is longer than polyline
        return false;
    }
}

Related Tutorials