views:

290

answers:

2

How do I get a NSString's size as if it drew in an NSRect. The problem is when I try -[NSString sizeWithAttributes:], it returns an NSSize as if it had infinite width. I want to give a maximum width to the method. Is there any way of doing so? (BTW: Mac OS, not iPhone OS)

Thanks, Alex

+1  A: 

I believe your only option here is NSLayoutManager and asking for a union of the used rects for a given glyph range.

Joshua Nozzi
A: 
float heightForStringDrawing(NSString *myString, NSFont *myFont,
        float myWidth)
{
 NSTextStorage *textStorage = [[[NSTextStorage alloc] initWithString:myString] autorelease];
 NSTextContainer *textContainer = [[[NSTextContainer alloc] initWithContainerSize:NSMakeSize(myWidth, FLT_MAX)] autorelease];
 ;
        NSLayoutManager *layoutManager = [[[NSLayoutManager alloc] init] autorelease];
 [layoutManager addTextContainer:textContainer];
 [textStorage addLayoutManager:layoutManager];
 [textStorage addAttribute:NSFontAttributeName value:myFont
      range:NSMakeRange(0, [textStorage length])];
 [textContainer setLineFragmentPadding:0.0];

 (void) [layoutManager glyphRangeForTextContainer:textContainer];
 return [layoutManager
   usedRectForTextContainer:textContainer].size.height;
}

It was in the docs after all. Thank you Joshua anyway!

Alexandre Cassagne