iOS计算文本高度

5th,Nov,2016

简介

iOS7.0以前使用-sizeWithFont: constrainedToSize: lineBreakMode计算高度,iOS7.0以后通过-boundingRectWithSize:options:attributes:contenxt计算高度

boundingRectWithSize

// NOTE: All of the following methods will default to drawing on a baseline, limiting drawing to a single line.
// To correctly draw and size multi-line text, pass NSStringDrawingUsesLineFragmentOrigin in the options parameter.
@interface NSString (NSExtendedStringDrawing)
- (CGRect)boundingRectWithSize:(CGSize)size options:(NSStringDrawingOptions)options attributes:(nullable NSDictionary *)attributes context:(nullable NSStringDrawingContext *)context NS_AVAILABLE(10_11, 7_0);
@end

size

描述文本绘制区域的宽高,如textView,获取textView的宽-padding(8)*2,以及textView的高.

options:

API文档中有指出该方法默认是在单行文本基线绘制,如要在多行文本上绘制,则需使用NSStringDrawingUsesLineFragmentOrigin。以下为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: 多行文本使用该参数。
NSStringDrawingUsesFontLeading: 使用行距计算行高(行距=行间距+字体高度)
NSStringDrawingUsesDeviceMetrics:计算高度时使用图元字形而不是印刷字形
NSStringDrawingTruncatesLastVisibleLine: 文本内容超过可绘制区域,则会截去超出文本添加省略号到文本末尾

attributes

一些属性,比如文本的font等。
demo:

[NSDictionary dictionaryWithObjectsAndKeys:textView.font,NSFontAttributeName, nil]

context

绘制上下文,可为nil。

Demo

+ (float)heightForTextView:(UITextView *)textView {
    float fPadding = 8.0;
    CGSize constraint = CGSizeMake(textView.contentSize.width - fPadding*2 - 30*2, MAXFLOAT);
    CGRect rect = [textView.text boundingRectWithSize:constraint options:NSStringDrawingUsesLineFragmentOrigin attributes:[NSDictionary dictionaryWithObjectsAndKeys:textView.font,NSFontAttributeName, nil] context:nil];
    float fHeight = rect.size.height + 16.0;
    return fHeight;
}

// iOS7以前,deprecated
- (void)height {
    CGSize size = [strText sizeWithFont: textView.font constrainedToSize:constraint lineBreakMode:UILineBreakModeWordWrap];
    CGFloat height = size.height;
}

参考资料

IOS动态获取文本的高度–自适应文本宽度、高度Textview
TextKit学习(四)通过boundingRectWithSize:options:attributes:context:计算文本尺寸

你可能感兴趣的:(iOS实战录)