你好,歡迎來到IOS教程網

 Ios教程網 >> IOS編程開發 >> IOS開發綜合 >> ios開發之屬性字符串NSAttributeString與NSString相互轉換包含圖片

ios開發之屬性字符串NSAttributeString與NSString相互轉換包含圖片

編輯:IOS開發綜合

分享幾個常用的 屬性字符串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;
 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)];//遍歷字符串,獲得所有的匹配字符串
    
    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屬性字符串轉換為普通字符串:

 

假設為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;

}

 

 

 

  1. 上一頁:
  2. 下一頁:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © Ios教程網 All Rights Reserved