天天看点

boundingRectWithSize:options:attributes:context:

在ios6.0以前,我们计算label中text所占size的大小是用以下方法:

- (CGSize)sizeWithFont:(UIFont *)font constrainedToSize:(CGSize)size lineBreakMode:(NSLineBreakMode)lineBreakMode
           

但是在ios7.0以后此方法被苹果弃用,下面这个方法是现在使用的:

- (CGRect)boundingRectWithSize:(CGSize)size
                       options:(NSStringDrawingOptions)options
                       context:(NSStringDrawingContext *)context
           

查看文档中定义如下:

Availability
Available in iOS 6.0 and later.

Discussion
You can use this method to compute the space required to draw the string. The constraints you specify in the size parameter are a guide for the renderer for how to size the string. However, the actual bounding rectangle returned by this method can be larger than the constraints if additional space is needed to render the entire string. Typically, the renderer preserves the width constraint and adjusts the height constraint as needed.

In iOS 7 and later, this method returns fractional sizes (in the size component of the returned CGRect); to use a returned size to size views, you must use raise its value to the nearest higher integer using the ceil function.
           

此方法ios6.0及之后版本系统可用。你可以使用此方法计算string所需空间。在ios7.0及以后版本中,此方法返回的是小数。使用的时候必须使用ceil方法取不小于他的最小整数。

下面是使用方法:(我的需求是计算label中显示一段文字所需size)

NSString *content = @"这是一个测试,大家可以试试,用来计算一段文字所占空间(高度和宽度)";
    NSStringDrawingOptions options = NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading;
    NSAttributedString *attributedStr = [[NSAttributedString alloc] initWithString:content attributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:13.0],NSFontAttributeName,[UIColor blackColor],NSForegroundColorAttributeName, nil]];
    CGRect rect = [attributedStr boundingRectWithSize:CGSizeMake(300, 400) options:options context:nil];
    CGFloat width = ceil(rect.size.width);
    CGFloat height = ceil(rect.size.height);