5
使用下面的代碼,我正在構造具有不同數量邊的多邊形。使用CGContext的繪圖圈
有人可以建議如何添加代碼來限定一個圓,並在每個多邊形中還有一個圓?
-(void) drawRect:(CGRect)rect{
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextBeginPath (context);
CGContextSetLineWidth(context,5);
NSArray * points = [PolygonUIView pointsForPolygonInRect:[self bounds] numberOfSides:polygon.numberOfSides];
NSLog(@"%d", [points count]);
NSLog(@"%d", polygon.numberOfSides);
for(NSValue * point in points) {
CGPoint val = [point CGPointValue];
if([points indexOfObject:point]==0)
{
CGContextMoveToPoint (context, val.x, val.y);
}
else
{
CGContextAddLineToPoint (context, val.x, val.y);
}
}
CGContextClosePath(context);
[[UIColor clearColor] setFill];
[[UIColor blackColor] setStroke];
CGContextDrawPath (context, kCGPathFillStroke);
polygonLabel.text = polygon.name;
}
+ (NSArray *)pointsForPolygonInRect:(CGRect)rect numberOfSides:(int)numberOfSides {
CGPoint center = CGPointMake(rect.size.width/2.0, rect.size.height/2.0);
float radius = 0.90 * center.x;
NSLog(@"%f rad",radius);
NSMutableArray *result = [NSMutableArray array];
float angle = (2.0 * M_PI)/numberOfSides;
float exteriorAngle = M_PI - angle;
float rotationDelta = angle - (0.5 * exteriorAngle);
for (int currentAngle = 0; currentAngle < numberOfSides; currentAngle++) {
float newAngle = (angle * currentAngle) - rotationDelta;
float curX = cos(newAngle) * radius;
float curY = sin(newAngle) * radius;
[result addObject:[NSValue valueWithCGPoint:CGPointMake(center.x + curX,
center.y + curY)]];
}
return result;
}
喜感謝您的答案,但需要如何計算得分更多的解釋以便返回的每個多邊形都被限制並正確刻錄 – superllanboy 2012-03-17 08:08:26
對於任何可能的多邊形都有一個通用答案?我不知道我害怕,你可能需要問數學交換。你可能會在CGPathGetBoundingBox的某個地方找到一個包含你的路徑的矩形,然後找出對角線來給出你的半徑? – jrturton 2012-03-17 08:18:40
你好,謝謝你的回答 - 你給了我一個主意的種子,所以我會擺弄,看看我能不能把它工作 – superllanboy 2012-03-17 09:11:47