我注意到像这样绘制的数字的数字不成比例 – 字形都具有相同的宽度.即使是瘦的“1”占据与“0”相同的空间.
测试证实了这一点:
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)支持比例数字字形(理想情况下,内置)?还要别的吗?
谢谢.
解决方法
给定UIFontDescriptor,还可以通过使用方法[fontDescriptor fontDescriptorByAddingAttributes:attibutes]来获取更改某些特征的自定义,其中attributes是字体属性的NSDictionary.
Apple记录了UIFontDescriptor
reference中的属性.
从引用中,一个特定的字体描述符属性UIFontDescriptorFeatureSettingsAttribute允许您提供“表示非默认字体功能设置的字典数组.每个字典包含UIFontFeatureTypeIdentifierKey和UIFontFeatureSelectorIdentifierKey”.
UIFontFeatureTypeIdentifierKeys和UIFontFeatureSelectorIdentifierKeys的文档在Apple’s Font Registry documentation.比例数字的具体情况在pdf of slides of an Apple presentation中有所涉及,所以我刚刚解除了.
此代码将使用现有的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的改进.