Calculates the angle between two line segments. - Android java.lang

Android examples for java.lang:Math Trigonometric Function

Description

Calculates the angle between two line segments.

Demo Code

/*/*  w ww.  j av  a2  s.c o  m*/
 * Copyright Kirill Morozov 2012
 * 
 * 
   This file is part of Mapper.

    Mapper is free software: you can redistribute it and/or modify
    it under the terms of the GNU Lesser General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    Mapper is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Lesser General Public License for more details.

    You should have received a copy of the GNU Lesser General Public License
    along with Mapper.  If not, see <http://www.gnu.org/licenses/>.
 * 
 * 
 */
import android.graphics.PointF;
import java.lang.Math;

public class Main{
    /**
     * Calculates the angle between two line segments. The two line segments that start at the same point 
     * @param start
     * @param end1
     * @param end2
     * @return the angle between the line segments [start, end1] and [start, end2]
     */
    public static float angleBetween(PointF start, PointF end1, PointF end2) {
        // Use cosine law: c^2 = a^2 + b^2 - 2abCos[theta]
        float a = distance(start, end1);
        float b = distance(start, end2);
        float c2 = (float) Math.pow(FloatHelper.distance(end1, end2), 2f);

        float a2 = (float) Math.pow(a, 2f);
        float b2 = (float) Math.pow(b, 2f);

        return (float) Math.acos((a2 + b2 - c2) / (2 * a * b));
    }
    public static float distance(PointF start, PointF end) {
        return (float) Math
                .sqrt((float) (Math.pow(end.x - start.x, 2) + Math.pow(
                        end.y - start.y, 2)));
    }
}

Related Tutorials