一、使用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;
}
二、设置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
的方案更优;