NSString UIKit additions provide vital Quartz text drawing enhancements

One of the distinctive features of Objective-C is categories. They allow you to add methods to a class without changing the original class’s source code (or deriving a subclass). I mostly use categories as a way to keep private methods out of the public interface of my own classes. But Apple has used them in the iOS SDK in the way they were originally intended.

I was struggling with drawing text in Quartz 2D when I stumbled on the NSString UIKit additions. There’s really no other good way to measure text before you draw it. You’ll need to do this to position text on a chart, for instance, as in my Climate Pathways app. The additions make Core Graphics much easier by allowing the use of UIKit objects. Now I use them everywhere to draw text.

They’re pretty straigtforward, but I got stuck when I tried to use them in CALayers. The additions assume they will be used in a view. They get the current graphics context for you by looking at the context pushed on the stack before drawRect: is called. If you are drawing dirctly in a layer, the context is not pushed on the stack. You have to do it yourself before calling the additions.

- (void)drawLayer:(CALayer *)layer inContext:(CGContextRef)c {
	UIGraphicsPushContext(c);
	CGPoint textPos = CGPointMake(MESSAGE_MARGIN_HORZ, MESSAGE_MARGIN_VERT - 1);
	[messageColor setFill];
	[messageText drawAtPoint:textPos withFont:messageFont];
	UIGraphicsPopContext();
}

Note that the text coordinate system does not need to be flipped when drawing text this way.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>