Re: Space Required By Text
Re: Space Required By Text
- Subject: Re: Space Required By Text
- From: Vince DeMarco <email@hidden>
- Date: Wed, 30 May 2001 13:20:43 -0700
On Wednesday, May 30, 2001, at 09:51 AM, David Remahl wrote:
Hi.
I have a text, which I would like to display in a text field. I would
like to size the text field on run time to fit exactly the text. The
text is line-broken by hard breaks, and occupies many lines, and
approximately 80 columns. I would like to know the rect in which the
text exactly fits using my font attributes.
I think this could be made using a constellation of NSTextContainer,
NSLayoutManager, NSTextStorage and possible other classes, but I don't
see how they fit.
Here is some code that does this
NSLayoutManager *layoutManager;
NSTextContainer *textContainer;
NSTextStorage *textStorage;
float newWidth;
NSRect drawingRect;
NSFont *myFont; /* Font used to display the string on the screen */
NSString *string; /* String to display on the screen */
newWidth = 80;
layoutManager = [[NSLayoutManager alloc] init];
textContainer = [[NSTextContainer alloc]
initWithContainerSize:NSMakeSize(newWidth,MAXFLOAT)];
textStorage = [[NSTextStorage alloc] initWithString:string
attributes:[NSDictionary
dictionaryWithObject:[myFont
forKey:NSFontAttributeName]];
[textStorage addLayoutManager:layoutManager];
[layoutManager addTextContainer:textContainer];
/* For the layoutmanager to recalculate everything */
(void)[layoutManager glyphRangeForTextContainer:textContainer];
drawingRect = [layoutManager usedRectForTextContainer:textContainer];
[layoutManager release];
[textContainer release];
[textStorage release];
drawingRect now contains the size of the text.
The above code assumes that newWidth is fixed and you only want to
change the height of the text text (IE wrap it to fit in a rectangle of
changing height)