ios学习--属性字符串NSAttributeString与NSString相互转换包含图片和emoji图

分享几个常用的 属性字符串NSAtrributeString 和 NSString 普通字符串的 转换方法:

 

 

一:把普通的字符串,替换为包含图片的属性字符串

plist 文件,图片 格式见下图:

加载中...

?
1
2
3
4
5
6
7
8
+(NSMutableAttributedString *)stringToAttributeString:(NSString *)text
{
     //先把普通的字符串text转化生成Attributed类型的字符串
     NSMutableAttributedString * attStr = [[NSMutableAttributedString alloc]initWithString:text];
     
     NSString * zhengze = @\[[a-zA-Z0- 9 \u4e00-\u9fa5]+\]; //正则表达式 ,例如  [呵呵] 这种形式的通配符
     
     NSError * error;
?
1
<span style= "font-family:" > NSRegularExpression * re = [NSRegularExpression regularExpressionWithPattern:zhengze options:NSRegularExpressionCaseInsensitive error:&error]; //正则表达式</span>
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
     if (!re)
     {
         NSLog(@%@,[error localizedDescription]); //打印错误
     }
     
     NSArray * arr = [re matchesInString:text options: 0 range:NSMakeRange( 0 , text.length)]; //遍历字符串,获得所有的匹配字符串
     
     NSBundle *bundle = [NSBundle mainBundle];
     NSString * path = [bundle pathForResource: @emotions ofType: @plist ];  //plist文件,制作一个 数组,包含文字,表情图片名称
     NSArray * face = [[NSArray alloc]initWithContentsOfFile:path];  //获取 所有的数组
     
     //如果有多个表情图,必须从后往前替换,因为替换后Range就不准确了
     for ( int j =( int ) arr.count - 1 ; j >= 0 ; j--) {
         //NSTextCheckingResult里面包含range
         NSTextCheckingResult * result = arr[j];
         
         for ( int i = 0 ; i < face.count; i++) {
             if ([[text substringWithRange:result.range] isEqualToString:face[i][ @chs ]]) //从数组中的字典中取元素
             {
                 NSString * imageName = [NSString stringWithString:face[i][ @png ]];
                 
                 NSTextAttachment * textAttachment = [[NSTextAttachment alloc]init]; //添加附件,图片
                 
                 textAttachment.image = [UIImage imageNamed:imageName];
                 
                 NSAttributedString * imageStr = [NSAttributedString attributedStringWithAttachment:textAttachment];
                 
                 [attStr replaceCharactersInRange:result.range withAttributedString:imageStr]; //替换未图片附件
                 
                 break ;
             }
         }
     }
     return attStr;
}

二:获取属性字符串的size大小:

注:对包含文字和图片的属性字符串,需要根据实际情况,调节其大小

 

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
+(CGSize)getAttributedTextSize:(NSString *)text
{
     //先把普通的字符串text转化生成Attributed类型的字符串
     NSMutableAttributedString * attStr = [[NSMutableAttributedString alloc]initWithString:text];
     
     NSString * zhengze = @\[[a-zA-Z0- 9 \u4e00-\u9fa5]+\];
     
     NSError * error;
     
     NSRegularExpression * re = [NSRegularExpression regularExpressionWithPattern:zhengze options:NSRegularExpressionCaseInsensitive error:&error];
     if (!re)
     {
         NSLog(@正则表达式匹配错误%@,[error localizedDescription]);
     }
     
     NSArray * arr = [re matchesInString:text options: 0 range:NSMakeRange( 0 , text.length)];
     
     
     if (!arr.count) //说明字符串中没有表情通配符,是普通的文本,则计算文本size
     {
         NSDictionary *dic=@{NSFontAttributeName: [UIFont systemFontOfSize: 14 ]};
         
         
         CGSize size1=[text boundingRectWithSize:CGSizeMake( 160 , 1000 ) options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil].size;
         
         if (size1.height<= 60 )
         {
             size1.height= 60 ;
         }
         
         else
         {
             size1.height+= 15 ;
         }
         
         
         
         return size1;
     }
     
     NSBundle *bundle = [NSBundle mainBundle];
     NSString * path = [bundle pathForResource: @emotions ofType: @plist ];
     NSArray * face = [[NSArray alloc]initWithContentsOfFile:path];
     
     //如果有多个表情图,必须从后往前替换,因为替换后Range就不准确了
     for ( int j =( int ) arr.count - 1 ; j >= 0 ; j--) {
         //NSTextCheckingResult里面包含range
         NSTextCheckingResult * result = arr[j];
         
         for ( int i = 0 ; i < face.count; i++) {
             if ([[text substringWithRange:result.range] isEqualToString:face[i][ @chs ]])
             {
                 NSString * imageName = [NSString stringWithString:face[i][ @png ]];
                 
                 NSTextAttachment * textAttachment = [[NSTextAttachment alloc]init];
                 
                 textAttachment.image = [UIImage imageNamed:imageName];
                 
                 NSAttributedString * imageStr = [NSAttributedString attributedStringWithAttachment:textAttachment];
                 
                 [attStr replaceCharactersInRange:result.range withAttributedString:imageStr];
                 
                 break ;
             }
         }
     }
     
     CGSize size2=[attStr boundingRectWithSize:CGSizeMake( 180 , 1000 ) options:NSStringDrawingUsesLineFragmentOrigin context:nil].size;
     
     size2.height+= 40 //表情文字增加高度
     
     
     
     return size2; //返回属性字符串的尺寸
}

三: 属性字符串转为普通字符串, 关键点: 图片的二进制比对(可以放入到一个 子线程去做)

 

图片二进制比对,获得图片名称:

 

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
//不能直接得到串的名字?
-(NSString *)stringFromImage:(UIImage *)image
{
     NSArray *face=[self getAllImagePaths];
     
     NSData * imageD = UIImagePNGRepresentation(image);
     
     NSString * imageName;
     
     for ( int i= 0 ; i<face.count; bundle= "[NSBundle" data= "UIImagePNGRepresentation(image);" emotions= "" face= "[[NSArray" getallimagepaths= "" if = "" image= "[UIImage" imaged= "" imagename= "face[i][@chs];" nsarray= "" nsbundle= "" nsdata= "" nsstring= "" path= "[bundle" pre= "" return = "" uiimage= "" >属性字符串转换为普通字符串:<p> </p><p>假设为TextView,label,button同理</p><p> </p><pre class = "brush:java;" > //把带有图片的属性字符串转成普通的字符串
-(NSString *)textString
{
     NSAttributedString * att = self.attributedText;
     
     NSMutableAttributedString * resutlAtt = [[NSMutableAttributedString alloc]initWithAttributedString:att];
     
     
     __weak __block UITextView * copy_self = self;
     //枚举出所有的附件字符串
     [att enumerateAttributesInRange:NSMakeRange( 0 , att.length) options:NSAttributedStringEnumerationReverse usingBlock:^(NSDictionary *attrs, NSRange range, BOOL *stop) {
         //key-NSAttachment
         //NSTextAttachment value类型
         NSTextAttachment * textAtt = attrs[ @NSAttachment ]; //从字典中取得那一个图片
         if (textAtt)
         {
             UIImage * image = textAtt.image;
             NSString * text = [copy_self stringFromImage:image];
             [resutlAtt replaceCharactersInRange:range withString:text];
             
         }
         
         
     }];
     
     
     return resutlAtt.string;
 
}
</pre>
<br>
<p> </p>
<p> </p>
<p> </p>
</face.count;>




转载自:http://www.2cto.com/kf/201501/372511.html
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值