#pragma mark 获取含自定义的图片的字符串
-(NSMutableAttributedString *)ImgWithString:(NSString *)string
{
if (!string) {
return [NSMutableAttributedString new];
}
NSMutableAttributedString *result = [[NSMutableAttributedString alloc] initWithString:string];
//所有表情数组
NSArray *expressionList = [[NSArray new] EmoticonArray];
int i = 0;
while (i < expressionList.count) {
NSString *item = expressionList[i];
NSRange range = [result.string rangeOfString:item];
if(range.location == NSNotFound){
i++;
continue;
}
ImageTextAttachment *textAttachment = [[ImageTextAttachment alloc] init];
//表情文本替换成图片
UIImage * image = [UIImage imageNamed:[self stringToImageName:item]];
CGSize size = [image size];
textAttachment.bounds = CGRectMake(0, 0, size.width*16/size.height, 16);
textAttachment.image = image;
textAttachment.imageTag = item;
NSAttributedString *attchString = [NSAttributedString attributedStringWithAttachment:textAttachment];
[result replaceCharactersInRange:range withAttributedString:attchString];
}
return result;
}
#pragma mark 根据表情名称--得到图片名称
-(NSString *)stringToImageName:(NSString *)string
{
NSString *result = string;
result = [result stringByReplacingOccurrencesOfString:@"/" withString:@""];
result = [result stringByReplacingOccurrencesOfString:@"[" withString:@""];
result = [result stringByReplacingOccurrencesOfString:@"]" withString:@""];
return result;
}
#pragma mark 图片转化成纯文本
-(NSString *)getPlainString {
NSMutableString *plainString = [NSMutableString stringWithString:self.string];
__block NSUInteger base = 0;
[self enumerateAttribute:NSAttachmentAttributeName inRange:NSMakeRange(0, self.length)
options:0
usingBlock:^(id value, NSRange range, BOOL *stop) {
//检查类型是否是自定义NSTextAttachment类
if (value && [value isKindOfClass:[ImageTextAttachment class]]) {
//替换
[plainString replaceCharactersInRange:NSMakeRange(range.location + base, range.length) withString:((ImageTextAttachment *) value).imageTag];
//增加偏移量
base += ((ImageTextAttachment *) value).imageTag.length - 1;
}
}];
return plainString;
}
网友评论