Wednesday, May 27, 2009

Determining the dimensions of a text string before display

With 2D graphical rendering, such as Apple's Quartz SDK, you occasionally want to display text. However, the text position is something you do manually and could change, depending on circumstances (for example, if the text is centered on the screen). The short answer, is this is how you do it.

The big epiphany for me was that I was trying too hard to stick purely with Core Graphics and shying away from Objective-C. However, Apple has taken pains to ensure that, even though the syntax and nomenclature is somewhat of a mish-mash, they do interoperate nicely. Here is an example of my final code:

-(void)drawText:(CGContextRef)context text:(NSString*)text color:(UIColor*)color {
UIFont *font = [UIFont systemFontOfSize:24.0];
CGSize size = [text sizeWithFont:font];
CGPoint center = CGPointMake(160.0, 100.0);
CGPoint origin = CGPointMake(center.x - (size.width / 2.0), center.y - (size.height / 2.0));
CGContextSetFillColorWithColor(context, color.CGColor);
[text drawAtPoint:origin withFont:font];
}

It took way too long to get this code. I hope it doesn't happen again... *sigh*

No comments:

Post a Comment