如何获取字体的所有字符CTFontCopyCharacterSet()
在斯威夫特? ...对于 macOS?
在实施该方法时出现了该问题OSX:CGGlyph 到 UniChar用斯威夫特回答。
func createUnicodeFontMap() {
// Get all characters of the font with CTFontCopyCharacterSet().
let cfCharacterSet: CFCharacterSet = CTFontCopyCharacterSet(ctFont)
//
let cfCharacterSetStr = "\(cfCharacterSet)"
print("CFCharacterSet: \(cfCharacterSet)")
// Map all Unicode characters to corresponding glyphs
var unichars = [UniChar](…NYI…) // NYI: lacking unichars for CFCharacterSet
var glyphs = [CGGlyph](repeating: 0, count: unichars.count)
guard CTFontGetGlyphsForCharacters(
ctFont, // font: CTFont
&unichars, // characters: UnsafePointer<UniChar>
&glyphs, // UnsafeMutablePointer<CGGlyph>
unichars.count // count: CFIndex
)
else {
return
}
// For each Unicode character and its glyph,
// store the mapping glyph -> Unicode in a dictionary.
// ... NYI
}
做什么用CFCharacterSet
检索实际字符一直难以捉摸。自动完成cfCharacterSet
实例提供没有显示相关方法。
And the 核心基础 > CFCharacterSet似乎有创建另一个 CFCharacterSet 的方法,但没有提供单字符数组|列表|字符串来创建映射字典。
注意:我正在寻找一个不特定于 iOS 的解决方案,如获取字体中的所有可用字符它使用UIFont
.
CFCharacterSet
与可可基金会对应机构免费桥接NSCharacterSet
,并且可以桥接到相应的 Swift 值类型CharacterSet
:
let charset = CTFontCopyCharacterSet(ctFont) as CharacterSet
然后方法是从NSArray 来自 NSCharacterSet可用于枚举该字符集的所有 Unicode 标量值(包括非 BMP 点,即大于 U+FFFF 的 Unicode 标量值)。
The CTFontGetGlyphsForCharacters()
期望非 BMP 字符作为代理对,即作为 UTF-16 代码单元的数组。
把它们放在一起,该函数将如下所示:
func createUnicodeFontMap(ctFont: CTFont) -> [CGGlyph : UnicodeScalar] {
let charset = CTFontCopyCharacterSet(ctFont) as CharacterSet
var glyphToUnicode = [CGGlyph : UnicodeScalar]() // Start with empty map.
// Enumerate all Unicode scalar values from the character set:
for plane: UInt8 in 0...16 where charset.hasMember(inPlane: plane) {
for unicode in UTF32Char(plane) << 16 ..< UTF32Char(plane + 1) << 16 {
if let uniChar = UnicodeScalar(unicode), charset.contains(uniChar) {
// Get glyph for this `uniChar` ...
let utf16 = Array(uniChar.utf16)
var glyphs = [CGGlyph](repeating: 0, count: utf16.count)
if CTFontGetGlyphsForCharacters(ctFont, utf16, &glyphs, utf16.count) {
// ... and add it to the map.
glyphToUnicode[glyphs[0]] = uniChar
}
}
}
}
return glyphToUnicode
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)