转载自:http://blog.sojingle.net/
最近在Cocoa学习中遇到一个小问题,就是在一个特定宽度的框中显示几个文字,需要根据宽度来计算字体的大小。后找到方法如下:
NSString有这样一个方法
sizeWithFont:minFontSize:actualFontSize:forWidth:lineBreakMode:
Returns the size of the string if it were rendered with the specified constraints, including a variable font size, on a single line.
原型为:
1
2
3
4
5
|
- (CGSize)sizeWithFont:(UIFont *)font
minFontSize:(CGFloat)minFontSize
actualFontSize:(CGFloat *)actualFontSize
forWidth:(CGFloat)width
lineBreakMode:(UILineBreakMode)lineBreakMode
|
使用时,font指定字体和最大字体大小,minFontSize指定最小字体,actualFontSize传递实际大小的引用。width指定总宽度,lineBreakMode指定换行模式。
示例:
1
2
3
4
5
6
7
8
|
CGFloat fontSize;
NSString *testString = @"All hail Sakuya!";
UIFont *font = [UIFont systemFontOfSize:500];
[testString sizeWithFont:font
minFontSize:10.0f
actualFontSize:&fontSize
forWidth:(self.bounds.size.width)
lineBreakMode:UILineBreakModeMiddleTruncation];
|
这段代码计算在一个UIView中显示一个字符串时要用的字体大小。方法的返回值这里没有用上,有用的是这个fontSize。