我想使用NSTextAttachment
在textView中插入“文本图片”。当文本是英文时很好,但是当文本是中文时出错了。代码:
- (IBAction)insertAt:(id)sender {
UIColor *color = [UIColor redColor];
UIFont *font = [UIFont systemFontOfSize:18.0];
NSTextAttachment *at = [[NSTextAttachment alloc] init];
NSString *name = @"TEST";
at.image = [self getImage:name];
NSMutableAttributedString *atAttribuString = [[NSAttributedString attributedStringWithAttachment:at] mutableCopy];
[atAttribuString addAttributes:@{NSFontAttributeName:font, NSForegroundColorAttributeName:color} range:NSMakeRange(0, atAttribuString.length)];
[self.textView.textStorage replaceCharactersInRange:self.textView.selectedRange
withAttributedString:atAttribuString];
self.textView.markedTextStyle = @{NSFontAttributeName:font, NSForegroundColorAttributeName:color};
}
- (UIImage*)getImage:(NSString*)text {
UIColor *color = [UIColor redColor];
UIFont *font = [UIFont systemFontOfSize:18.0];
CGRect rect = [text boundingRectWithSize:CGSizeMake(1000, 1000) options:NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading attributes:@{NSFontAttributeName:font, NSForegroundColorAttributeName:color} context:nil];
CGFloat leading = 0.0;
rect = CGRectMake(leading, 0.0, CGRectGetWidth(rect) + leading * 2, CGRectGetHeight(rect));
// UIGraphicsBeginImageContext(rect.size);
UIGraphicsBeginImageContextWithOptions(rect.size, NO, 0.0);
[text drawInRect:rect withAttributes:@{NSFontAttributeName:font, NSForegroundColorAttributeName:color}];
// 从当前context中创建一个改变大小后的图片
UIImage *textImage = UIGraphicsGetImageFromCurrentImageContext();
// 使当前的context出堆栈
UIGraphicsEndImageContext();
return textImage;
}