Created
March 12, 2014 10:35
-
-
Save randomsequence/9504445 to your computer and use it in GitHub Desktop.
Smooth CGPath from Array of Points
This file contains hidden or 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
// build a smooth CGPath from an array of CGPoints (stored as NSValues) | |
- (CGMutablePathRef)newPathFromPoints:(NSArray *)points { | |
CGMutablePathRef mutablePath = CGPathCreateMutable(); | |
NSUInteger pointCount = [points count]; | |
if (pointCount > 0) { | |
CGPoint p0 = [points[0] CGPointValue]; | |
CGPathMoveToPoint(mutablePath, NULL, p0.x, p0.y); | |
// for a single point, create a circle. When drawing, fill this. | |
if (pointCount == 1) { | |
CGFloat strokeWidth = self.lineStyle.strokeWidth; | |
CGRect pointRect = CGRectMake(p0.x - strokeWidth/2.0, | |
p0.y - strokeWidth/2.0, | |
strokeWidth, | |
strokeWidth); | |
CGPathAddPath(mutablePath, NULL, CGPathCreateWithEllipseInRect(pointRect, NULL)); | |
// for pointCount > 1 stroke the path | |
} else if (pointCount == 2) { | |
CGPoint p1 = [points[1] CGPointValue]; | |
CGPathAddLineToPoint(mutablePath, NULL, p1.x, p1.y); | |
} else { | |
CGPoint p1 = p0; | |
CGPoint p2; | |
for (NSUInteger i=0; i<pointCount-1; i++) { | |
p2 = [points[i+1] CGPointValue]; | |
CGPoint midPoint = CGPointMake((p1.x + p2.x)/2.0, | |
(p1.y + p2.y)/2.0); | |
CGPathAddQuadCurveToPoint(mutablePath, NULL, p1.x, p1.y, midPoint.x, midPoint.y); | |
p1 = p2; | |
} | |
} | |
} | |
return mutablePath; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment