ios开发之属性字符串NSAttributeString与NSString相互转换包含图片

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

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

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

技术分享

+(NSMutableAttributedString *)stringToAttributeString:(NSString *)text
{
    //先把普通的字符串text转化生成Attributed类型的字符串
    NSMutableAttributedString * attStr = [[NSMutableAttributedString alloc]initWithString:text];
    
    NSString * zhengze = @"\\[[a-zA-Z0-9\\u4e00-\\u9fa5]+\\]"; //正则表达式 ,例如  [呵呵] 这种形式的通配符
    
    NSError * error;
<span style="font-family: Arial, Helvetica, sans-serif;"> NSRegularExpression * re = [NSRegularExpression regularExpressionWithPattern:zhengze options:NSRegularExpressionCaseInsensitive error:&error];//正则表达式</span>
    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大小:

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

+(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;//返回属性字符串的尺寸
}

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

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

//不能直接得到串的名字?
-(NSString *)stringFromImage:(UIImage *)image
{
    NSArray *face=[self getAllImagePaths];
    
    NSData * imageD = UIImagePNGRepresentation(image);
    
    NSString * imageName;
    
    for (int i=0; i<face.count; i++)
    {
        UIImage *image=[UIImage imageNamed:face[i][@"png"]];
        NSData *data=UIImagePNGRepresentation(image);
        if ([imageD isEqualToData:data])
        {
            imageName=face[i][@"chs"];
            //NSLog(@"匹配成功!");
        }
    }
    
    
    return imageName;
}




-(NSArray *)getAllImagePaths//数组结构还是上述的截图的数组结构
{
    NSBundle *bundle = [NSBundle mainBundle];
    
    NSString * path = [bundle pathForResource:@"emotions" ofType:@"plist"];
    
    NSArray * face = [[NSArray alloc]initWithContentsOfFile:path];
    
    return face;
}
属性字符串转换为普通字符串:

假设为TextView,label,button同理

//把带有图片的属性字符串转成普通的字符串
-(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;

}

原文地址:http://blog.csdn.net/yangbingbinga/



郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。