2010-09-11 87 views
4

嘿,我试图从字体和字体大小中找出字符串的像素宽度。我目前正在使用此代码,但它不能100%的工作。还有另一种方法可以做到吗?可可从字体中获取字符串的宽度(以像素为单位)

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

我想有该方法'NSAttributedString(AppKitAdditions)' 。 – zneak 2010-09-11 18:34:25

+1

没有“像素宽度”。像素仅在光栅环境(例如窗口或位图上下文)中才有意义,并且只有在您将矢量绘制到上下文中时才会更改这些像素,例如通过绘制字符串。测量一个字符串返回其宽度(和高度)*点*。 – 2010-09-11 19:45:29

回答

7

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

这并没有解决它。它仍然没有改变。 fontSize将从10更改为22,但大小仍然相同... – user445229 2010-09-11 19:03:25

+0

所有时间的最大提示!谢谢! – 2014-10-20 05:01:55

1

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

+0

文档说'NSFontNameAttribute'是“指定字体名称的可选'NSString'对象。” – zneak 2010-09-11 18:44:03

+0

太棒了!谢谢!这实际上将解决我们的其他一些问题! – user445229 2010-09-11 19:34:43

+3

user445229:你接受了你不是那个意思的答案吗? – 2010-09-11 19:44:13

2

这里是我用它来得到一个字符串的大小...

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

注:如果要添加字符串到一个文本框,我发现,你需要添加约10以适合它的size.width。

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]; 
相关问题