使用下面的代码,我正在构建具有不同数量边的多边形 .
有人可以建议我如何添加代码来限制圆圈并在每个返回的多边形中刻上一个圆圈吗?
-(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;
}
2 回答
终于把它弄出来了,感谢下面的一些指针代码下面添加到原始代码给了我需要的结果谢谢
您使用
CGContextAddEllipseInRect()
绘制圆圈,传入正方形CGRect . 计算矩形以适合您返回的每个多边形内部,这取决于您希望它适合的紧密程度 .