Drawing Text

Discussion in 'iOS Programming' started by printf, May 24, 2010.

  1. printf macrumors regular

    Aug 27, 2008
    I'm trying to draw text to a custom UIView, but from what I can tell using Quartz 2D isn't quite as flexible as say, ATSU. For example, this text doesn't break at the newline character:

    CGContextShowTextAtPoint(ctx, 10, 10, "this\nis a test", strlen("this\nis a test"));

    and I don't think I can use bounding rects to have a body of text break naturally at the specified bounds.

    What can i use alternatively? A lot of the documentation references ATSU, but doesn't provide links, which I'm guessing is Apple's subtle way of saying it's deprecated. I don't need anything as advanced as rtf, just something beyond what's available out of the box with CGContext
  2. Sander macrumors 6502

    Apr 24, 2008
    Just use Cocoa Text? Quartz is rather low level.
  3. robbieduncan Moderator emeritus


    Jul 24, 2002
    UIView implies this is on the iPhone so Cocoa Text is most likely not available. Of course the poster should have posted it in the correct place to start with.
  4. Sander macrumors 6502

    Apr 24, 2008
  5. printf thread starter macrumors regular

    Aug 27, 2008
    thanks for the responses. NSString won't work as i need to write to a CGContext. Sorry, just realized my original post didn't indicate that.

    are there any other options? also is ATSU definitely deprecated?
  6. Sander macrumors 6502

    Apr 24, 2008
    In that case, you can still use Cocoa Text. You'll have to set the current graphics context to your CGContext temporarily, with something like this:

    NSGraphicsContext *current = [NSGraphicsContext currentContext]; // for restoration later on
    NSGraphicsContext *nsContext = [NSGraphicsContext graphicsContextWithGraphicsPort:yourCGContextRef flipped:NO];
    [NSGraphicsContext setCurrentContext:nsContext];
    // your Cocoa drawing here
    // [myNSString drawInRect ...];
    [NSGraphicsContext setCurrentContext:current];
  7. kainjow Moderator emeritus


    Jun 15, 2000
    NSGraphicsContext is part of AppKit which is not available on the iPhone.

    If you're using CGContextRef directly you can use the NSString drawing methods. But you probably need to use UIGraphicsPushContext() and UIGraphicsPopContext() before and after you call any UIKit drawing methods.

Share This Page