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

liushuaikobe
  • 2,046
  • 1
  • 20
  • 23
0924wuyr
  • 13
  • 3
  • in Chinese input,after insert a NSTextAttachment,then no matter what i input,the NSTextAttachment just insert repeat show at the mark area.. however ,it normal when i test by ios8 – 0924wuyr Oct 23 '15 at 01:58
  • maybe should resetTextViewStyle or something , because after insert attachment,then i type a blank space, then every is fine. – 0924wuyr Oct 23 '15 at 02:01

0 Answers0