本文介绍了NSString sizeWithAttributes:content rect的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何获得NSString的大小,就像它在NSRect中绘制一样。问题是当我尝试 - [NSString sizeWithAttributes:],它返回一个NSSize,如果它有无限宽度。我想给方法的最大宽度。有什么办法吗? (BTW:Mac OS,not iPhone OS)
How do I get a NSString's size as if it drew in an NSRect. The problem is when I try -[NSString sizeWithAttributes:], it returns an NSSize as if it had infinite width. I want to give a maximum width to the method. Is there any way of doing so? (BTW: Mac OS, not iPhone OS)
感谢,
Alex
Thanks,Alex
推荐答案
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;
}
毕竟在文档中。谢谢Joshua!
It was in the docs after all. Thank you Joshua anyway!
这篇关于NSString sizeWithAttributes:content rect的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!