Search code examples
iphoneobjective-cpolygonquartz-graphicscgpoint

Draw a irregular polygon on iphone


i have this question: i have a array of points and i would draw a irregular polygon by this points with Quartz or similar. Can you suggest me the best way to make this?

MyTest drawRect is this:

- (void)drawRect:(CGRect)rect
{
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    CGContextClearRect(ctx, rect);

    CGContextSetRGBStrokeColor(ctx, 255, 0, 255, 1);
    CGPoint points[6] = { CGPointMake(100, 200), CGPointMake(150, 250),
        CGPointMake(150, 250), CGPointMake(50, 250),
        CGPointMake(50, 250), CGPointMake(100, 200) };
    CGContextStrokeLineSegments(ctx, points, 6);
}

Solution

  • You can use UIBezierPath / NSBezierPath:

    UIBezierPath *poly = [[UIBezierPath alloc] init];
    [poly moveToPoint:CGPointMake(0.0, 0.0)];
    [poly addLineToPoint:CGPointMake(1.0, 0.0)];
    [poly addLineToPoint:CGPointMake(1.0, 1.0)];
    [poly closePath];
    [poly stroke]; // draw stroke
    [poly release];