Search code examples
iosswiftcgpath

Find where on a path a touch is (by percentage)


I have a CGPath, and on that path I detect touches. The path is basically a line or a curve, but it is not filled. The idea is that the user strokes the path, so wherever the user has stroked along the path I'd like to draw the path with a different stroke/color etc.

First, to find if the touches are inside the path, and to give the user some room for error, I'm using CGPathCreateCopyByStrokingPath, and CGPointInsidePath. This works fine.

Next, I need to find how far along the path the user has stroked. That is today's question.

When that is done, and I have an answer like 33%, then I'd be a simple assignment to strokeEnd on the path. (two copies, one complete path, and one on top with strokeEnd set to whatever percentage of the complete path the user has stroked with his finger so far).

Any ideas how to find how far along the path the user has stroked his finger?


Solution

  • I have a utility class GHPathUtilies.m which includes a method:

    +(CGFloat) totalLengthOfCGPath:(CGPathRef)pathRef
    

    This is all written in Objective-C, but presumably you could use the same technique to walk along the path elements, using CGPathApply, until you are near enough, or have passed the target point. The general idea is to break the curves between each element into small line segments and keep a running sum of the length of each segment.

    Of course if the path doubles back on itself, you'll have to figure out which point is the touch point.