#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;
}
iOS中表情等含图片的字符串
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...