一、使用NSTextAttachment可渲染富文本中的图片
NSString *text = @"efghefghefgh";
UIFont *baseFont = [UIFont boldSystemFontOfSize:30];
NSMutableAttributedString *result = [[NSMutableAttributedString alloc] initWithString:text];
[result addAttributes:@{NSFontAttributeName: baseFont} range:NSMakeRange(0, text.length)];
NSTextAttachment *attachment = [[NSTextAttachment alloc] init];
attachment.image = [UIImage imageNamed:@"love"];
attachment.bounds = CGRectMake(0, 0, baseFont.lineHeight, baseFont.lineHeight);
NSAttributedString *attachmentStr = [NSAttributedString attributedStringWithAttachment:attachment];
[result insertAttributedString:attachmentStr atIndex:4];
CGRect rect = [result boundingRectWithSize:CGSizeMake(CGFLOAT_MAX, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading context:NULL];
NSLog(@"lineHeight--%f", baseFont.lineHeight); // 35.800781
NSLog(@"bounding--%f", rect.size.height); // 43.037109

结果
这其中有两个问题:
- 结果虽然正常显示了
attachment,但是它与其他文本没有垂直居中;font的lineHeight是35.800781,但是根据boundingRectWithSize计算出来的高度却是43.037109;
这是因为两个原因导致的:
-
NSTextAttachment默认的垂直对齐方式,也是基线对齐; -
attachment.bounds = CGRectMake(0, 0, baseFont.lineHeight, baseFont.lineHeight);,我们设置了attachment的高度为baseFont.lineHeight;
所以attachment的实际y坐标,是
-baseFont.descender,即-7.236328,而这刚好是上方boundingRectWithSize与lineHeight的差值;
通过上方的结论,我们可以使用两种方法来使attachment与文字垂直居中对齐:
- 设置
attachment的bounds - 通过设置
NSBaselineOffsetAttributeName;
二、设置attachment的bounds
CGFloat height = 40;
CGFloat originX = [self calculateOriginY:baseFont height:height];
attachment.bounds = CGRectMake(0, originX, height, height);
...
NSLog(@"lineHeight--%f", baseFont.lineHeight); // 35.800781
NSLog(@"bounding--%f", rect.size.height); // 35.800781
...
- (CGFloat)calculateOriginY:(UIFont *)baseFont height:(CGFloat)height
{
CGFloat baseHeight = baseFont.lineHeight;
CGFloat baseDescender = -baseFont.descender;
CGFloat result = (baseHeight - height) / 2 - baseDescender;
return result;
}

image.png
二、设置NSBaselineOffsetAttributeName
attachment.bounds = CGRectMake(0, 0, height, height);
NSMutableAttributedString *attachmentStr = [[NSAttributedString attributedStringWithAttachment:attachment] mutableCopy];
CGFloat baseline = [self calculateBaseLineOffset:baseFont height:height];
[attachmentStr addAttributes:@{NSBaselineOffsetAttributeName: @(baseline)} range:NSMakeRange(0, attachmentStr.length)];
NSLog(@"lineHeight--%f", baseFont.lineHeight); // 35.800781
NSLog(@"bounding--%f", rect.size.height); // 44.595703
...
- (CGFloat)calculateBaseLineOffset:(UIFont *)baseFont height:(CGFloat)height
{
CGFloat baseHeight = baseFont.lineHeight;
CGFloat baseDescender = -baseFont.descender;
CGFloat result = (baseHeight - height) / 2 - baseDescender;
return result;
}

结论
虽然通过
NSBaselineOffsetAttributeName可以实现垂直居中,但是也有缺陷,boundingRectWithSize计算的高度与lineHeight不符;
结论:设置bounds的方案更优;