Search code examples
androidgraphicsandroid-canvasgraphics2d

How to detect weather a line intersects with a path in android


I am drawing a path in android canvas. This works fine. Now i want to detect when a swipe gesture is made on screen whether it is made over the drawn path. I am using the gesture listener to detect 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;
        }
}

Inside FlingMovement i will get the start point and endpoint of the swipe. Then i need to check whether the line formed by these points intersects with any of the paths drawn in canvas. How can i do this?


Solution

  • Try this way

    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
            }