Reputation: 22731
I am drawing a simple stroked circle using the following class:
@implementation StrokedCircle
- (id)initWithRadius:(CGFloat)radius strokeWidth:(CGFloat)strokeWidth strokeColor:(UIColor *)strokeColor
{
self = [super initWithRadius:radius];
if (self)
{
_strokeWidth = strokeWidth;
_strokeColor = strokeColor;
}
return self;
}
- (void)drawRect:(CGRect)rect
{
NSLog(@"Drawing with color %@ and stroke width %f", self.strokeColor, self.strokeWidth);
CGContextRef context = UIGraphicsGetCurrentContext();
CGRect circleRect = CGRectInset(rect, self.strokeWidth, self.strokeWidth);
CGContextAddEllipseInRect(context, circleRect);
CGContextSetLineWidth(context, self.strokeWidth);
CGContextSetStrokeColor(context, CGColorGetComponents([self.strokeColor CGColor]));
CGContextStrokePath(context);
}
@end
Note: the superclass is a simple circle (sublass of UIView
) with a radius
property that is set and where the backgroundcolor of the view is set to clearColor
.
In a view controller, I add the following code in viewDidLoad
:
- (void)viewDidLoad
{
[super viewDidLoad];
StrokedCircle *strokedCircle = [[StrokedCircle alloc] initWithRadius:50.0 strokeWidth:1.0 strokeColor:[UIColor blueColor]];
strokedCircle.center = self.view.center;
[self.view addSubview:strokedCircle];
}
This actually works fine, the console outputs:
2014-06-14 10:31:58.270 ShapeTester[1445:60b] Drawing with color UIDeviceRGBColorSpace 0 0 1 1 and stroke width 1.000000
and a blue circle is shown in the middle of the screen.
However, when I modify the color to [UIUColor blackColor]
, [UIColor grayColor]
, or [UIColor whiteColor]
(but then also changing the view's backgroundColor
), no circle is shown any more.
Does anyone know what the reason for this behaviour is? Doesn't core graphics draw grayscale colors? I read through the appropriate section in the Core Graphics Programming Guide but nothing like this was mentioned there.
Upvotes: 1
Views: 674
Reputation: 385500
Black, white, and gray (as returned by the methods you named) aren't in the RGB color space. They're in the grayscale color space. The grayscale color space only has one component (plus alpha), not three (plus alpha). So you're only setting one of the components of the stroke color, and the other two components are undefined. You're probably ending up setting alpha to zero due to this problem, so you don't get anything.
Don't use CGContextSetStrokeColor
. It requires you to worry about the color space (which you would need to set using CGContextSetStrokeColorSpace
). Instead, use CGContextSetStrokeColorWithColor
, which sets both the color space and the color components:
CGContextSetStrokeColorWithColor(context, self.strokeColor.CGColor);
Upvotes: 7