简体   繁体   中英

How to draw polygons in cocoa touch using UIBezierPath

I want to draw polygon of different sides (4-12). What is the logic for drawing a polygon. For eg if user selects 6 side, it should draw a hexagon, if user enters 8 sides it should draw a octagon. I have found the following code but i also want to resize the UIView in which i am drawing a polygon so that the shape inside of the view also grows along with the view. Any body can help me please. Following is the code i am using currently but it is not positioned at the center also when i resize the view that shape moves to another position in the view.

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

        }

now to resize ur UIBazierPath you can add below code,

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);

If you want to make a regular polygon with any number of sides the following code will give you the vertices of each edge and it is easy to rescale in size and number of sides:

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

Hope this helps. If you have any questions feel free to ask and have a great day!

~Deadly Porcupine

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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