views:

604

answers:

4

Using Objective-C/Cocoa how do you calculate the width and height required to draw a string based on a particular font? In C#/.Net you can do it like this:

SizeF textSize = graphics.MeasureString(someString, someFont);

Is there something like that available in Objective-C/Cocoa?

+4  A: 

You use the sizeWithAttributes: method.

http://snipr.com/d1jap

danielpunkass
+3  A: 

One way is sizeWithAttributes:, as danielpunkass said. The other way is to create an NSAttributedString and ask that for its size. The only difference is that one way gives you an object with the text and attributes together (the attributed string), whereas the other keeps them separate.

Peter Hosey
+3  A: 

The following code is similar to what I use for a cross-platform text CALayer:

#if defined(TARGET_IPHONE_SIMULATOR) || defined(TARGET_OS_IPHONE)
    UIFont *theFont = [UIFont fontWithName:fontName size:fontSize];
    CGSize textSize = [text sizeWithFont:theFont];
#else
    NSFont *theFont = [NSFont fontWithName:fontName size:fontSize];
    CGSize textSize = NSSizeToCGSize([text sizeWithAttributes:[NSDictionary dictionaryWithObject:theFont forKey: NSFontAttributeName]]);
#endif

This gives you a CGSize for an NSString named text, with a font name of fontName and size of fontSize.

Brad Larson
A: 

Here's a specific example based on the answers given by danielpunkass and Peter Hosey:

NSDictionary *attributes = [NSDictionary dictionaryWithObjectsAndKeys:[NSFont fontWithName:@"Helvetica" size:12]];
NSAttributedString * text = [[NSAttributedString alloc] initWithString:@"Hello" attributes: attributes];
NSSize textSize = [text size];

For those new to Objective-C/Cocoa like myself an example really goes a long way. If you're coming from C++/Java/C# or whatever the Objective-C syntax can appear really foreign and since Apple doesn't embed much if any sample code in their Cocoa documentation, learning this stuff is kind of difficult.

Jason Roberts