Accessing OpenType Features in UIKit or CoreText

筅森魡賤 提交于 2019-12-04 06:13:54

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!