Finding the height of a piece of text
Finding the height of a piece of text
- Subject: Finding the height of a piece of text
- From: Vincent Coetzee <email@hidden>
- Date: Fri, 23 Nov 2007 02:56:29 +0200
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);
}
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden