用核心图形在一行中绘制带边框的矩形

6

如何一行代码画一个带边框的矩形?

有多种方法,比如:

CGContextStrokeRect(context, someRectangle);

并且

CGContextFillRect(context, someRectangle);

但是有没有一种同时实现这两个功能的东西呢?
3个回答

10
- (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);
}

虽然我不能说它比分别调用描边和填充的方式更加简洁...


嗯...非常正确,我想我只能选择分开调用。谢谢。 - chinabuffet

6
如果您只是想节省行空间,您可以定义自己的方法来进行两次调用,并将其放置在实用类中。
void strokeAndFill(CGContextRef c, CGRect rect)
{
    CGContextFillRect(c, rect);
    CGContextStrokeRect(c, rect);
}

-1

如果您事先设置填充和描边颜色,CGContextDrawPath会一次性完成。

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

8
嗯...我在头文件中看到CGContextDrawPath的签名是:CGContextDrawPath(CGContextRef c, CGPathDrawingMode mode) - chinabuffet

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接