Skip navigation.
 
mlFinding the height of a piece of text
FROM : Vincent Coetzee
DATE : Fri Nov 23 01:56:29 2007

Dear List,

I am attempting to find the height of a piece of text in a particular 
font and color, given that it must be laid out within a specified 
width. There is a piece of code in the "Text Layout Programming Guide" 
that shows how to do this. I have incorporated this code into my 
class, and use various constituents of the Text System, to not only 
calculate the size of my text, but also to display it. I have tried 
various different ways of doing this, up to and including using both 
NSTextViews, NSTextFields and NSTextFieldCells, to do the layout and 
display. I however always end up with the same problem, in that the 
height that I calculate for my text (as per the code in the "Text 
Layout Programming Guide") is always too small (by about ~1 line 
height) . Does anyone have a working solution to this problem or a 
more elegant method of solving it ? I attach my code below. The code 
correctly initializes the various components, and I have checked that 
the font, color and stringValue are all correctly set. I finally call 
desiredHeightForWidth: aWidth to ascertain the correct height, and the 
result is always incorrect.

Thanks in advance

Vincent

- (void) initialize
   {
   [super initialize];
   theDesiredWidth = 10.0f;
   theTextStorage  = [[NSTextStorage alloc] initWithString: @""];
   theTextContainer = [[NSTextContainer alloc] initWithContainerSize: 
NSMakeSize(theDesiredWidth, FLT_MAX)];
   theLayoutManager = [[NSLayoutManager alloc] init];
   [theLayoutManager addTextContainer: theTextContainer];
   [theTextStorage addLayoutManager: theLayoutManager];
   [theTextContainer setLineFragmentPadding:0.0];
   }

- (void) setStringValue: (NSString*) string
   {
   [theTextStorage replaceCharactersInRange: NSMakeRange(0,
[theTextStorage length]) withString: string];
   }

- (float) desiredHeightForWidth: (float) width
   {
   [theTextStorage setFont: [self font]];
   [theTextStorage setForegroundColor: [self textColor]];
   [theTextContainer setContainerSize: NSMakeSize(width,FLT_MAX)];
   [theLayoutManager glyphRangeForTextContainer: theTextContainer];
   return([theLayoutManager usedRectForTextContainer: 
theTextContainer].size.height);
   }

Related mailsAuthorDate
mlFinding the height of a piece of text Vincent Coetzee Nov 23, 01:56
mlRe: Finding the height of a piece of text Nygard Steve Nov 23, 07:39
mlRe: Finding the height of a piece of text Vincent Coetzee Nov 23, 10:16
mlRe: Finding the height of a piece of text Jerry Krinock Nov 23, 16:00
mlRe: Finding the height of a piece of text Aki Inoue Nov 26, 19:11
mlRe: Finding the height of a piece of text Aki Inoue Nov 26, 22:04