NSString *str = @"计算字符串的宽度和高度";
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
[paragraphStyle setLineSpacing:4];//设置行间距
//最大宽度为300,最大高度为200
CGSize size = [str boundingRectWithSize:CGSizeMake(300, 200) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:15] ,NSParagraphStyleAttributeName:paragraphStyle} context:nil].size;

NSLog(@"宽度=%f,高度=%f",size.width,size.height);
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.
        
    }

 

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