Last active
November 21, 2015 04:34
-
-
Save mcianni/3890611 to your computer and use it in GitHub Desktop.
Category on NSBezierPath to approximate the length of a curve
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// 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