How to test if point falls inside bezier path

Last week I was working on the Spider Chart library. The purpose of this library is to plot data in 2 dimensions. One unit of data is plotted along the pie and other in radial direction.

The problem I ran into was how to detect touch in one of the pie shapes. For example following is the sample spider chart.

spider_chart

If user touches inside orange section, it should be detected which section that was. It was a problem for me since I was not dealing with frames. It was simply bezier path with angle and radius parameters. One thing I tried was to take touch point and check the position inside pie shape. But it proved to be tricky too, since shape was curved.

Luckily, last week while going through similar pie-chart library which did the same thing I was looking for. Given a point, check if it falls inside given bezier path.

The function was straightforward, say user touches a graph and you have collection of CGPath objects stored in an array and you want to check if touch point falls within any one of them.


override public func touchesBegan(touches: Set, withEvent event: UIEvent?) {
        if let touch = touches.first {
            let touchLocation = touch.locationInView(self)
            let sliceLayers = self.layersCollection
            var transform = CGAffineTransformIdentity
            for (index, _) in sliceLayers.enumerate() {
                let path = paths[index]
                if CGPathContainsPoint(path, &transform, touchLocation, false) {
                    // Point falls within path having sequence number index.
                    break
                }
            }
        }
        super.touchesBegan(touches, withEvent:event)
    }

I have updated my Spider chart library with this new change. This new change is reflected on master as well as on the tag 0.3. You may clone and use the repo from Github page.

Jayesh Kawli

I am a web and mobile developer working at Wayfair in Boston, MA. I come to learn so many things during course of life and I write about things which helped me and feel like they can help others too.

Subscribe to Fresh Beginning

Get the latest posts delivered right to your inbox.

or subscribe via RSS with Feedly!