// 1获取文字的基本信息存入字典
NSDictionary *attributes = [NSDictionary dictionaryWithObjectsAndKeys:
[NSFont systemFontOfSize: [NSFont smallSystemFontSize]], NSFontAttributeName,
[NSParagraphStyle defaultParagraphStyle], NSParagraphStyleAttributeName,
nil];
NSSize size = NSMakeSize(200.0, MAXFLOAT);
NSRect bounds;
// 2获得该文字的高度和宽度
bounds = [@"This is a really really really really really really really long string that won't fit on one line"
boundingRectWithSize: size
options: NSStringDrawingUsesFontLeading
attributes: attributes];
NSLog(@"height: %02f, width: %02f", bounds.size.height, bounds.size.width);
// mac 还有一个动态获取文本高度的方法,但是此方法算出的高度会有一定的误差。蛋疼
// 动态调整文字的高度
float heightForStringDrawing(NSString *myString, NSFont *myFont,float myWidth)
{
//you instantiate the needed text objects and hook them together
NSTextStorage *textStorage = [[[NSTextStorage alloc]
initWithString:myString] autorelease];
NSTextContainer *textContainer = [[[NSTextContainer alloc]
initWithContainerSize: NSMakeSize(myWidth, FLT_MAX)] autorelease];
NSLayoutManager *layoutManager = [[[NSLayoutManager alloc] init]
autorelease];
// Once the text objects are created, you can hook them together:
[layoutManager addTextContainer:textContainer];
[textStorage addLayoutManager:layoutManager];
// Set the line fragment padding to 0 to get an accurate width measurement.
[textStorage addAttribute:NSFontAttributeName value:myFont
range:NSMakeRange(0, [textStorage length])];
[textContainer setLineFragmentPadding:0.0];
(void) [layoutManager glyphRangeForTextContainer:textContainer];
return [layoutManager usedRectForTextContainer:textContainer].size.height;
}