iOS 富文本中插入表情图片非常容易,可是显示的时候发现位置总是不在设想的位置,虽然经过微调也可展示到居中的位置,但还是感觉有问题。找了好多资料终于发现了表情图片位置计算规律。
- (NSMutableAttributedString *)getAttributedString:(NSString *)content image:(UIImage *)image font:(UIFont *)font {
NSMutableAttributedString *contentAtt = [[NSMutableAttributedString alloc] initWithString:content attributes:@{NSFontAttributeName : font}];
NSTextAttachment *imageMent = [[NSTextAttachment alloc] init];
imageMent.image = image;
CGFloat paddingTop = font.lineHeight - font.pointSize;
imageMent.bounds = CGRectMake(0, -paddingTop, font.lineHeight, font.lineHeight);
NSAttributedString *imageAtt = [NSAttributedString attributedStringWithAttachment:imageMent];
[contentAtt appendAttributedString:imageAtt];
return contentAtt;
}
网友评论