如何让CTFontCreateUIFontForLanguage支持汉字与Emoji?
CoreText框架在Swift 5.10中处理汉字/Emoji字符的异常问题
涉及Apple平台CoreText框架,使用Swift 5.10开发时发现:当传入的UniChar数组包含汉字或Emoji字符时,CTFontCreateUIFontForLanguage()返回的字体无法正常获取对应字形。
我的尝试
我使用以下Swift脚本来调用CTFontCreateUIFontForLanguage():
#!/usr/bin/env swift import CoreText import Foundation guard let osFont = CTFontCreateUIFontForLanguage( .system, 14, "zh-Hant" as CFString ) else { print("CTFont initiation failed.") exit(1) // Abortion. } extension CTFont { func glyphs(for string: String) -> [CGGlyph]? { let arrUTF16 = Array(string.utf16) var glyphs = [CGGlyph](repeating: 0, count: arrUTF16.count) let result = CTFontGetGlyphsForCharacters(self, arrUTF16, &glyphs, arrUTF16.count) return result ? glyphs : nil } } let string = "這是草莓蛋糕🍓🍰。" // NOTE: Edit this line to try various parameters. let unichars = Array(string.utf16) var fetchedGlyphs: [CGGlyph]? = osFont.glyphs(for: string) guard var fetchedGlyphs = fetchedGlyphs else { print("Screwed. I don't know why it only works with ASCII glyphs.") exit(1) // Abortion. }
注意:上述创建的CTFont可替换为
NSFont.systemFont(ofSize: NSFont.systemFontSize),在Swift 5中CTFont与NSFont是免费桥接的。
问题现象
当传入的字符串参数包含汉字和/或Emoji字符时,(CTFont instance).glyphs(for:)方法返回nil。单独测试仅含汉字或仅含Emoji的字符串,同样会出现该问题。
内容的提问来源于stack exchange,提问作者Shiki Suen
相关产品推荐
相关产品推荐

