实现步骤:
- 生成一个图片的附件
- 创建一个富文本对象
- 设置图片的bounds
- 将图片添加到富文本上
- 把图片富文本转换成可变的富文本
图片文本
- 创建NSTextAttachment的对象,用来装载图片
- 将NSTextAttachment对象的image属性设置为想要使用的图片
- 设置NSTextAttachment对象bounds大小,也就是要显示的图片的大小
- 用[NSAttributedString attributedStringWithAttachment:attch]方法,将图片添加到富文本上
例子:
//1. 生成一个图片的附件
UIImage *image1 = [UIImage imageWithContentsOfFile:path];
///////根据自己项目的到真实的宽高////
NSArray *widths = [temp3[1] componentsSeparatedByString:@"<HEIGHT>"];
NSArray *heights = [widths[1] componentsSeparatedByString:@"<ID>"];
CGFloat realWidth = [widths[0] floatValue];
CGFloat realHeight = [heights[0] floatValue];
///////////////////////////////
//2.创建一个富文本对象,用来装载图片
NSTextAttachment *attachment = [[NSTextAttachment alloc] init];
//给附件添加图片
attachment.image = image1;
CGFloat imgWidth = [self getImgWidthWithImg:realWidth realheight:realHeight];
CGFloat imgHeight = [self getImgHeightWithImg:realWidth realheight:realHeight];
//3.设置图片的bounds :调整一下图片的位置,如果你的图片偏上或者偏下,调整一下bounds的y值即可
attachment.bounds = CGRectMake(0, 0, imgWidth, imgHeight);
//3.将图片添加到富文本上
NSAttributedString *textAttachmentString = [NSAttributedString attributedStringWithAttachment:attachment];
//4.把图片富文本转换成可变的富文本
NSMutableAttributedString *string = [[NSMutableAttributedString alloc]initWithAttributedString:_cardContentTv.attributedText];
[string insertAttributedString:textAttachmentString atIndex:_cardContentTv.selectedRange.location];
_cardContentTv.attributedText = string;
遇到的问题:
当图片存在沙盒documents中时,每次重启APP沙盒docu路径是变化的,所以要使用之前保存在沙盒中的图片的时候要用当前的沙盒doc路径
别人写的一个基于swift的demo https://github.com/VitasLiu/WeiBoComposeDemo