从表情符号中获取代理对

时间:2016-02-28 19:48:42

标签: ios swift

我要做的是检查是否可以在iOS设备上呈现表情符号:

    let font = CTFontCreateWithName("AppleColorEmoji", 12, nil)
    var code_point: [UniChar] = [0xD83D, 0xDE0D]
    var glyphs: [CGGlyph] = [0, 0]
    let has_glyph = CTFontGetGlyphsForCharacters(font, &code_point, &glyphs, 2)

    if has_glyph == false {
        return false
    }
    else {
        return true
    }

需要两个代码点并检查表情符号是否可以呈现。现在我遇到的麻烦是如何从表情符号中直接获取代理对 。我用Google搜索,似乎无法找到任何办法。有什么想法吗?

2 个答案:

答案 0 :(得分:1)

您正在寻找的是角色的UTF-16表示:

let emoji = ""
let utf16codepoints = Array(emoji.utf16)

utf16codepoints[UInt16]数组,UniCharUInt16的类型别名,因此可以在CTFontGetGlyphsForCharacters()中直接使用此数组来检查是否一个字体有一个字形 对于这个角色(现在更新为Swift 3/4):

let font = CTFontCreateWithName("AppleColorEmoji" as CFString, 12, nil)
var glyphs: [CGGlyph] = [0, 0]
let has_glyph = CTFontGetGlyphsForCharacters(font, utf16codepoints, &glyphs, utf16codepoints.count)
print(has_glyph)
// true

Hex转储数组以验证它是否与 你问题中的code_point数组:

print(utf16codepoints.map { String($0, radix: 16)} )
// ["d83d", "de0d"]

print(utf16codepoints == [0xD83D, 0xDE0D])
// true

答案 1 :(得分:0)

如果有人正在寻找Obj-C实施:

- (BOOL)isEmojiSupported:(NSString*)emoji
{
    NSUInteger length = [emoji length];

    unichar characters[length + 1];
    [emoji getCharacters:characters range:NSMakeRange(0, length)];
    characters[length] = 0x0; 

    CGGlyph glyphs[length];     
    CTFontRef ctFont = CTFontCreateWithName(CFSTR("AppleColorEmoji"), 12, NULL);
    BOOL ret = CTFontGetGlyphsForCharacters(ctFont, characters, glyphs, emoji.length);
    CFRelease(ctFont);

    return ret;
}