0

I'm having trouble drawing a string in a custom CALayer. The drawInContext method is called but nothing is visible on the screen. I can fill the layer with a solid colour but can't seem to draw a string onto it.

Any suggestions? Thanks.

- (void)drawInContext:(CGContextRef)ctx
{
    CGContextSaveGState(ctx);

    NSString *myString = @"Hello World";    
    NSDictionary *attr = [NSDictionary dictionaryWithObjectsAndKeys:
                                    [NSFont systemFontOfSize:14], NSFontAttributeName, nil];

    [myString drawAtPoint:NSMakePoint(0,0) withAttributes:attr];

    CGContextRestoreGState(ctx);
}

2 Answers 2

3

I didn't want to use Quartz to draw a string but I guess I have to. So here is what I ended up doing

   NSString *string = @"Hello world";
   CGContextSelectFont (ctx,"Helvetica", 24, kCGEncodingMacRoman);
   CGContextSetTextDrawingMode (ctx, kCGTextFillStroke);
   CGContextShowTextAtPoint (ctx, 40, 40, [string UTF8String], (int)[string length]);

Alternative solution

    [NSGraphicsContext saveGraphicsState];

    NSGraphicsContext *currentContext = [NSGraphicsContext graphicsContextWithGraphicsPort:theContext flipped:NO];
    [NSGraphicsContext setCurrentContext:currentContext]; 

    //Draw here

    [NSGraphicsContext restoreGraphicsState];
0

You'd probably want to use a CATextLayer. Get the parent layer, add your text to the TextLayer, then use -addSublayer to add the TextLayer to the parent layer.

1
  • I have text of various properties that I need to draw. I would rather draw the text myself since it is more versatile than creating a CATextLayer for all my strings and putting in a parent layer.
    – David
    Mar 15, 2011 at 2:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.