我正在构建一个iOS应用程序,而Emojis在其中扮演很重要的角色.
In iOS 10.2,new emojis were released.
我很确定,如果有人有iOS 8,例如,他们实际上不会看到这些emojis.有没有办法检测这个?我正在努力动态地构建用户iOS版本支持的所有Emojis的列表,但是我有一些麻烦.
解决方法
>要知道给定设备或操作系统上是否有几个表情符号或Unicode字符可用,您可以在下面运行emojiAvailable()方法.
它通过将给定的字符图像与已知的无效字符1f3f6进行比较来工作.
>为了制作一些表单或unicode字符,可以在循环中调用characterData(),如batchTest()所示.通过缓存无效字符1f3f6一次,效率略高一些.
第一个例子:测试3个表情符号
let codes:[Character] = ["\u{2764}","\u{1f600}","\u{1F544}"] // change that for code in codes { print("\(code) : \(emojiAvailable(code))") }
第二个例子:测试几百个表情符号
func batchTest() { let refCode = Character("\u{1f3f6}") // do not change this if let refData = characterData(refCode) { for emojiCode in 0x1f300...0x1f600 { // change that let emojiCharacter = Character(UnicodeScalar(emojiCode)!) if let testData = characterData(emojiCharacter) { let valid = !(refData as NSData).isEqual(to: testData) print("Emoji \(emojiCharacter) for code \(emojiCode) is valid: \(valid)") } } } }
emojiAvailable()
func emojiAvailable(_ emojiCode:Character) -> Bool { let refCode = Character("\u{1f3f6}") // do not change this if let refData = characterData(refCode),let testData = characterData(emojiCode) { return !(refData as NSData).isEqual(to: testData) } return false }
字符到PNG
func characterData(_ char:Character) -> Data? { let attributes = [NSFontAttributeName: UIFont.systemFont(ofSize: 10)] let charStr = "\(char)" as NSString let size = charStr.size(attributes: attributes) UIGraphicsBeginImageContext(size) charStr.draw(at: CGPoint(x: 0,y :0),withAttributes: attributes) var charData:Data? = nil if let charImage = UIGraphicsGetImageFromCurrentImageContext() { charData = UIImagePNGRepresentation(charImage) } UIGraphicsEndImageContext() return charData }
►要下载完整的项目,请查阅swiftarchitect.com上的Emoji & Unicode文章.