iOS踩过的坑之富文本计算文字高度

在设置了label中文字的字间距、行间距、段间距后,获取label总的高度,尝试了各种计算方法,最后只发现一种方式是有效的。

    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSNumber  *fontSize = [defaults objectForKey:@"DetailContentFont"];
    if (!fontSize) fontSize = @16;
    NSMutableParagraphStyle *npgStyle = [[NSMutableParagraphStyle alloc] init];
    npgStyle.alignment = NSTextAlignmentJustified;
    npgStyle.paragraphSpacing = 16; // 段与段的距离
    npgStyle.lineSpacing = 16;
    NSDictionary *attr = @{NSFontAttributeName:[UIFont systemFontOfSize:[fontSize integerValue]],NSForegroundColorAttributeName:[UIColor darkGrayColor],NSParagraphStyleAttributeName:npgStyle};
    CGSize size = CGSizeMake(CYBMacros.kScreenWidth-36*CYBMacros.kWidthScale, CGFLOAT_MAX);
    NSString *displayStr = [self.detailInfoModel.content stringByAppendingString:@"\n"];
    CGFloat height = [displayStr boundingRectWithSize:size
                                                     options:\
    NSStringDrawingTruncatesLastVisibleLine |
    NSStringDrawingUsesLineFragmentOrigin |
    NSStringDrawingUsesFontLeading
    attributes:attr context:nil].size.height;
            
    DebugLog(@"计算的文字高度=%.2f", height)
    return height;

每次使用原字符串内容计算完高度时,最后一行都无法显示,

解决方案

在文章末尾添加一个换行符,然后再计算总高度。

其中,options的枚举值说明:

typedef NS_OPTIONS(NSInteger, NSStringDrawingOptions) {
        
        NSStringDrawingUsesLineFragmentOrigin = 1 << 0,
        // 整个文本将以每行组成的矩形为单位计算整个文本的尺寸
        // The specified origin is the line fragment origin, not the base line origin
        
        NSStringDrawingUsesFontLeading = 1 << 1,
        // 使用字体的行间距来计算文本占用的范围,即每一行的底部到下一行的底部的距离计算
        // Uses the font leading for calculating line heights
        
        NSStringDrawingUsesDeviceMetrics = 1 << 3,
        // 将文字以图像符号计算文本占用范围,而不是以字符计算。也即是以每一个字体所占用的空间来计算文本范围
        // Uses image glyph bounds instead of typographic bounds
        
        NSStringDrawingTruncatesLastVisibleLine
        // 当文本不能适合的放进指定的边界之内,则自动在最后一行添加省略符号。如果NSStringDrawingUsesLineFragmentOrigin没有设置,则该选项不生效
        // Truncates and adds the ellipsis character to the last visible line if the text doesn't fit into the bounds specified. Ignored if NSStringDrawingUsesLineFragmentOrigin is not also set.
        
    }

你可能感兴趣的:(iOS踩过的坑之富文本计算文字高度)