1

我想绘制不同边的多边形(4-12)。绘制多边形的逻辑是什么。例如,如果用户选择 6 边,它应该画一个六边形,如果用户输入 8 个边,它应该画一个八边形。我找到了以下代码,但我也想调整我正在绘制多边形的 UIView 的大小,以便视图内部的形状也随着视图一起增长。任何机构都可以帮助我。以下是我当前正在使用的代码,但是当我调整形状移动到视图中另一个位置的视图时,它也没有定位在中心。

    int radius = MINIMUM(widht, height)*0.4 ;

     for (int i = 0; i < _numberOFsides; i++){

            CGPoint point = CGPointMake(widht/2+radius *cosf(i*2*M_PI/_numberOFsides), widht/2+radius*sinf(i*2*M_PI/_numberOFsides));

            if (i==0) {

                [_shapePath moveToPoint:point];

            }
            else{
                [_shapePath addLineToPoint:point];

                [_shapePath stroke];
            }

        }
4

2 回答 2

1

现在要调整您的 UIBazierPath 的大小,您可以添加以下代码,

CGRect bazierRect = CGPathGetBoundingBox(bezierpath.CGPath)
CGFloat scaleX = view.frame.size.width / bazierRect.frame.size.width;
CGFloat scaleY = view.frame.size.height / bazierRect.frame.size.height;
CGAffineTransform transform = CGAffineTransformMakeScale(scaleX, scaleY);
CGPathRef newPath = CGPathCreateCopyByTransformingPath(bezierpath.CGPath, &transform);
bezierPath.CGPath = newPath;
CFRelease(newPath);
于 2013-03-05T09:40:02.277 回答
0

如果您想制作具有任意数量边的正多边形,以下代码将为您提供每条边的顶点,并且很容易重新调整大小和边数:

int n = 10; //number of edges
float j = 20; //length of each edge
float x = 130;
float y = 250;//the point 130,250 will be at the bottom of the figure
float angle = 2*M_PI;
for (int i = 0; i < n; i++) {

    CGRect frame = CGRectMake(x, y, 2, 2);//put a dot on x,y
    NSLog(@"%f | %f, %f", angle, x, y);
    x = x + j*cosf(angle); 
    y = y + j*sinf(angle); //move to the next point
    angle = angle - 2*M_PI/n; //update the angle

    //display the dot
    UIView *rect = [[UIView alloc] initWithFrame:frame];
    rect.backgroundColor = [UIColor blueColor];
    [self.view addSubview:rect];  
} 

希望这可以帮助。如果您有任何问题,请随时提问,祝您度过愉快的一天!

~致命豪猪

于 2013-07-11T15:09:57.630 回答