Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you calculate the bouding rect for a string in Objective-C/Cocoa?

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?

like image 710
Jason Roberts Avatar asked Mar 04 '09 01:03

Jason Roberts


3 Answers

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

NSDictionary *attributes = [NSDictionary dictionaryWithObjectsAndKeys:[NSFont fontWithName:@"Helvetica" size:12], NSFontAttributeName, nil];
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.

like image 88
Jason Roberts Avatar answered Jan 11 '23 21:01

Jason Roberts


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.

like image 24
Brad Larson Avatar answered Jan 11 '23 23:01

Brad Larson


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.

like image 29
Peter Hosey Avatar answered Jan 11 '23 23:01

Peter Hosey