Search code examples
iosfunctioncgpointcgpath

Most efficient way to check number of CGPoints in CGPathRef


I want to find out if my CGMutablePathRef has more then 3 points! This checking will happen frequently so Im looking for an efficient solution.

This reason I need to do this is because in my project the user draws a shape. As the user drags his/her finger a CGPoint(current location of finger) is added to the path and a physical body is added when the touchEnded: is called.. now if the user just taps the screen the CGMutablePathRef only has one point in it(my reasoning in my head) and I get the following error when I use the my CGMutablePathRef for adding the physical body.

Assertion failed: (count >= 2), function CreateChain, file /SourceCache/PhysicsKit/PhysicsKit-6.5.4/PhysicsKit/Box2D/Collision/Shapes/b2ChainShape.cpp, line 45.

Im looking to make a function to call that takes a cgpathref as a parameter and counts the points until it reaches 3 (or the end if there isn't 3) and returns a bool

Thanks :)


Solution

  • If you want to enumerate the elements of a CGPath, you have to use CGPathApply, and there is no support for early termination. You must enumerate all of the elements.

    Grab my Rob_forEachElementOfCGPath function from this answer, and use it like this:

    int numberOfSegmentsInCGPath(CGPathRef path) {
        __block int count = 0;
        Rob_forEachElementOfCGPath(path, ^(const CGPathElement *element) {
            if (element->type != kCGPathElementMoveToPoint) {
                ++count;
            }
        });
        return count;
    }