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

來源:互聯網
上載者:User

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]+\]; //Regex ,例如  [呵呵] 這種形式的萬用字元        NSError * error;
 NSRegularExpression * re = [NSRegularExpression regularExpressionWithPattern:zhengze options:NSRegularExpressionCaseInsensitive error:&error];//Regex
    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(@Regex匹配錯誤%@,[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;}

 

 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.