0

I want to insert a 'text image' into the textView using the NSTextAttachment. It's fine when the text is English, but something wrong when the text is Chinese. the code:

- (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;

}

the screenshot

4

0 回答 0