计算最大的字体大小,适合一个矩形?

我试图find最大的字体大小,将适合给定的矩形给定的string。 该algorithm的目标是尽可能多地填充尽可能大的字体。 我的方法 – 从我在网上find的方法中进行修改 – 做的是公平的工作,但往往不能满足整个scheme。 我很想看看如何改进这个algorithm,以便每个人都可以从中受益:

-(float) maxFontSizeThatFitsForString:(NSString*)_string inRect:(CGRect)rect withFont:(NSString *)fontName onDevice:(int)device { // this is the maximum size font that will fit on the device float _fontSize = maxFontSize; float widthTweak; // how much to change the font each iteration. smaller // numbers will come closer to an exact match at the // expense of increasing the number of iterations. float fontDelta = 2.0; // sometimes sizeWithFont will break up a word // if the tweak is not applied. also note that // this should probably take into account the // font being used -- some fonts work better // than others using sizeWithFont. if(device == IPAD) widthTweak = 0.2; else widthTweak = 0.2; CGSize tallerSize = CGSizeMake(rect.size.width-(rect.size.width*widthTweak), 100000); CGSize stringSize = [_string sizeWithFont:[UIFont fontWithName:fontName size:_fontSize] constrainedToSize:tallerSize]; while (stringSize.height >= rect.size.height) { _fontSize -= fontDelta; stringSize = [_string sizeWithFont:[UIFont fontWithName:fontName size:_fontSize] constrainedToSize:tallerSize]; } return _fontSize; } 

对于给定的矩形和string,使用以下方法计算可以适合的字体。

您可以将字体更改为所需的字体。 另外,如果需要,你可以添加一个默认的字体高度;

方法是自我解释。

 -(UIFont*) getFontTofitInRect:(CGRect) rect forText:(NSString*) text { CGFloat baseFont=0; UIFont *myFont=[UIFont systemFontOfSize:baseFont]; CGSize fSize=[text sizeWithFont:myFont]; CGFloat step=0.1f; BOOL stop=NO; CGFloat previousH; while (!stop) { myFont=[UIFont systemFontOfSize:baseFont+step ]; fSize=[text sizeWithFont:myFont constrainedToSize:rect.size lineBreakMode:UILineBreakModeWordWrap]; if(fSize.height+myFont.lineHeight>rect.size.height){ myFont=[UIFont systemFontOfSize:previousH]; fSize=CGSizeMake(fSize.width, previousH); stop=YES; }else { previousH=baseFont+step; } step++; } return myFont; } 

没有必要浪费时间做循环。 首先,在最大和最小字体点设置处测量文本宽度和高度。 取决于哪一个更严格,宽度或高度,使用以下math:

如果宽度更加限制(即, maxPointWidth / rectWidth > maxPointHeight / rectHeight ),请使用:

 pointSize = minPointSize + rectWidth * [(maxPointSize - minPointSize) / (maxPointWidth - minPointWidth)] 

否则,如果身高更限制使用:

 pointSize = minPointSize + rectHeight * [(maxPointSize - minPointSize) / (maxPointHeight - minPointHeight)] 

完全填充矩形可能是不可能的。

说一定的字体大小,你有两行文字,既水平填充屏幕,但垂直,你有几乎,但不是三行的空间。

如果只增加一点字体大小,那么线条就不再适合了,所以你需要三条线,但是三条线不能垂直放置。

所以你别无select,只能与垂直差距生活在一起。