8
votes

I am trying to draw in a CALayer subclass. The drawInContext is called with setNeedsDisplay but nothing is drawn. What am doing/getting wrong here ?

 - (void)drawInContext:(CGContextRef)ctx
{
    CGContextSetFillColorWithColor(ctx, [UIColor redColor].CGColor);
    [[UIBezierPath bezierPathWithRect:CGRectMake(100, 100, 100, 100)] fill];

    [@"Vowel" drawAtPoint:CGPointMake(0, 0) withFont:[UIFont fontWithName:@"Chalkboard" size:14]];
}

Edit I am getting this error :

CGContextAddPath: invalid context 0x0

Thanks Shani

1

1 Answers

31
votes

You're mixing CG calls and UIKit calls. -[UIBezierPath fill] and -[NSString drawAtPoint:withFont:] both draw into the context at the top of the UIKit context stack. That's not the same thing as the context passed into -drawInContext:. You should modify your function to look like:

- (void)drawInContext:(CGContextRef)ctx {
    UIGraphicsPushContext(ctx);
    [[UIColor redColor] setFill];
    [[UIBezierPath bezierPathWithRect:CGRectMake(100, 100, 100, 100)] fill];
    [@"Vowel" drawAtPoint:CGPointMake(0, 0) withFont:[UIFont fontWithName:@"Chalkboard" size:14]];
    UIGraphicsPopContext();
}