NSAttributedString(二)NSTextAttac

2023-04-02  本文已影响0人  fanren

一、使用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
结果

这其中有两个问题:

  1. 结果虽然正常显示了attachment,但是它与其他文本没有垂直居中;
  2. fontlineHeight35.800781,但是根据boundingRectWithSize计算出来的高度却是43.037109;

这是因为两个原因导致的:

所以attachment的实际y坐标,是-baseFont.descender,即-7.236328,而这刚好是上方boundingRectWithSizelineHeight的差值;

通过上方的结论,我们可以使用两种方法来使attachment与文字垂直居中对齐:

二、设置attachmentbounds

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的方案更优;

上一篇 下一篇

猜你喜欢

热点阅读