get Gesture Direction - Android User Interface

Android examples for User Interface:Key Event

Description

get Gesture Direction

Demo Code


//package com.java2s;

public class Main {
    private static final int DIRECTION_DOWN = 6;
    private static final int DIRECTION_DOWN_LEFT = 7;
    private static final int DIRECTION_DOWN_RIGHT = 5;
    private static final int DIRECTION_LEFT = 8;
    private static final int DIRECTION_RIGHT = 4;
    private static final int DIRECTION_UP = 2;
    private static final int DIRECTION_UP_LEFT = 1;
    private static final int DIRECTION_UP_RIGHT = 3;
    private static final int NO_DIRECTION = 0;
    private static double MIN_DISTANCE = 100;

    /**/*from   www .java 2s.  c o m*/
     * @param touchDown_x
     * @param touchDown_y
     * @param touchUp_x
     * @param touchUp_y
     * @return
     */
    private static int getGestureDirection(int touchDown_x,
            int touchDown_y, int touchUp_x, int touchUp_y) {

        int direction = NO_DIRECTION;
        double dx = touchUp_x - touchDown_x;
        double dy = touchUp_y - touchDown_y;
        double angle = (Math.atan2(dx, dy) * 180) / Math.PI;

        if (getMoveDistance(touchDown_x, touchDown_y, touchUp_x, touchUp_y) >= MIN_DISTANCE) {

            if (angle >= 157.5 || angle <= -157.5) {

                direction = DIRECTION_UP;

            } else if (angle >= 112.5 && angle <= 157.5) {

                direction = DIRECTION_UP_RIGHT;

            } else if (angle >= 67.5 && angle <= 112.5) {

                direction = DIRECTION_RIGHT;

            } else if (angle >= 22.5 && angle <= 67.5) {

                direction = DIRECTION_DOWN_RIGHT;

            } else if (angle >= -22.5 && angle <= 22.5) {

                direction = DIRECTION_DOWN;

            } else if (angle >= -67.5 && angle <= -22.5) {

                direction = DIRECTION_DOWN_LEFT;

            } else if (angle >= -112.5 && angle <= -67.5) {

                direction = DIRECTION_LEFT;

            } else if (angle >= -157.5 && angle <= -112.5) {

                direction = DIRECTION_UP_LEFT;

            }
        }

        return direction;

    }

    /**
     * @param touchDown_x
     * @param touchDown_y
     * @param touchUp_x
     * @param touchUp_y
     * @return
     */
    private static double getMoveDistance(int touchDown_x, int touchDown_y,
            int touchUp_x, int touchUp_y) {

        double dx = touchUp_x - touchDown_x;
        double dy = touchUp_y - touchDown_y;

        double distance = Math.sqrt(dx * dx + dy * dy);

        return distance;

    }
}

Related Tutorials