# uliwitness/UliKit

Code clean-up & comments of the regular polygon drawing code.

1 parent 5d87e21 commit a0b8ef13df8a71ea37265a96ae36361d3190ea8b committed Apr 30, 2011
Showing with 9 additions and 2 deletions.
1. +9 −2 NSBezierPath+ULIRegularPolygon.m
 @@ -13,6 +13,8 @@ @implementation NSBezierPath (ULIRegularPolygon) -(void) appendRegularPolygonAroundPoint: (NSPoint)centre startPoint: (NSPoint)startCorner cornerCount: (NSInteger)numCorners { + NSAssert( (numCorners >= 3), @"Too few corners on polygon." ); + // To draw a regular polygon, you simply calculate as many evenly-spaced // points on a circle as you need corners, then connect them with lines. @@ -23,24 +25,29 @@ -(void) appendRegularPolygonAroundPoint: (NSPoint)centre startPoint: (NSPoint)st if( xDiff <= 0 ) // Don't divide by zero, don't do work if there's nothing to draw. return; - CGFloat degrees = (xDiff == 0) ? 0 : ((yDiff == 0) ? 0.5 * M_PI : yDiff / xDiff); + CGFloat degrees = (xDiff == 0) ? 0 : ((yDiff == 0) ? 0.5 * M_PI : yDiff / xDiff); // Calc angle at which centre & startCorner are, so we know at what angle to put the first point. CGFloat stepSize = (2.0 * M_PI) / ((CGFloat)numCorners); + // Draw first corner at start angle: NSPoint firstCorner = NSZeroPoint; firstCorner.x = centre.x +radius * cos( degrees ); firstCorner.y = centre.y +radius * sin( degrees ); [self moveToPoint: firstCorner]; + // Now draw following corners: for( NSInteger x = 0; x < numCorners; x++ ) { NSPoint currCorner = NSZeroPoint; degrees += stepSize; + if( degrees > (2.0 * M_PI) ) + degrees -= (2.0 * M_PI); currCorner.x = centre.x +radius * cos( degrees ); currCorner.y = centre.y +radius * sin( degrees ); - [self lineToPoint: currCorner]; + [self lineToPoint: currCorner]; // Draw edge from prev to curr corner. } + // Now close the shape by drawing final edge: [self lineToPoint: firstCorner]; }