如何检测线与android中的路径相交的天气

时间:2013-09-10 11:04:21

标签: android graphics android-canvas graphics2d

我正在Android画布中绘制一条路径。这很好用。现在我想检测何时在屏幕上进行滑动手势是否在绘制的路径上进行。我正在使用手势监听器来检测FlingMovement。

private class GestureListener extends GestureDetector.SimpleOnGestureListener {

        private static final int SWIPE_MIN_DISTANCE = 120;
        private static final int SWIPE_MAX_OFF_PATH = 250;
        private static final int SWIPE_THRESHOLD_VELOCITY = 200;
@Override
        public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
                float velocityY) 
        {
            try 
            {
                if (Math.abs(e1.getX() - e2.getX()) > SWIPE_MAX_OFF_PATH){
                    return false;
                }

                if (e1.getY() - e2.getY() > SWIPE_MIN_DISTANCE
                        && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) 
                {
                    //Here find whether the swipe occured on any of the paths drawn in canvas
                }
            }
            catch(Exception e)
            {

            }
            return true;
        }
}

在FlingMovement内部,我将获得滑动的起点和终点。然后我需要检查这些点形成的线是否与画布中绘制的任何路径相交。我怎么能这样做?

2 个答案:

答案 0 :(得分:1)

尝试此代码,它会检测线是否与路径相交,

import android.graphics.Point;
import java.util.List;

static Boolean isPathComplex(List<Point> path) {

    if (path == null || path.size() <= 2) {
        return false;
    }

    int len = path.size();  

   for (int i = 1; i < len; i++) {
        Point lineAStart = path.get(i - 1);
        Point lineAEnd = path.get(i);

        for (int j = i + 1; j < len; j++) {
            Point lineBStart = path.get(j - 1);
            Point lineBEnd = path.get(j);
            if (lineSegmentsIntersect(lineAStart, lineAEnd, lineBStart, lineBEnd)) {
                return true;
            }

        } // inner loop

   } // outer loop

}

static Boolean lineSegmentsIntersect(Point aInitial, Point aFinal, Point bInitial, Point bFinal) {
    // left as an exercise to the reader
}

答案 1 :(得分:0)

试试这种方式

Path pp; // your path variable which is drawn on canvas

        RectF rectPathBounds=new RectF();
        pp.computeBounds(rectPathBounds,true);

        if(rectPathBounds.contains((int) event.getX(), (int) event.getY())){
            //your action
        }