import UIKit
import CoreText
extension Font {
public func hasGlyph(utf32 character:UInt32) -> Bool {
var code_point: [UniChar] = [
UniChar.init(truncatingBitPattern: character),
UniChar.init(truncatingBitPattern: character >> 16)
]
var glyphs: [CGGlyph] = [0,0]
let result = CTFontGetGlyphsForCharacters(self as CTFont, &code_point, &glyphs, glyphs.count)
return result
}
}
public class Glypher {
let font:UIFont
var support:[CTFont] = []
public init(for font:UIFont, languages:[String] = ["en"]) {
self.font = font
let languages = languages as CFArray
let result = CTFontCopyDefaultCascadeListForLanguages(font as CTFont, languages)
let array = result as! Array<CTFontDescriptor>
for descriptor in array {
support.append(CTFontCreateWithFontDescriptor(descriptor,18,nil))
}
}
public func isGlyph(_ point:UInt32) -> Bool {
return font.hasGlyph(utf32:point) || isGlyphSupported(point)
}
public func isGlyphSupported(_ point:UInt32) -> Bool {
for font in support {
var code_point: [UniChar] = [
UniChar.init(truncatingBitPattern: point),
UniChar.init(truncatingBitPattern: point >> 16)
]
var glyphs: [CGGlyph] = [0, 0]
let result = CTFontGetGlyphsForCharacters(font as CTFont, &code_point, &glyphs, glyphs.count)
if result {
return true
}
}
return false
}
}
let glypher = Glypher(for:UIFont.systemFont(ofSize:18))
if glypher.isGlyph(0x1CDA) {
print("bingo!")
}
extension Font {
func canRender(emoji: String) -> Bool {
var code_points = Array(emoji.utf16)
var glyphs: [CGGlyph] = Array(repeating: 0, count: code_points.count)
return CTFontGetGlyphsForCharacters(self as CTFont, &code_points, &glyphs, glyphs.count)
}
}
class Glypher {
private let font: Font
private var support: [CTFont] = []
init(for font: Font, languages: [String] = ["en"]) {
self.font = font
let languages = languages as CFArray
let result = CTFontCopyDefaultCascadeListForLanguages(font as CTFont, languages)
let array = result as! Array<CTFontDescriptor>
for descriptor in array {
support.append(CTFontCreateWithFontDescriptor(descriptor, 18, nil))
}
}
func isRenderable(emoji: String) -> Bool {
return font.canRender(emoji: emoji) || renderSupported(emoji: emoji)
}
func renderSupported(emoji: String) -> Bool {
var code_points = Array(emoji.utf16)
var glyphs: [CGGlyph] = Array(repeating: 0, count: code_points.count)
for font in support where CTFontGetGlyphsForCharacters(font as CTFont, &code_points, &glyphs, glyphs.count) {
return true
}
return false
}
}
3条答案
按热度按时间8zzbczxx1#
Swift 3,XCode 8.6 version:
2ic8powd2#
这也可以工作,它不检查字形,但检查字符集
示例测试:
x9ybnkn63#
这在很大程度上是基于@andrewz的答案,所以大部分归功于他们!我发现某些emoji给出假否定的问题(包括),所以我做了一些修改,包括将emoji作为
String
传递:(**注意:**我使用
Font
而不是UIFont
,因为我在iOS和macOS上都使用它,所以有一个typealias来在两个字体类之间切换,你可以在你选择的平台上用NS
或UI
作为前缀!)