检测用户是否在UITextView中键入了表情符号字符

时间:2013-01-15 00:10:41

标签: ios objective-c unicode detect emoji

我有一个UITextView,我需要检测用户是否输入表情符号字符。

我认为只检查最新字符的unicode值就足够了,但是对于新的表情符号2s,一些字符分散在整个unicode索引中(即Apple新设计的版权和注册徽标)。

也许与使用NSLocale或LocalizedString值检查字符的语言有关?

有谁知道一个好的解决方案?

谢谢!

9 个答案:

答案 0 :(得分:17)

多年来,这些表情符号检测解决方案不断突破,因为Apple添加了新的表情符号(如通过预先诅咒带有附加角色的角色制作的肤色表情符号)等等。

我终于崩溃了,只是编写了以下方法,该方法适用于所有当前的表情符号,并且应该适用于所有未来的表情符号。

该解决方案创建了一个带有角色和黑色背景的UILabel。然后,CG拍摄标签的快照,并扫描快照中的所有像素,以查找任何非纯黑像素。我添加黑色背景的原因是为了避免由Subpixel Rendering

引起的假色问题

解决方案在我的设备上运行非常快,我可以每秒检查数百个字符,但应该注意这是一个CoreGraphics解决方案,不应像使用常规文本方法那样大量使用。图形处理数据量很大,因此一次检查数千个字符可能会导致明显的延迟。

-(BOOL)isEmoji:(NSString *)character {

    UILabel *characterRender = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 1, 1)];
    characterRender.text = character;
    characterRender.backgroundColor = [UIColor blackColor];//needed to remove subpixel rendering colors
    [characterRender sizeToFit];

    CGRect rect = [characterRender bounds];
    UIGraphicsBeginImageContextWithOptions(rect.size,YES,0.0f);
    CGContextRef contextSnap = UIGraphicsGetCurrentContext();
    [characterRender.layer renderInContext:contextSnap];
    UIImage *capturedImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    CGImageRef imageRef = [capturedImage CGImage];
    NSUInteger width = CGImageGetWidth(imageRef);
    NSUInteger height = CGImageGetHeight(imageRef);
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    unsigned char *rawData = (unsigned char*) calloc(height * width * 4, sizeof(unsigned char));
    NSUInteger bytesPerPixel = 4;
    NSUInteger bytesPerRow = bytesPerPixel * width;
    NSUInteger bitsPerComponent = 8;
    CGContextRef context = CGBitmapContextCreate(rawData, width, height,
                                                 bitsPerComponent, bytesPerRow, colorSpace,
                                                 kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);
    CGColorSpaceRelease(colorSpace);

    CGContextDrawImage(context, CGRectMake(0, 0, width, height), imageRef);
    CGContextRelease(context);

    BOOL colorPixelFound = NO;

    int x = 0;
    int y = 0;
    while (y < height && !colorPixelFound) {
        while (x < width && !colorPixelFound) {

            NSUInteger byteIndex = (bytesPerRow * y) + x * bytesPerPixel;

            CGFloat red = (CGFloat)rawData[byteIndex];
            CGFloat green = (CGFloat)rawData[byteIndex+1];
            CGFloat blue = (CGFloat)rawData[byteIndex+2];

            CGFloat h, s, b, a;
            UIColor *c = [UIColor colorWithRed:red green:green blue:blue alpha:1.0f];
            [c getHue:&h saturation:&s brightness:&b alpha:&a];

            b /= 255.0f;

            if (b > 0) {
                colorPixelFound = YES;
            }

            x++;
        }
        x=0;
        y++;
    }

    return colorPixelFound;

}

答案 1 :(得分:3)

另一种解决方案:https://github.com/woxtu/NSString-RemoveEmoji

然后,在导入此扩展程序后,您可以像这样使用它:

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    // Detect if an Emoji is in the string "text"
    if(text.isIncludingEmoji) {
        // Show an UIAlertView, or whatever you want here
        return NO;
    }

    return YES;
}

