4GetFullOf
4GetFullOf

Reputation: 1738

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 :)

Upvotes: 0

Views: 755

Answers (2)

rob mayoff
rob mayoff

Reputation: 386038

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;
}

Upvotes: 2

Ian MacDonald
Ian MacDonald

Reputation: 14030

There's no particularly efficient way to do this, but you could keep track of the number of points as you add them.

@interface MyPath : NSObject
@property (assign) int pointCount;
@property (assign) CGPathRef path;
@end

If you wanted to make sure you had complete control over it (and didn't want to worry about someone else incrementing your count or changing your path without incrementing), you could make the properties readonly and have an 'add point' function on the object ... Not great, but it would be more efficient than ApplyPath.

Upvotes: 2

Related Questions