iOS文字高度计算

1,017 阅读1分钟

NSString有一个计算高度的方法

- (CGRect)boundingRectWithSize:(CGSize)size options:(NSStringDrawingOptions)options attributes:(nullable NSDictionary<NSAttributedStringKey, id> *)attributes context:(nullable NSStringDrawingContext *)context NS_AVAILABLE(10_11, 7_0);

其中NSStringDrawingOptions

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 NS_ENUM_AVAILABLE(10_5, 6_0) = 1 << 5, // 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.

} NS_ENUM_AVAILABLE(10_0, 6_0);


  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.