使用Objective-C/Cocoa如何根据特定字体计算绘制字符串所需的宽度和高度?在C#/ .Net中你可以这样做:
SizeF textSize = graphics.MeasureString(someString, someFont);
Run Code Online (Sandbox Code Playgroud)
Objective-C/Cocoa中是否有类似的东西?
Jas*_*rts 13
这是一个基于danielpunkass和Peter Hosey给出的答案的具体例子:
NSDictionary *attributes = [NSDictionary dictionaryWithObjectsAndKeys:[NSFont fontWithName:@"Helvetica" size:12], NSFontAttributeName, nil];
NSAttributedString *text = [[NSAttributedString alloc] initWithString:@"Hello" attributes: attributes];
NSSize textSize = [text size];
Run Code Online (Sandbox Code Playgroud)
对于像我这样的Objective-C/Cocoa新手来说,一个例子确实有很长的路要走.如果您来自C++/Java/C#或者任何Objective-C语法看起来真的很陌生,并且因为Apple在Cocoa文档中没有嵌入太多的示例代码,那么学习这些东西有点困难.
以下代码类似于我用于跨平台文本CALayer的代码:
#if defined(TARGET_IPHONE_SIMULATOR) || defined(TARGET_OS_IPHONE)
UIFont *theFont = [UIFont fontWithName:fontName size:fontSize];
CGSize textSize = [text sizeWithFont:theFont];
#else
NSFont *theFont = [NSFont fontWithName:fontName size:fontSize];
CGSize textSize = NSSizeToCGSize([text sizeWithAttributes:[NSDictionary dictionaryWithObject:theFont forKey: NSFontAttributeName]]);
#endif
Run Code Online (Sandbox Code Playgroud)
这为您提供了一个名为text的NSString的CGSize,其字体名称为fontName,大小为fontSize.
一种方法是sizeWithAttributes:,正如danielpunkass所说.另一种方法是创建一个NSAttributedString并询问它size.唯一的区别是,一种方式为您提供了一个具有文本和属性的对象(属性字符串),而另一种方式将它们分开.
| 归档时间: |
|
| 查看次数: |
10891 次 |
| 最近记录: |