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: Steve Bennett <email@hidden>
- Date: Tue, 19 Feb 2002 10:45:55 -0500
on 2/18/02 6:36 PM, Douglas Davidson at email@hidden wrote:
>
On Monday, February 18, 2002, at 02:46 PM, Steve Bennett wrote:
>
>
> 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.
>
>
>
> <snip>
>
>
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;
>
}
Thanks. That worked perfectly. (The 1e7 threw me for a loop for a second
as I rarely use exponential constants... :)
-->Steve Bennett
_______________________________________________
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.