Cocoa从字体获取字符串宽度(以像素为单位)

use*_*229 4 fonts cocoa objective-c

嘿伙计们,我试图从字体和字体大小中找到字符串的宽度(以像素为单位).我目前正在使用此代码,但它不是100%的工作时间.还有另一种方法吗?

NSSize textSize = [aTextLayer.string sizeWithAttributes:[NSDictionary dictionaryWithObjectsAndKeys:@"Bank Gothic Medium", NSFontNameAttribute, [NSNumber numberWithFloat:aTextLayer.fontSize], NSFontSizeAttribute, nil]];
Run Code Online (Sandbox Code Playgroud)

zne*_*eak 9

NSAttributedString-size通过Application Kit Additions 授予方法.

NSDictionary* attributes = [NSDictionary dictionaryWithObjectsAndKeys:
    @"Bank Gothic Medium", NSFontNameAttribute,
    [NSNumber numberWithFloat:aTextLayer.fontSize], NSFontSizeAttribute,
    nil];
NSAttributedString* attributedString = [[NSAttributedString alloc] initWithString:aTextLayer.string attributes:attributes];
NSSize size = attributedString.size;
Run Code Online (Sandbox Code Playgroud)