如何检测表情符号和更改字体大小

How to detect emoji and change font size

我有包含表情符号的文本,我们可以通过对字符串进行编码和解码来正确显示它,我需要实现的是增加文本中只有表情符号的字体大小,如下图所示,

我有一个想法来确定所有表情符号的范围,并在 NSAttributedString 中提供增加的字体大小。现在不知道如何检测给定字符串中的表情符号范围?

谢谢

你可以像下面这样直接使用它或者

if ([myString containsString:@""]) 
   {
        NSLog(@"one");
        //change the font size here.
   }
else
   {
        NSLog(@"fk");
       //change the font size here.
   }

或者您可以使用

[mystring is isEqualToString:"I believe "];

试试看。希望对你有所帮助。

我做了一个演示,你可以从下面的字符串中检测到表情符号,

  NSString *str = @"this is  and test ";

NSArray *arr = [str componentsSeparatedByString:@" "];

for (int i = 0; i < arr.count; i++) {

NSString *temp = [arr objectAtIndex:i];

if ( ![temp canBeConvertedToEncoding:NSASCIIStringEncoding]) {

    NSLog(@"%d",i);
    NSLog(@"%@",temp);  // temp is emoji. You can detect emoji here from your string now you can manage as per your need


}


}

我也做过

    let string = "This is emoji Test"
    let attributedEmoji = NSMutableAttributedString(string: " \u{1F600}", attributes: [NSFontAttributeName:UIFont.systemFontOfSize(60)])

    let attribString = NSMutableAttributedString.init(string: string)
    attribString.appendAttributedString(attributedEmoji)

    lblEmoji.attributedText = attribString

您可以更改字体和字体大小以缩放表情符号。

  1. 将所有可能的表情符号(您的应用程序使用)放入一个数组中。
  2. 从 array.If 中搜索字符串中的表情符号,找到应用属性的表情符号。
  3. 编写一个接受表情符号代码和 return 属性表情符号文本的方法。

希望这些信息能更好地帮助您。

https://github.com/woxtu/NSString-RemoveEmoji

感谢所有回答的人,但是 none 是完整的答案,虽然 @Raj 的建议看起来 NSString-RemoveEmoji 帮助我实现了这个解决方案,在这里,它适用于任何类型表情符号

-(NSMutableAttributedString *)getAttributedEmojiString:(NSString *)inputString{

    NSMutableArray *__block emojiRange=[[NSMutableArray alloc] init];
    [inputString enumerateSubstringsInRange:NSMakeRange(0, [inputString length])
                                    options:NSStringEnumerationByComposedCharacterSequences
                                 usingBlock: ^(NSString* substring, NSRange substringRange, NSRange enclosingRange, BOOL* stop) {
             if([substring isEmoji]){
                 [emojiRange addObject:@{@"startrange":@(substringRange.location),@"endrange":@(enclosingRange.length)}];
             }
     }];

    NSMutableAttributedString *mutString=[[NSMutableAttributedString alloc] initWithString:inputString];


    [mutString addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:16.0] range:NSMakeRange(0, mutString.length)];

    [emojiRange enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [mutString addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:35.0] range:NSMakeRange([obj[@"startrange"] floatValue], [obj[@"endrange"] floatValue])];
    }];

    return mutString;
}

描述

  1. 首先使用NSString-RemoveEmoji函数isEmoji找到字符串中所有表情符号的NSRange,并存储在数组中。
  2. 提供获取的范围以对范围内的字符应用更大的字体大小
  3. 最后将生成的属性文本赋给标签。

    self.label.attributedText=[self getAttributedEmojiString:EmojiDecoded(originalText)];
    

我使用两个宏来编码和解码表情符号,因为我需要将这些值保存到服务器并通读 api,下面是宏。

#define Encoded(val) [[val dataUsingEncoding:NSUTF8StringEncoding] base64EncodedStringWithOptions:0]
#define Decoded(val) [[NSString alloc] initWithData:[[NSData alloc] initWithBase64EncodedString:val options:0] encoding:NSUTF8StringEncoding]

#define EmojiEncoded(val) [[NSString alloc] initWithData:[val dataUsingEncoding:NSNonLossyASCIIStringEncoding] encoding:NSUTF8StringEncoding]
#define EmojiDecoded(val) [[NSString alloc] initWithData:[val dataUsingEncoding:NSUTF8StringEncoding] encoding:NSNonLossyASCIIStringEncoding]

希望对正在寻找类似解决方案的任何人有所帮助。

干杯,感谢大家。

这有点晚了,但可能对偶然发现此答案的其他人有用。秘诀是询问 Core Text,它知道 NSAttributedString 中的哪些字符是表情符号字符。

// Build the attributed string as needed
let ns = NSAttributedString(string: s)

// Now create a typesetter and render the line
let typesetter = CTTypesetterCreateWithAttributedString(nsa)
let line = CTTypesetterCreateLine(typesetter, CFRangeMake(0, nsa.length))

// Once you have a line you can enumerate the runs
guard let runs = CTLineGetGlyphRuns(line) as? [CTRun] else {
    throw NSError(domain: "CoreText", code: -1, userInfo: nil)
}

// Each run will have a font with specific attributes
print("There are \(runs.count) run(s) in \(ns.string)")
print()
for run in runs {
    let charRange = CTRunGetStringRange(run)
    let x: NSAttributedString = CFAttributedStringCreateWithSubstring(nil, nsa, charRange)

    print("    Chars: '\(x.string)'")

    let attributes: NSDictionary = CTRunGetAttributes(run)
    let font = attributes["NSFont"] as! CTFont

    let traits = CTFontGetSymbolicTraits(font)
    print("    Emoji == \(traits.contains(.traitColorGlyphs))")

    print()
}