这个问题与CoreText(在苹果平台上可用)有关.语言是Swift 5.10
.
如果给定的UniChar数组包含汉字/表情符号,则CTFontCreateUIFontForLanguage()
似乎不会返回可用的结果.
我的try :
假设我使用以下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)
,而不是我在上面创建的字体.CTFont和NSFont在SWIFT 5中是免费桥接的.
此案的问题在于:
如果给定的字符串参数包含汉字和/或表情字符,则(CTFont instance).glyphs(for:)
返回nil.可以try 使用其他仅支持汉字的字符串或仅支持表情符号的字符串.