自定義表情 NSString和NSAttributedString相互轉換

首先,先實現普通字符串轉屬性字符串吧(網上現成的??):

+(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:@"emj" 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][@"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;

}

}

}

return attStr;

}

當然,你肯定會需要轉回來??:

//把帶有圖片的屬性字符串轉成普通的字符串

+ (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"];//從字典中取得那一個圖片

if (textAtt)

{

UIImage * image = textAtt.image;

NSString * text = [helper stringFromImage:image];

[resutlAtt replaceCharactersInRange:range withString:text];

}

}];

return resutlAtt.string;

}

//獲取圖片數組

-(NSArray *)getAllImagePaths//數組結構還是上述的截圖的數組結構

{

NSBundle *bundle = [NSBundle mainBundle];

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

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

return face;

}

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

+(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:@"emj" 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][@"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;//返回屬性字符串的尺寸

}

當然,以上這些都是網上現成的??酗洒,下面要寫一點不一樣的東西了??????????????????????????????????????????????

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

1樱衷、UITextView棋嘲、UITextField

以UITextView為例,假設你得到的屬性字符串是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
設置顯示的大小。

2侄榴、UILabel

這個控件就不用多說了雹锣,直接有個屬性名字叫attributedText,設上result
就能顯示了癞蚕。

本文就到此結束了??????????蕊爵。。桦山。攒射。醋旦。

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市会放,隨后出現的幾起案子饲齐,更是在濱河造成了極大的恐慌,老刑警劉巖咧最,帶你破解...
    沈念sama閱讀 222,807評論 6 518
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件捂人,死亡現場離奇詭異,居然都是意外死亡窗市,警方通過查閱死者的電腦和手機先慷,發(fā)現死者居然都...
    沈念sama閱讀 95,284評論 3 399
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來咨察,“玉大人论熙,你說我怎么就攤上這事∩阌” “怎么了脓诡?”我有些...
    開封第一講書人閱讀 169,589評論 0 363
  • 文/不壞的土叔 我叫張陵,是天一觀的道長媒役。 經常有香客問我祝谚,道長,這世上最難降的妖魔是什么酣衷? 我笑而不...
    開封第一講書人閱讀 60,188評論 1 300
  • 正文 為了忘掉前任交惯,我火速辦了婚禮,結果婚禮上穿仪,老公的妹妹穿的比我還像新娘席爽。我一直安慰自己,他們只是感情好啊片,可當我...
    茶點故事閱讀 69,185評論 6 398
  • 文/花漫 我一把揭開白布只锻。 她就那樣靜靜地躺著,像睡著了一般紫谷。 火紅的嫁衣襯著肌膚如雪齐饮。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 52,785評論 1 314
  • 那天笤昨,我揣著相機與錄音祖驱,去河邊找鬼。 笑死瞒窒,一個胖子當著我的面吹牛羹膳,可吹牛的內容都是我干的。 我是一名探鬼主播根竿,決...
    沈念sama閱讀 41,220評論 3 423
  • 文/蒼蘭香墨 我猛地睜開眼陵像,長吁一口氣:“原來是場噩夢啊……” “哼就珠!你這毒婦竟也來了?” 一聲冷哼從身側響起醒颖,我...
    開封第一講書人閱讀 40,167評論 0 277
  • 序言:老撾萬榮一對情侶失蹤礁叔,失蹤者是張志新(化名)和其女友劉穎似芝,沒想到半個月后,有當地人在樹林里發(fā)現了一具尸體,經...
    沈念sama閱讀 46,698評論 1 320
  • 正文 獨居荒郊野嶺守林人離奇死亡苗膝,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 38,767評論 3 343
  • 正文 我和宋清朗相戀三年束凑,在試婚紗的時候發(fā)現自己被綠了氛堕。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片枪芒。...
    茶點故事閱讀 40,912評論 1 353
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖挺庞,靈堂內的尸體忽然破棺而出晰赞,到底是詐尸還是另有隱情,我是刑警寧澤选侨,帶...
    沈念sama閱讀 36,572評論 5 351
  • 正文 年R本政府宣布掖鱼,位于F島的核電站,受9級特大地震影響援制,放射性物質發(fā)生泄漏戏挡。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 42,254評論 3 336
  • 文/蒙蒙 一晨仑、第九天 我趴在偏房一處隱蔽的房頂上張望褐墅。 院中可真熱鬧,春花似錦洪己、人聲如沸妥凳。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,746評論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽猾封。三九已至澄耍,卻和暖如春噪珊,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背齐莲。 一陣腳步聲響...
    開封第一講書人閱讀 33,859評論 1 274
  • 我被黑心中介騙來泰國打工痢站, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人选酗。 一個月前我還...
    沈念sama閱讀 49,359評論 3 379
  • 正文 我出身青樓阵难,卻偏偏與公主長得像,于是被迫代替她去往敵國和親芒填。 傳聞我的和親對象是個殘疾皇子呜叫,可洞房花燭夜當晚...
    茶點故事閱讀 45,922評論 2 361

推薦閱讀更多精彩內容