Ale*_*gne 18
float heightForStringDrawing(NSString *myString, NSFont *myFont,
float myWidth)
{
NSTextStorage *textStorage = [[[NSTextStorage alloc] initWithString:myString] autorelease];
NSTextContainer *textContainer = [[[NSTextContainer alloc] initWithContainerSize:NSMakeSize(myWidth, FLT_MAX)] autorelease];
;
NSLayoutManager *layoutManager = [[[NSLayoutManager alloc] init] autorelease];
[layoutManager addTextContainer:textContainer];
[textStorage addLayoutManager:layoutManager];
[textStorage addAttribute:NSFontAttributeName value:myFont
range:NSMakeRange(0, [textStorage length])];
[textContainer setLineFragmentPadding:0.0];
(void) [layoutManager glyphRangeForTextContainer:textContainer];
return [layoutManager
usedRectForTextContainer:textContainer].size.height;
}
Run Code Online (Sandbox Code Playgroud)
毕竟是在文档中.无论如何,谢谢Joshua!
我修改了Alexandre Cassagne对启用ARC的iOS 的答案.
CGSize ACMStringSize(NSString *string, UIFont *font, CGSize size)
{
NSTextStorage *textStorage = [[NSTextStorage alloc] initWithString:string];
[textStorage addAttribute:NSFontAttributeName value:font range:NSMakeRange(0, [textStorage length])];
NSLayoutManager *layoutManager = [[NSLayoutManager alloc] init];
NSTextContainer *textContainer = [[NSTextContainer alloc] initWithSize:size];
textContainer.lineFragmentPadding = 0;
[layoutManager addTextContainer:textContainer];
[textStorage addLayoutManager:layoutManager];
return [layoutManager usedRectForTextContainer:textContainer].size;
}
Run Code Online (Sandbox Code Playgroud)