自定義表情 NSString和NSAttributedString相互轉(zhuǎn)換

首先,先實(shí)現(xiàn)普通字符串轉(zhuǎn)屬性字符串吧(網(wǎng)上現(xiàn)成的??):

+(NSMutableAttributedString *)stringToAttributeString:(NSString *)text

{

//先把普通的字符串text轉(zhuǎn)化生成Attributed類型的字符串

NSMutableAttributedString * attStr = [[NSMutableAttributedString alloc]initWithString:text];

NSString * zhengze = @"\\[\\([a-zA-Z0-9\u4e00-\u9fa5]+\\)\\]"; //正則表達(dá)式 ,例如  [(呵呵)] = ??

NSError * error;

NSRegularExpression * re = [NSRegularExpression regularExpressionWithPattern:zhengze options:NSRegularExpressionCaseInsensitive error:&error];

if (!re)

{

NSLog(@"%@??",[error localizedDescription]);//打印錯(cuò)誤??

}

NSArray * arr = [re matchesInString:text options:0 range:NSMakeRange(0, text.length)];//遍歷字符串,獲得所有的匹配字符串

NSBundle *bundle = [NSBundle mainBundle];

NSString * path = [bundle pathForResource:@"emj" ofType:@"plist"];  //plist文件,制作一個(gè) 數(shù)組,包含文字,表情圖片名稱

NSArray * face = [[NSArray alloc]initWithContentsOfFile:path];//獲取 所有的數(shù)組

//如果有多個(gè)表情圖,必須從后往前替換,因?yàn)樘鎿Q后Range就不準(zhǔn)確了

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][@"key"]])//從數(shù)組中的字典中取元素

{

NSString * imageName = [NSString stringWithString:face[i][@"picture"]];

NSTextAttachment * textAttachment = [[NSTextAttachment alloc]init];//添加附件,圖片

textAttachment.image = [UIImage imageNamed:imageName];

NSAttributedString * imageStr = [NSAttributedString attributedStringWithAttachment:textAttachment];

[attStr replaceCharactersInRange:result.range withAttributedString:imageStr];//替換未圖片附件

break;

}

}

}

return attStr;

}

當(dāng)然,你肯定會(huì)需要轉(zhuǎn)回來??:

//把帶有圖片的屬性字符串轉(zhuǎn)成普通的字符串

+ (NSString *)textString:(NSAttributedString *)attributedText

{

NSMutableAttributedString * resutlAtt = [[NSMutableAttributedString alloc]initWithAttributedString:attributedText];

EmoticonsHelper * helper = [EmoticonsHelper new];

//枚舉出所有的附件字符串

[attributedText enumerateAttributesInRange:NSMakeRange(0, attributedText.length) options:NSAttributedStringEnumerationReverse usingBlock:^(NSDictionary *attrs, NSRange range, BOOL *stop) {

NSTextAttachment * textAtt = attrs[@"NSAttachment"];//從字典中取得那一個(gè)圖片

if (textAtt)

{

UIImage * image = textAtt.image;

NSString * text = [helper stringFromImage:image];

[resutlAtt replaceCharactersInRange:range withString:text];

}

}];

return resutlAtt.string;

}

//獲取圖片數(shù)組

-(NSArray *)getAllImagePaths//數(shù)組結(jié)構(gòu)還是上述的截圖的數(shù)組結(jié)構(gòu)

{

NSBundle *bundle = [NSBundle mainBundle];

NSString * path = [bundle pathForResource:@"emojo" ofType:@"plist"];

NSArray * face = [[NSArray alloc]initWithContentsOfFile:path];

return face;

}

會(huì)不會(huì)需要屬性字符串的尺寸大小呢?不用著急,直接有代碼:

+(CGSize)getAttributedTextSize:(NSString *)text

{

//先把普通的字符串text轉(zhuǎn)化生成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(@"正則表達(dá)式匹配錯(cuò)誤%@" ,[error localizedDescription]);

}

NSArray * arr = [re matchesInString:text options:0 range:NSMakeRange(0, text.length)];

if (!arr.count)//說明字符串中沒有表情通配符,是普通的文本,則計(jì)算文本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:@"emj" ofType:@"plist"];

NSArray * face = [[NSArray alloc]initWithContentsOfFile:path];

//如果有多個(gè)表情圖,必須從后往前替換,因?yàn)樘鎿Q后Range就不準(zhǔn)確了

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][@"key"]])

{

NSString * imageName = [NSString stringWithString:face[i][@"picture"]];

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;//返回屬性字符串的尺寸

}

當(dāng)然,以上這些都是網(wǎng)上現(xiàn)成的??,下面要寫一點(diǎn)不一樣的東西了??????????????????????????????????????????????

     首先我們知道和字符串相關(guān)的UI控件呢不外乎那么幾種,怎么樣利用上屬性字符串呢???

1、UITextView、UITextField

以UITextView為例,假設(shè)你得到的屬性字符串是NSAttributedString *result,我要顯示出表情圖片還得:

[TextView.textStorage insertAttributedString:result TextView.selectedRange.location];

TextView.selectedRange = NSMakeRange(TextView.selectedRange.location+1, 0);

//重置格式

NSRange wholeRange = NSMakeRange(0,TextView.textStorage.length);

[TextView.textStorage removeAttribute:NSFontAttributeName range:wholeRange];

[TextView.textStorage addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:20.0f] range:wholeRange];

這樣不但能顯示表情圖片到你的TextView里??,還能通過UIFont
設(shè)置顯示的大小。

2、UILabel

這個(gè)控件就不用多說了,直接有個(gè)屬性名字叫attributedText,設(shè)上result
就能顯示了。

本文就到此結(jié)束了??????????。。。。。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容