利用NSTextAttachment实现简单的图文混排
//添加UItextView,NSTextView是支持富文本编辑器的控件
UITextView *label=[[UITextView alloc]initWithFrame:CGRectMake(20, 50, self.view.frame.size.width-40, 300)];
[self.view addSubview:label];
//设置内容
NSMutableAttributedString *string =[[NSMutableAttributedString alloc]initWithString:@"123456789101112" attributes:nil];
NSTextAttachment *textAttachment = [[ NSTextAttachment alloc ] initWithData:nil ofType:nil ] ;
UIImage * smileImage = [UIImage imageNamed:@"test.jpg"];
// 方法1
textAttachment.image = [self image:smileImage byScalingToSize:CGSizeMake(20,20)];
// 方法2
// textAttachment.image =smileImage;
// textAttachment.bounds=CGRectMake(0, 0, 20, 20);
NSAttributedString * textAttachmentString = [ NSAttributedString attributedStringWithAttachment:textAttachment ] ;
[ string insertAttributedString:textAttachmentString atIndex:6 ] ;
label.attributedText = string ;
#pragma makr-返回修改大小后的图片
- (UIImage *)image:(UIImage*)image byScalingToSize:(CGSize)targetSize {
UIImage *sourceImage = image;
UIImage *newImage = nil;
UIGraphicsBeginImageContext(targetSize);
CGRect thumbnailRect = CGRectZero;
thumbnailRect.origin = CGPointZero;
thumbnailRect.size.width = targetSize.width;
thumbnailRect.size.height = targetSize.height;
[sourceImage drawInRect:thumbnailRect];
newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage ;
}
AttributedString属性参照
// NSFontAttributeName 设置字体属性,默认值:字体