繁体   English   中英

如何使用UIBezierPath在可可触摸中绘制多边形

[英]How to draw polygons in cocoa touch using UIBezierPath

我想绘制不同边的多边形(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];
            }

        }

现在要调整您的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);

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

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];  
} 

希望这可以帮助。 如果您有任何疑问,请随时提出并祝您愉快!

〜致命豪猪

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM