7

我正在使用 OpenType(.otf) 格式的自定义字体,并希望使用该字体的一些OpenType 功能

如何使用 UIKit 或 CoreText 完成此任务?我显然更喜欢 UIKit,但看看UIFont,选项非常有限。

似乎完全没有关于 iOS 上 OpenType 支持的文档,除了可以使用字体格式。

相关阅读:Microsoft对 OpenType 功能的参考,以及一些关于浏览器如何开始提供 OpenType 功能支持的信息。虽然这个问题是为了在 iOS 上原生渲染具有 OpenType 功能的字体。

4

1 回答 1

7

Since all I'm hearing are crickets in this dark and lonesome Core Text place, I thought I'd post the answer I found on my own.

The answer is UIKit does not support the setting of OpenType features within its framework(at the time of writing), you have to drop down to Core Text to do it, and luckily they do have an API that exposes additional font features.

I won't go into detail about using Core Text to draw text, but the relevant idea is you will need to get a CTFontDescriptorRef that defines all the attributes of the font that will be used to draw your text.

Sample Code:

CTFontDescriptorRef fontDescriptorNoFeatures = CTFontDescriptorCreateWithNameAndSize((__bridge CFStringRef)self.font.fontName, pointSize);

// Set up OpenType Attributes
CFAllocatorRef defaultAllocator = CFAllocatorGetDefault();

int numberSpacing = kNumberSpacingType;
int numberSpacingType = kMonospacedNumbersSelector;

CFNumberRef numberSpacingId = CFNumberCreate(defaultAllocator, kCFNumberIntType, &numberSpacing);
CFNumberRef monospacedNumbersSelector = CFNumberCreate(defaultAllocator, kCFNumberIntType, &numberSpacingType);

CTFontDescriptorRef fontDescriptor = CTFontDescriptorCreateCopyWithFeature(fontDescriptorNoFeatures, numberSpacingId, monospacedNumbersSelector);

CFRelease(fontDescriptorNoFeatures);
CFRelease(numberSpacingId);
CFRelease(monospacedNumbersSelector);

The main thing I am doing here is making a copy, using CTFontDescriptorCreateCopyWithFeature(), of the normal font descriptor with an additional feature, in OpenType it is called "Tabular Figures", but in Core Text you would access this feature by using the number spacing feature (kNumberSpacingType), and set the value for the appropriate enum defined in <CoreText/SFNTLayoutTypes.h>.

For the number spacing feature the enum values(for some reason they call them selectors!?!) are:

enum {
  kMonospacedNumbersSelector    = 0,
  kProportionalNumbersSelector  = 1,
  kThirdWidthNumbersSelector    = 2,
  kQuarterWidthNumbersSelector  = 3
};

So the trick is there isn't a direct one-to-one mapping of OpenType to CoreText features, but it appears they all are there, you'll just need to go through the pain of identifying the feature by looking through the constants defined in <CoreText/SFNTLayoutTypes.h>.

The rest of the pain is now you have to draw the text with this font in Core Text, instead of a higher level view, but there are lots of references out there for doing that.

于 2013-11-13T19:24:35.840 回答