简体   繁体   English

如何在cocoa中获取字体的大小

[英]How do I get the size of a font in cocoa

I have a NSString with it's attributes (a dictionary). 我有一个NSString与它的属性(字典)。 I could get a NSAttributedString with this. 我可以用这个获得NSAttributedString。
I need to know what's the size of the string.With the font I can only get the height, using capHeight method, but I need also the width, how do I get this info? 我需要知道字符串的大小是什么。使用capHeight方法我只能得到高度的字体,但我还需要宽度,我如何获得这些信息?

Take a look at: 看一眼:

- (NSRect)boundingRectWithSize:(NSSize)size options:(NSStringDrawingOptions)options

on NSAttributedString 在NSAttributedString上

You can do it like this: 你可以这样做:

NSDictionary *attributes = [NSDictionary dictionaryWithObjectsAndKeys:font, NSFontAttributeName, nil];
NSAttributedString *attrString = [[NSAttributedString alloc] initWithString:string attributes:attributes];
NSSize size = [attrString size];
CGFloat width = size.width;
CGFloat height = size.height;
[attrString release];

NSLog(@"String width: %f", width);
NSLog(@"String height: %f", height);

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

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