Re: Height of a string with fixed width and given font
Re: Height of a string with fixed width and given font
- Subject: Re: Height of a string with fixed width and given font
- From: Douglas Davidson <email@hidden>
- Date: Mon, 18 Feb 2002 15:36:49 -0800
On Monday, February 18, 2002, at 02:46 PM, Steve Bennett wrote:
In the "It should be trivial but this blasted documentation doesn't
show it"
department:
Simple Task -- I want to display a block of text (a single NSString) in
an
area which has a fixed width. The text could easily wrap, or contain
newlines, etc, and I want to know what the resulting total height of the
text will be if drawn with a specific font.
I would think that the NSString method sizeWithAttributes would be able
to
do this, but I've tried all kinds of attributes and can't find one which
will tell it to give me anything but the base font height.
I've read through the docs on just about every NSTextXxxx class,
NSLayoutManager, NSFont, NSAttributedString (and it's AppKit additions),
NSString (and it's Appkit additions), and NSTypesetter, and barring
writing
some massive function to use a dozen classes to calculate the wrap
points
and line endings and count the resulting lines and then use the font
height
to calculate the actual text height, I'm stumped.
Please tell me I'm missing something obvious? It seems ridiculous that
such
a trivial task could be so complex to do under cocoa...
There is a lacuna of sorts here in the string drawing methods, but it's
not that massive to do it yourself. As a matter of fact, the CircleView
example does something very much like this, although that may not be
immediately obvious. Adapting from the example gives something like
this (untested, but should be close):
float heightForStringDrawing(NSString *myString, NSFont *desiredFont,
float desiredWidth) {
NSTextStorage *textStorage = [[[NSTextStorage alloc]
initWithString:myString] autorelease];
NSTextContainer *textContainer = [[[NSTextContainer alloc]
initWithContainerSize:NSMakeSize(desiredWidth, 1e7)] autorelease];
NSLayoutManager *layoutManager = [[[NSLayoutManager alloc] init]
autorelease];
[textStorage addAttribute:NSFontAttributeName value:desiredFont
range:NSMakeRange(0, [textStorage length])];
[textContainer setLineFragmentPadding:0.0]; // padding usually
is not appropriate for string drawing
[layoutManager addTextContainer:textContainer];
[textStorage addLayoutManager:layoutManager];
(void)[layoutManager
glyphRangeForTextContainer:textContainer]; // force layout
return [layoutManager
usedRectForTextContainer:textContainer].size.height;
}
I make it nine lines and three classes for the function body...
Douglas Davidson
_______________________________________________
cocoa-dev mailing list | email@hidden
Help/Unsubscribe/Archives:
http://www.lists.apple.com/mailman/listinfo/cocoa-dev
Do not post admin requests to the list. They will be ignored.