Search code examples
objective-cioscore-graphicsdrawrect

draw a stroke around the shape, core graphic


I am drawing a shape like following :

- (void)drawRect:(CGRect)rect
{
    // Draw a cross rectagle
    CGContextRef    context     =   UIGraphicsGetCurrentContext();
    CGContextSaveGState(context);
    CGContextMoveToPoint(context, 190, 0);
    CGContextAddLineToPoint(context, 220, 0);
    CGContextAddLineToPoint(context, 310, 90);
    CGContextAddLineToPoint(context, 310, 120);
    CGContextSetFillColorWithColor(context, [UIColor lightGrayColor].CGColor);
    CGContextFillPath(context);
    CGContextRestoreGState(context);
}

I am getting a light-dark cross flag below

enter image description here

Now I would like to draw a stroke around the cross flag I have just drawn

What should I do to achieve this. Please advice me on this issue. Thanks.


Solution

  • Surely CGContextDrawPath(context, kCGPathFillStroke); is what you're after

    You can adjust the pattern and color using:

    CGContextSetStrokePattern
    CGContextSetStrokeColor
    

    https://developer.apple.com/library/ios/#documentation/graphicsimaging/reference/CGContext/Reference/reference.html

    So, in your case, assuming you want a plain black stroke, you'd have:

    - (void)drawRect:(CGRect)rect
    {
        CGContextRef    context     =   UIGraphicsGetCurrentContext();
        CGContextSaveGState(context);
    
        CGContextSetLineWidth(context, 2.0);
        CGContextSetStrokeColorWithColor(context, [UIColor blackColor].CGColor);
        CGContextSetFillColorWithColor(context, [UIColor lightGrayColor].CGColor);
    
        CGContextMoveToPoint(context, 190, 0);
        CGContextAddLineToPoint(context, 220, 0);
        CGContextAddLineToPoint(context, 310, 90);
        CGContextAddLineToPoint(context, 310, 120);
        CGContextClosePath(context);
    
        CGContextDrawPath(context, kCGPathFillStroke);
        CGContextFillPath(context);
    
        CGContextRestoreGState(context);
    }
    

    Produces:

    Reminds me of Kraftwork! Result of drawRect: