如何获得NSString的大小,就像它在一个NSRect中一样.问题是当我尝试 – [NSString sizeWithAttributes:],它返回一个NSSize,就好像它有无限宽度.我想给方法最大的宽度.有什么办法吗(BTW:Mac OS,而不是iPhone操作系统)
谢谢,
亚历克斯
解决方法
- 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;
- }
毕竟这是文件.谢谢约书亚!