1、给定字体大小和宽度,计算文本的显示高度
- (CGFloat)textHeightWithString:(NSString*)string Font:(UIFont*)font maxWidth:(CGFloat)width{
CGFloatheight =0;
do{
if(self.length<=0) {
break;
}
//字符串中的空格会影响换行的高度,填充空格后再计算
NSString *allStr = [string stringByReplacingOccurrencesOfString:@" " withString:@"a"];
NSDictionary *attribute = @{NSFontAttributeName:font};
CGRect retSize = [allStr boundingRectWithSize:CGSizeMake(width, MAXFLOAT) options:NSStringDrawingTruncatesLastVisibleLine |
NSStringDrawingUsesLineFragmentOrigin |
NSStringDrawingUsesFontLeading attributes:attribute context:nil];
height = retSize.size.height;
}while(0);
return ceil(height);
}
2、给定字体大小和高度,计算文本的显示宽度
- (CGFloat)textWidthWithString:(NSString*)string Font:(UIFont*)font maxHeight:(CGFloat)height{
CGFloatwidth =0;
do{
if(self.length<=0) {
break;
}
NSDictionary *attribute = @{NSFontAttributeName:font};
CGRect retSize = [string boundingRectWithSize:CGSizeMake(MAXFLOAT, height) options:NSStringDrawingTruncatesLastVisibleLine |
NSStringDrawingUsesLineFragmentOrigin |
NSStringDrawingUsesFontLeading attributes:attribute context:nil];
width = retSize.size.width;
}while(0);
return ceil(width);
}
3、给定字体大小、显示宽度、段落格式,计算文本的显示高度
- (CGFloat)textHeightWithString:(NSString*)string Font:(UIFont*)font maxWidth:(CGFloat)width paragraphStyle:(NSMutableParagraphStyle*)paragraphStyle{
CGFloatheight =0;
do{
if(self.length<=0) {
break;
}
//字符串中的空格会影响换行的高度,填充空格后再计算
NSString *allStr = [string stringByReplacingOccurrencesOfString:@" " withString:@"a"];
NSDictionary *attribute = @{NSFontAttributeName:font,NSParagraphStyleAttributeName:paragraphStyle};
CGRect retSize = [allStr boundingRectWithSize:CGSizeMake(width, MAXFLOAT) options:NSStringDrawingTruncatesLastVisibleLine |
NSStringDrawingUsesLineFragmentOrigin |
NSStringDrawingUsesFontLeading attributes:attribute context:nil];
height = retSize.size.height;
}while(0);
returnceil(height);
}
4、给定字体大小、最大显示宽高、截断方式,计算文本的显示
- (CGSize)textSizeWithString:(Nsstring *)string Font:(UIFont*)font maxSize:(CGSize)maxSize lineBreakMode:(NSLineBreakMode)lineBreakMode{
CGSize result = CGSizeZero;
do{
if(self.length<=0) {
break;
}
NSMutableParagraphStyle *style = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
[stylesetLineBreakMode:lineBreakMode];
NSDictionary *attribute = @{NSFontAttributeName: font, NSParagraphStyleAttributeName: style};
CGRect retSize = [string boundingRectWithSize:CGSizeMake(maxSize.width, maxSize.height) options:NSStringDrawingTruncatesLastVisibleLine | NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:attribute context:nil];
result =CGSizeMake(CGRectGetWidth(retSize),CGRectGetHeight(retSize));
}while(0);
returnresult;
}