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

时间:2010-09-11 18:31:00

标签: objective-c cocoa fonts

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

NSSize textSize = [aTextLayer.string sizeWithAttributes:[NSDictionary dictionaryWithObjectsAndKeys:@"Bank Gothic Medium", NSFontNameAttribute, [NSNumber numberWithFloat:aTextLayer.fontSize], NSFontSizeAttribute, nil]];

4 个答案:

答案 0 :(得分:9)

NSAttributedString被Application Kit Additions授予-size方法。

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;

答案 1 :(得分:3)

以下是我用来获取字符串大小的内容......

NSSize size = [@"Some text" sizeWithAttributes:[NSDictionary dictionaryWithObject:[NSFont fontWithName:@"Helvetica Neue Bold" size:24.0f] forKey:NSFontAttributeName]];

注意:如果您要将字符串添加到文本字段,我发现您需要添加大约10到size.width以使其适合。

答案 2 :(得分:1)

尝试使用实际的NSFont(或UIFont)对象,而不仅仅是字体名称。

答案 3 :(得分:0)

这是另一个例子:

NSString *test = [[NSString alloc] initWithFormat:@"%u:%u:%u.000", hours, minutes, seconds];
NSSize boundingSize = {100,300};  //I suppose this is the constraints?
NSRect boundingRect = [test boundingRectWithSize:boundingSize options:NULL attributes:stringAttributes];
point.x -= boundingRect.size.width; //This point points at the end of screen
[test drawAtPoint:point withAttributes:stringAttributes];

这是stringAttributes,这可能有助于像我这样的新手:

NSMutableDictionary *stringAttributes;
    stringAttributes = [NSMutableDictionary dictionary];
    [stringAttributes setObject:[NSFont fontWithName:@"Monaco" size:16] forKey:NSFontAttributeName];
    [stringAttributes setObject:[NSColor whiteColor] forKey:NSForegroundColorAttributeName];
    [stringAttributes setObject:[NSColor blackColor] forKey:NSBackgroundColorAttributeName];