2018-08-09 富文本 文字大小不同居中对齐

转自:https://blog.csdn.net/kuangdacaikuang/article/details/79584587

解决NSMutableAttributedString富文本,不同文字大小水平轴对齐问题(默认底部对齐)

默认是底部对齐,其实对的也不齐,

目标效果:

代码:

NSBaselineOffsetAttributeName

基线偏移量:
调整: NSBaselineOffsetAttributeName的值得大小,就可以得到不同的对齐位置

CGFloat fontRatio = 0.16;//基线偏移比率
CGFloat fontRatio = 0.66;//基线偏移比率
20180316171739121.png
2018031617185531.png
2018031617241740.png
20180316172346486.png
- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"富文本";

    NSString *text = @"(2) 3 : 2 (1)";

    NSInteger fontSize1 = 30;
    NSInteger fontSize2 = 16;
    CGFloat fontRatio = 0.66;//基线偏移比率

    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(150, 200, 150, 40)];
    label.text = text;

    NSMutableAttributedString *attributedStringM = [[NSMutableAttributedString alloc] initWithString:text];

    [attributedStringM addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:fontSize2] range:NSMakeRange(0, 3)];
    [attributedStringM addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(0, 3)];

    [attributedStringM addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:fontSize1] range:NSMakeRange(3, text.length - 6)];
    [attributedStringM addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:NSMakeRange(3, text.length - 6)];

    [attributedStringM addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:fontSize2] range:NSMakeRange(text.length - 3, 3)];
    [attributedStringM addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(text.length - 3, 3)];

    //不同大小的文字水平中部对齐(默认是底部对齐)
    [attributedStringM addAttribute:NSBaselineOffsetAttributeName value:@(fontRatio * (fontSize1 - fontSize2)) range:NSMakeRange(0, 3)];
    [attributedStringM addAttribute:NSBaselineOffsetAttributeName value:@(fontRatio * (fontSize1 - fontSize2)) range:NSMakeRange(text.length - 3, 3)];

    label.attributedText = attributedStringM;
    [self.view addSubview:label];
}

你可能感兴趣的:(2018-08-09 富文本 文字大小不同居中对齐)