1. 基础知识
2. 示例
self.view.backgroundColor = [UIColor darkGrayColor];
UIFont *font15 = [UIFont systemFontOfSize:15];
UIFont *font30 = [UIFont systemFontOfSize:30];
NSDictionary *dic1 = @{NSFontAttributeName:font15,
NSForegroundColorAttributeName:[UIColor blackColor],
NSBackgroundColorAttributeName:[UIColor yellowColor],
NSBaselineOffsetAttributeName:@0,
// NSBaselineOffsetAttributeName:@((font30.lineHeight - font15.lineHeight)/2 + ((font30.descender - font15.descender)))
};
NSDictionary *dic2 = @{NSFontAttributeName:font30,
NSForegroundColorAttributeName:[UIColor redColor],
NSBackgroundColorAttributeName:[UIColor yellowColor],
NSBaselineOffsetAttributeName:@0
};
NSMutableAttributedString *attributeStr1 = [[NSMutableAttributedString alloc] initWithString:@"a" attributes:dic1];
NSAttributedString *attributeStr2 = [[NSAttributedString alloc] initWithString:@"Aa" attributes:dic2];
[attributeStr1 appendAttributedString:attributeStr2];
// - 图片
NSTextAttachment *attachment = [[NSTextAttachment alloc] init];
attachment.image = [UIImage imageNamed:@"ab"];
attachment.bounds = CGRectMake(0,0,font30.ascender,font30.ascender);
[attributeStr1 appendAttributedString:[NSAttributedString attributedStringWithAttachment:attachment]];
CGRect rect = [attributeStr1 boundingRectWithSize:CGSizeMake(600, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading context:NULL];
NSLog(@"lineHeight : %f %f",font15.lineHeight, font30.lineHeight);
NSLog(@"pointSize : %f %f",font15.pointSize, font30.pointSize);
NSLog(@"descender : %f %f",font15.descender, font30.descender);
NSLog(@"ascender : %f %f",font15.ascender, font30.ascender);
NSLog(@"leading : %f %f",font15.leading, font30.leading);
NSLog(@"descender + ascender + leading = %f, %f",font15.ascender - font15.descender + font15.leading, font30.ascender - font30.descender + font30.leading);
NSLog(@"boundingRectWithSizeHeight : %f",rect.size.height);
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 100, 600, 100)];
label.attributedText = attributeStr1;
label.numberOfLines = 0;
[self.view addSubview:label];
2021-11-23 16:38:37.268589+0800 Demo_03[18590:4777570] lineHeight : 17.900391 35.800781
2021-11-23 16:38:37.268675+0800 Demo_03[18590:4777570] pointSize : 15.000000 30.000000
2021-11-23 16:38:37.268705+0800 Demo_03[18590:4777570] descender : -3.618164 -7.236328
2021-11-23 16:38:37.268728+0800 Demo_03[18590:4777570] ascender : 14.282227 28.564453
2021-11-23 16:38:37.268753+0800 Demo_03[18590:4777570] leading : 0.000000 0.000000
2021-11-23 16:38:37.268776+0800 Demo_03[18590:4777570] descender + ascender + leading = 17.900391, 35.800781
2021-11-23 16:38:37.268800+0800 Demo_03[18590:4777570] boundingRectWithSizeHeight : 35.800781
3. 原理
4. 方法
-
默认样式
-
让两个字体的文字居中对齐
NSBaselineOffsetAttributeName:@((font30.lineHeight - font15.lineHeight)/2 + ((font30.descender - font15.descender)))
- 让图片居中对齐
attachment.bounds = CGRectMake(0,font30.descender,font30.lineHeight,font30.lineHeight);