Skip to content

Instantly share code, notes, and snippets.

@mcianni
Last active November 21, 2015 04:34
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mcianni/3890611 to your computer and use it in GitHub Desktop.
Save mcianni/3890611 to your computer and use it in GitHub Desktop.
Category on NSBezierPath to approximate the length of a curve
//
// NSBezierPath+Length.h
//
// Created by mcianni on 10/14/12.
//
#import <Cocoa/Cocoa.h>
@interface NSBezierPath (Length)
- (double)length;
@end
@implementation NSBezierPath (Length)
- (double)length
{
NSBezierPath *flattened_path = [self bezierPathByFlatteningPath];
int segments = (int)flattened_path.elementCount;
NSPoint last_point;
NSPoint point;
double length;
for (int i=0; i<segments; i++) {
/*
* Normally, elementAtIndex:associatedPoints: would set the variable
* passed to associatedPoints as an array of NSPoints with max
* size 3. However, since we've called bezierPathByFlatteningPath,
* we can assume we'll always get a single point. The other points
* are normally used as control points for bezier curves.
*/
NSBezierPathElement e = [flattened_path elementAtIndex:i
associatedPoints:&point];
// e == 0 is a moveToPoint command
if (e == 0) {
last_point = point;
}
else {
// distance formula
double distance = sqrt(pow(point.x - last_point.x, 2) +
pow(point.y - last_point.y, 2));
length += distance;
last_point = point;
}
}
return length;
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment