I\'m attempting to find the maximum font size that will fit in a given rect for a given string. The goal of the algorithm is to fill as much of the rect as possible with as
There is no need to waste time doing loops. First, measure the text width and height at the max and min font point settings. Depending on whichever is more restrictive, width or height, use the following math:
If width is more restrictive (i.e., maxPointWidth / rectWidth > maxPointHeight / rectHeight
) use:
pointSize = minPointSize + rectWidth * [(maxPointSize - minPointSize) / (maxPointWidth - minPointWidth)]
Else, if height is more restrictive use:
pointSize = minPointSize + rectHeight * [(maxPointSize - minPointSize) / (maxPointHeight - minPointHeight)]
Use the following method to calculate the font which can fit, for a given rect and string.
You can change the font to the one which you require. Also, If required you can add a default font height;
Method is self explanatory.
-(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;
}
It may be impossible to fill a rectangle completely.
Say at a certain font size you have two lines of text, both filling the screen horizontally, but vertically you have almost but not quite three lines of space.
If you increase the font size just a tiny bit, then the lines don't fit anymore, so you need three lines, but three lines don't fit vertically.
So you have no choice but to live with the vertical gap.