希望有所帮助;)

答案 2 :(得分:3)

首先让我们解决您的“55357方法” - 和为什么它适用于许多表情符号字符。

在Cocoa中,NSStringunichar的集合,unichar只是unsigned short的一个类型,与UInt16相同。由于UInt16的最大值为0xffff,因此可以将一些表情符号排除在一个unichar之外,因为用于表情符号的六个主要Unicode块中只有两个属于这个范围:

这些块包含113个表情符号,另外66个可以表示为单个unichar的表情符号可以在各个其他块周围找到。但是,这179个字符仅代表1126 emoji base characters的一小部分,其余部分必须由多个unichar表示。

让我们分析您的代码:

unichar unicodevalue = [text characterAtIndex:0];

正在发生的事情是你只是接受字符串的第一个unichar,虽然这适用于前面提到的179个字符,但是当遇到UTF-32字符时,它会分开,因为{{1将所有内容转换为UTF-16编码。转化工作substituting the UTF-32 value with surrogate pairs,这意味着NSString现在包含两个NSString

现在我们已经了解为什么数字55357或unichar出现在许多表情符号中:当你只查看UTF-32的第一个UTF-16值时你获得高代理人的角色,每个代理人都有1024个低代理人。高代理0xd83d的范围是U + 1F400-U + 1F7FF,它从最大的表情符号块Miscellaneous Symbols and Pictographs(U + 1F300-U + 1F5FF)的中间开始,并继续全部直至Geometric Shapes Extended(U + 1F780-U + 1F7FF) - 在此范围内共包含563个表情符号和333个非表情符号字符。

因此,令人印象深刻的50%的表情符号基础字符具有高代理0xd83d,但这些演绎方法仍然留下384个表情符号字符未处理,并且至少给出了误报率。

那么,如何判断角色是否是表情符号?

我最近回答了somewhat related question with a Swift implementation,如果您愿意,可以查看this framework中我是如何检测表情符号的,这是为了用自定义图像替换标准表情符号而创建的。

无论如何,你可以做的是从字符中提取UTF-32代码点,我们将根据the specification执行:

0xd83d

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text { // Get the UTF-16 representation of the text. unsigned long length = text.length; unichar buffer[length]; [text getCharacters:buffer]; // Initialize array to hold our UTF-32 values. NSMutableArray *array = [[NSMutableArray alloc] init]; // Temporary stores for the UTF-32 and UTF-16 values. UTF32Char utf32 = 0; UTF16Char h16 = 0, l16 = 0; for (int i = 0; i < length; i++) { unichar surrogate = buffer[i]; // High surrogate. if (0xd800 <= surrogate && surrogate <= 0xd83f) { h16 = surrogate; continue; } // Low surrogate. else if (0xdc00 <= surrogate && surrogate <= 0xdfff) { l16 = surrogate; // Convert surrogate pair to UTF-32 encoding. utf32 = ((h16 - 0xd800) << 10) + (l16 - 0xdc00) + 0x10000; } // Normal UTF-16. else { utf32 = surrogate; } // Add UTF-32 value to array. [array addObject:[NSNumber numberWithUnsignedInteger:utf32]]; } NSLog(@"%@ contains values:", text); for (int i = 0; i < array.count; i++) { UTF32Char character = (UTF32Char)[[array objectAtIndex:i] unsignedIntegerValue]; NSLog(@"\t- U+%x", character); } return YES; } 中键入“”将此内容写入控制台:

UITextView

使用该逻辑,只需将 contains values: - U+1f60e 的值与表情符号代码点的数据源进行比较,您就会确切地知道该字符是否为表情符号。

P.S。

有一些“隐形”字符,即Variation Selectorszero-width joiners,也应该处理,所以我建议研究那些以了解它们的行为。< / p>

答案 3 :(得分:2)

如果您不希望键盘显示表情符号,则可以使用 YOURTEXTFIELD/YOURTEXTVIEW.keyboardType = .ASCIICapable
这将显示没有表情符号的键盘

答案 4 :(得分:2)

这是快速中的表情符号检测方法。工作正常。希望对别人有帮助。

 func isEmoji(_ character: String?) -> Bool {

        if character == "" || character == "\n" {
            return false
        }
        let characterRender = UILabel(frame: CGRect(x: 0, y: 0, width: 1, height: 1))
        characterRender.text = character
        characterRender.backgroundColor = UIColor.black  
        characterRender.sizeToFit()
        let rect: CGRect = characterRender.bounds
        UIGraphicsBeginImageContextWithOptions(rect.size, true, 0.0)

        if let contextSnap:CGContext = UIGraphicsGetCurrentContext() {
            characterRender.layer.render(in: contextSnap)
        }

        let capturedImage: UIImage? = (UIGraphicsGetImageFromCurrentImageContext())
        UIGraphicsEndImageContext()
        var colorPixelFound:Bool = false

        let imageRef = capturedImage?.cgImage
        let width:Int = imageRef!.width
        let height:Int = imageRef!.height

        let colorSpace = CGColorSpaceCreateDeviceRGB()

        let rawData = calloc(width * height * 4, MemoryLayout<CUnsignedChar>.stride).assumingMemoryBound(to: CUnsignedChar.self)

            let bytesPerPixel:Int = 4
            let bytesPerRow:Int = bytesPerPixel * width
            let bitsPerComponent:Int = 8

            let context = CGContext(data: rawData, width: Int(width), height: Int(height), bitsPerComponent: Int(bitsPerComponent), bytesPerRow: Int(bytesPerRow), space: colorSpace, bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue | CGBitmapInfo.byteOrder32Big.rawValue)



        context?.draw(imageRef!, in: CGRect(x: 0, y: 0, width: width, height: height))

            var x:Int = 0
            var y:Int = 0
            while (y < height && !colorPixelFound) {

                while (x < width && !colorPixelFound) {

                    let byteIndex: UInt  = UInt((bytesPerRow * y) + x * bytesPerPixel)
                    let red = CGFloat(rawData[Int(byteIndex)])
                    let green = CGFloat(rawData[Int(byteIndex+1)])
                    let blue = CGFloat(rawData[Int(byteIndex + 2)])

                    var h: CGFloat = 0.0
                    var s: CGFloat = 0.0
                    var b: CGFloat = 0.0
                    var a: CGFloat = 0.0

                    var c = UIColor(red:red, green:green, blue:blue, alpha:1.0)
                    c.getHue(&h, saturation: &s, brightness: &b, alpha: &a)

                    b = b/255.0

                    if Double(b) > 0.0 {
                        colorPixelFound = true
                    }
                    x+=1
                }
                x=0
                y+=1
            }

        return colorPixelFound
}

答案 5 :(得分:0)

以下是代码的更干净,更高效的实现,该代码检查以查看绘制的字符是否具有任何颜色。

这些已被编写为类别/扩展方法,以使其更易于使用。

Objective-C:

NSString + Emoji.h:

#import <Foundation/Foundation.h>

@interface NSString (Emoji)

- (BOOL)hasColor;

@end

NSString + Emoji.m:

#import "NSString+Emoji.h"
#import <UIKit/UIKit.h>

@implementation NSString (Emoji)

- (BOOL)hasColor {
    UILabel *characterRender = [[UILabel alloc] initWithFrame:CGRectZero];
    characterRender.text = self;
    characterRender.textColor = UIColor.blackColor;
    characterRender.backgroundColor = UIColor.blackColor;//needed to remove subpixel rendering colors
    [characterRender sizeToFit];

    CGRect rect = characterRender.bounds;
    UIGraphicsBeginImageContextWithOptions(rect.size, YES, 1);
    CGContextRef contextSnap = UIGraphicsGetCurrentContext();
    [characterRender.layer renderInContext:contextSnap];
    UIImage *capturedImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    CGImageRef imageRef = capturedImage.CGImage;
    size_t width = CGImageGetWidth(imageRef);
    size_t height = CGImageGetHeight(imageRef);
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    size_t bytesPerPixel = 4;
    size_t bitsPerComponent = 8;
    size_t bytesPerRow = bytesPerPixel * width;
    size_t size = height * width * bytesPerPixel;
    unsigned char *rawData = (unsigned char *)calloc(size, sizeof(unsigned char));
    CGContextRef context = CGBitmapContextCreate(rawData, width, height,
                                                 bitsPerComponent, bytesPerRow, colorSpace,
                                                 kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);
    CGColorSpaceRelease(colorSpace);

    CGContextDrawImage(context, CGRectMake(0, 0, width, height), imageRef);
    CGContextRelease(context);

    BOOL result = NO;
    for (size_t offset = 0; offset < size; offset += bytesPerPixel) {
        unsigned char r = rawData[offset];
        unsigned char g = rawData[offset+1];
        unsigned char b = rawData[offset+2];

        if (r || g || b) {
            result = YES;
            break;
        }
    }

    free(rawData);

    return result;
}

@end

用法示例:

if ([@"?" hasColor]) {
    // Yes, it does
}
if ([@"@" hasColor]) {
} else {
    // No, it does not
}

快捷键:

String + Emoji.swift:

import UIKit

extension String {
    func hasColor() -> Bool {
        let characterRender = UILabel(frame: .zero)
        characterRender.text = self
        characterRender.textColor = .black
        characterRender.backgroundColor = .black
        characterRender.sizeToFit()
        let rect = characterRender.bounds
        UIGraphicsBeginImageContextWithOptions(rect.size, true, 1)

        let contextSnap = UIGraphicsGetCurrentContext()!
        characterRender.layer.render(in: contextSnap)

        let capturedImageTmp = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        guard let capturedImage = capturedImageTmp else { return false }

        let imageRef = capturedImage.cgImage!
        let width = imageRef.width
        let height = imageRef.height

        let colorSpace = CGColorSpaceCreateDeviceRGB()

        let bytesPerPixel = 4
        let bytesPerRow = bytesPerPixel * width
        let bitsPerComponent = 8
        let size = width * height * bytesPerPixel
        let rawData = calloc(size, MemoryLayout<CUnsignedChar>.stride).assumingMemoryBound(to: CUnsignedChar.self)

        guard let context = CGContext(data: rawData, width: width, height: height, bitsPerComponent: bitsPerComponent, bytesPerRow: bytesPerRow, space: colorSpace, bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue | CGBitmapInfo.byteOrder32Big.rawValue) else { return false }

        context.draw(imageRef, in: CGRect(x: 0, y: 0, width: width, height: height))

        var result = false
        for offset in stride(from: 0, to: size, by: 4) {
            let r = rawData[offset]
            let g = rawData[offset + 1]
            let b = rawData[offset + 2]

            if (r > 0 || g > 0 || b > 0) {
                result = true
                break
            }
        }

        free(rawData)

        return result
    }
}

用法示例:

if "?".hasColor() {
    // Yes, it does
}
if "@".hasColor() {
} else {
    // No, it does not
}

答案 6 :(得分:0)

Swift的String类型具有.isEmoji属性

最好查看isEmojiPresentation警告的文档

https://developer.apple.com/documentation/swift/unicode/scalar/properties/3081577-isemoji

答案 7 :(得分:-3)

你可以用它来检测它是否只有ascii字符:

[myString canBeConvertedToEncoding:NSASCIIStringEncoding];

如果失败(或有表情符号),它会说不。然后你可以做一个if else语句,不允许他们点击回车或其他东西。

答案 8 :(得分:-4)

表情符号字符长度为2,因此检查字符串长度是否为2,方法是shouldChangeTextInRange:在键盘命中每个键后调用

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text

{

    // Detect if an Emoji is in the string "text"
    if([text length]==2) {
        // Show an UIAlertView, or whatever you want here
        return YES;
    }
    else
{

       return NO;
}

}