iOS-富文本显示表情

作者: 蔡胜波 | 来源:发表于2017-04-13 15:55 被阅读171次

    总想写点什么,用不知道从什么写起,那就想起什么写什么吧(是不是太随便了*_*)。本文讲述如何使用NSRegularExpressionNSMutableAttributedStringNSTextAttachment实现表情文字排。

    Demo地址

    先来看一下实现利用表情图片替换字符串的步骤:
    1.既然要替换字符为表情,那首先要找到哪些字符需要替换,用什么找呢?用这个NSRegularExpression正则;
    2.已经找到了,当然要替换了,替换需要用到NSMutableAttributedStringNSTextAttachment,这个下面将它们是干什么的。

    首先我们需要又一个字符串跟图片一一对应的关系:

    /// 表情字符、图片对应表
        static let EmotionsTable = [
            "[):]": "ee_1.png",
            "[:D]": "ee_2.png",
            "[;)]": "ee_3.png",
            ...
            "[(W)]": "ee_34.png",
            "[(D)]": "ee_35.png",
            ]
    

    然后根据正则匹配出可能代表表情的字符,为什么说是可能呢?因为正则不一定能准确只包含代表表情的字符,很有可能一个字符串并不代表一个表情,但是符合正则的匹配,不细说,有兴趣的百度百科

         /// 正则表达式的格式
        static let pattern = "\\[.{2,3}\\]"
        
        /// bundle路径
        static let pathPrexfix = "ExpressionResource.bundle/"
        
        static func convertToCommonEmoticons(text: String, font: UIFont, textColor: UIColor) -> NSMutableAttributedString {
            
            /// 字体、颜色
            let textAttributes = [NSFontAttributeName: font, NSForegroundColorAttributeName: textColor]
            
            /// 获取字体的行高,作为表情的高度
            let attachmentHeight = font.lineHeight;
            
            //转成NSString
            let originalNSString = text as NSString
            //通过str获得NSMutableAttributedString
            let attStr = NSMutableAttributedString.init(string: text, attributes: textAttributes)
            var regex: NSRegularExpression?
            do {
                regex = try NSRegularExpression.init(pattern: pattern, options: NSRegularExpression.Options.caseInsensitive)
            } catch let error as NSError {
                print(error.localizedDescription)
            }
            
            //获取到匹配正则的数据
            if let matches = regex?.matches(in: text, options: NSRegularExpression.MatchingOptions.withoutAnchoringBounds, range: NSMakeRange(0, attStr.string.characters.count)) {
                if matches.count > 0 {
                    //遍历符合的数据进行解析
                    for i in 0..<matches.count {
                        let result = matches[matches.count-i-1]
                        let range = result.range
                        let emojiStr = originalNSString.substring(with: range)
                        //符合的数据是否为表情
                        if EmotionsTable.keys.contains(emojiStr) {
                            if let image = UIImage.init(named: pathPrexfix + EmotionsTable[emojiStr]!) {
                                //创建一个NSTextAttachment
                                let attachment = NSTextAttachment()
                                attachment.image  = image
                                
                                let attachmentWidth = attachmentHeight * image.size.width / image.size.height
                                attachment.bounds = CGRect(x: 0, y: 0, width: attachmentWidth, height: attachmentHeight);
                                //通过NSTextAttachment生成一个NSAttributedString
                                let rep = NSAttributedString(attachment: attachment)
                                //把表情于之前的字符串替换
                                attStr.replaceCharacters(in: range, with: rep)
                            }
                        }
                    }
                }
            }
            
            return attStr
        }
    

    上面就是根据一个正则表达式,匹配出字符串中符合的字符串数组,遍历数组,从后往前替换(想想为什么呢?)。替换的方法是创建一个NSTextAttachment对象,给它一个UIImage和bounds,就可以用它初始化一个NSAttributedString,替换字符串就完成了。

    最终效果图.png

    相关文章

      网友评论

        本文标题:iOS-富文本显示表情

        本文链接:https://www.haomeiwen.com/subject/owibattx.html