在iOS上显示按比例分配的数字(而不是等宽/表格)
我在iOS中渲染数字(目标是7或更高),方法是将它们存储在NSAttributedString中,并使用“drawAtPoint:”进行渲染。 我正在使用Helvetica Neue。
我已经注意到, 像这样绘制的数字不是成比例的 – 这些字形都具有相同的宽度。 即使是一个瘦的“1”也占据了与“0”相同的空间。
一个testing证实了这一点:
for(NSInteger i=0; i<10; ++i) { NSString *iString = [NSString stringWithFormat: @"%d", i]; const CGSize iSize = [iString sizeWithAttributes: [self attributes]]; NSLog(@"Size of %d is %f", i, iSize.width); }
与其他地方一起:
-(NSDictionary *) attributes { static NSDictionary * attributes; if(!attributes) { attributes = @{ NSFontAttributeName: [UIFont systemFontOfSize:11], NSForegroundColorAttributeName: [UIColor whiteColor] }; } return attributes; }
由此产生的字形都具有 6.358点的相同宽度 。
有一些渲染选项,我可以打开,以启用比例数字字形 ? 是否还有另一种支持比例数字字形的字体(理想情况下类似于Helvetica Neue)? 还要别的吗?
谢谢。
iOS 7允许您使用UIFontDescriptor
实例指定字体。 然后从描述符获得UIFont
实例。
给定一个UIFontDescriptor
也可以通过使用方法[fontDescriptor fontDescriptorByAddingAttributes: attibutes]
来获得一个自定义的[fontDescriptor fontDescriptorByAddingAttributes: attibutes]
,这个attributes
是一个字体属性的NSDictionary
。
Apple在UIFontDescriptor
引用中logging属性。
从引用中,一个特定的字体描述符属性UIFontDescriptorFeatureSettingsAttribute
允许您提供“表示非默认字体特征设置的字典数组,每个字典包含UIFontFeatureTypeIdentifierKey
和UIFontFeatureSelectorIdentifierKey
。
UIFontFeatureTypeIdentifierKey
和UIFontFeatureSelectorIdentifierKey
的文档在Apple的字体registry文档中 。 苹果演示文稿的幻灯片PDF格式中包含了比例数字的具体情况,所以我只是解除了这一点。
这个代码将采用现有的UIFont
实例并返回一个带有比例数字的新实例:
// You'll need this somewhere at the top of your file to pull // in the required constants. #import <CoreText/CoreText.h> … UIFont *const existingFont = [UIFont preferredFontForTextStyle: UIFontTextStyleBody]; UIFontDescriptor *const existingDescriptor = [existingFont fontDescriptor]; NSDictionary *const fontAttributes = @{ // Here comes that array of dictionaries each containing UIFontFeatureTypeIdentifierKey // and UIFontFeatureSelectorIdentifierKey that the reference mentions. UIFontDescriptorFeatureSettingsAttribute: @[ @{ UIFontFeatureTypeIdentifierKey: @(kNumberSpacingType), UIFontFeatureSelectorIdentifierKey: @(kProportionalNumbersSelector) }] }; UIFontDescriptor *const proportionalDescriptor = [existingDescriptor fontDescriptorByAddingAttributes: fontAttributes]; UIFont *const proportionalFont = [UIFont fontWithDescriptor: proportionalDescriptor size: [existingFont pointSize]];
如果你愿意的话,你可以在UIFont
上添加这个类别。
编辑说明:感谢Chris Schwerdt的改进。