使用Core Graphics绘制多个弧

时间:2013-08-14 20:50:09

标签: core-graphics

我正在尝试使用Core Graphics绘制两个同心圆。我希望以下代码在内部绘制一个蓝色圆圈和一个较小的白色圆圈,但它只绘制蓝色圆圈。我错过了什么?

CGContextRef c = UIGraphicsGetCurrentContext();

CGContextAddArc(c, self.bounds.size.width/2, self.bounds.size.height/2, 100, 0, M_PI * 2, true);
CGContextSetFillColor(c, CGColorGetComponents([[UIColor blueColor] CGColor]));
CGContextFillPath(c);

CGContextAddArc(c, self.bounds.size.width/2, self.bounds.size.height/2, 90, 0, M_PI * 2, true);
CGContextSetFillColor(c, CGColorGetComponents([[UIColor whiteColor] CGColor]));
CGContextFillPath(c);

1 个答案:

答案 0 :(得分:2)

您正在以不必要的间接方式设置填充颜色。这样做:

CGContextAddArc(c, self.bounds.size.width/2, self.bounds.size.height/2, 100, 0, M_PI * 2, true);
CGContextSetFillColorWithColor(c, [[UIColor blueColor] CGColor]);
CGContextFillPath(c);

CGContextAddArc(c, self.bounds.size.width/2, self.bounds.size.height/2, 90, 0, M_PI * 2, true);
CGContextSetFillColorWithColor(c, [[UIColor whiteColor] CGColor]);
CGContextFillPath(c);

或者,更好的是,直接使用UIKit的绘图方法:

[[UIColor blueColor] setFill];
[[UIBezierPath bezierPathWithArcCenter:CGPointMake(self.bounds.size.width/2, self.bounds.size.height/2) radius:100 startAngle:0 endAngle:M_PI * 2 clockwise:YES] fill];

[[UIColor whiteColor] setFill];
[[UIBezierPath bezierPathWithArcCenter:CGPointMake(self.bounds.size.width/2, self.bounds.size.height/2) radius:90 startAngle:0 endAngle:M_PI * 2 clockwise:YES] fill];

您的代码失败,因为[[UIColor whiteColor] CGColor]返回“灰色”颜色空间中的颜色,该颜色空间只有两个组件,“灰色”值(黑色为0,白色为1)和alpha值。在这种情况下,上下文是RGBA,因此CGContextSetFillColor期望看到4个组件,三个用于RGB,一个用于alpha。

The documentation for CGContextSetFillColor指出:

  

请注意,现在使用的首选API   CGContextSetFillColorWithColor。

相关问题