chinabuffet
chinabuffet

Reputation: 5578

Core graphics draw rectangle with border in one line

How can I draw a rectangle with a border in one line?

There are separate methods like:

CGContextStrokeRect(context, someRectangle);

and

CGContextFillRect(context, someRectangle);

but is there something that does both in one?

Upvotes: 6

Views: 16464

Answers (3)

Daij-Djan
Daij-Djan

Reputation: 50089

CGContextDrawPath does it one go if you set fill and stroke color beforehand.

CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetStrokeColor(context, a);
CGContextSetFillColor(context, b);
CGContextDrawPath(context, rect)

Upvotes: -1

MJN
MJN

Reputation: 10808

If you're just looking to save line space, you could define your own method to make two calls and place it in a utility class.

void strokeAndFill(CGContextRef c, CGRect rect)
{
    CGContextFillRect(c, rect);
    CGContextStrokeRect(c, rect);
}

Upvotes: 6

FluffulousChimp
FluffulousChimp

Reputation: 9185

- (void)drawRect:(CGRect)rect {
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGPathRef path = CGPathCreateWithRect(rect, NULL);
    [[UIColor redColor] setFill];
    [[UIColor greenColor] setStroke];
    CGContextAddPath(context, path);
    CGContextDrawPath(context, kCGPathFillStroke);
    CGPathRelease(path);
}

Although, I can't say it's any less verbose than stroke & fill in separate calls...

Upvotes: 11

Related Questions