简体   繁体   English

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

[英]Cocoa get string width in pixels from font

I am trying to find the width in pixels of a string from the font and font size.我试图从字体和字体大小中找到字符串的宽度(以像素为单位)。 I am currently using this code, but it is not working 100% of the time.我目前正在使用此代码,但它不是 100% 的时间。 Is there another way to do it?还有另一种方法吗?

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

NSAttributedString is granted a -size method by the Application Kit Additions. Application Kit Additions 授予NSAttributedString一个-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;

Here is what i use to get the size of a string...这是我用来获取字符串大小的方法...

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

NOTE: If you are adding the string to a textfield, i have found that you need to add about 10 to size.width for it to fit.注意:如果您要将字符串添加到文本字段,我发现您需要将大约 10 添加到 size.width 以使其适合。

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

Here is yet another example:这是另一个例子:

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];

Here is for the stringAttributes, that may help noobs like me:这是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];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM