Best way to obtain the width of a piece of text?
Best way to obtain the width of a piece of text?
- Subject: Best way to obtain the width of a piece of text?
- From: Steve Sims <email@hidden>
- Date: Thu, 8 Apr 2004 18:12:31 -0400
Hey gang,
I need to be able to work out what the width of a piece of text is, but
I'm having a few problems.
First up the code I had to do this is as follows:
// Get a font
NSFont *font = [NSFont labelFontOfSize:50.0];
// Create our text layout manager objects
NSTextStorage *textStore = [[NSTextStorage alloc] initWithString:
@"Test test test"];
NSTextContainer *textContainer = [[NSTextContainer alloc] init];
NSLayoutManager *myLayout = [[NSLayoutManager alloc] init];
[myLayout addTextContainer:textContainer];
[textStore addLayoutManager:myLayout];
[textStore setFont:font];
// Get the bounding rectangle for our text
NSRect glyphRect = [myLayout usedRectForTextContainer:textContainer];
// Get the width of our string, including any leading space
float stringWidth = glyphRect.size.width + glyphRect.origin.x;
Unfortunately though this doesn't work - stringWidth will be zero,
since all the values of glyphRect will be zero. It seems that the
layout system needs to be forced to work out the rectangle. Adding in
the following line before the line that grabs glyphRect accomplishes
this:
NSRange glyphRange = [myLayout
glyphRangeForTextContainer:textContainer];
Now there's actually another method to get the rectangle used for our
text, namely using the following call, which also makes use of the
glyphRange value:
NSRect glyphRect = [myLayout boundingRectForGlyphRange:glyphRange
inTextContainer:textContainer];
Curiously though using this call leads to a slightly smaller
stringWidth value by 5 units. This is, I feel, slightly bizarre.
Now for some truely odd behaviour try replacing the NSTextStorage line
with this:
NSTextStorage *textStore = [[NSTextStorage alloc] initWithString:
@"This is a test to see if I can make this fail.\tAnd it does."];
In this case the boundingRectForGlyphRange method of getting the width
gives us a stringWidth of 9999995. On the other hand
usedRectForTextContainer gives the value 1018.79. However this value
is wrong - it only gives the width of the text up to the tab character.
Smaller strings containing a tab character do get a correct width
calculated.
BTW I don't care about line wrapping at all, I just want to get the
width of a string as it would be if it were all rendered along a
straight line.
So I'm puzzled. Any ideas?
Steve
_______________________________________________
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.