Estoy intentando encontrar el tamaño de fuente máximo que cabe en un rect determinado para una cadena dada. El objetivo del algoritmo es llenar tanto de rect como sea posible con una fuente lo más grande posible. Mi enfoque, que se modifica de uno que encontré en línea, hace un buen trabajo, pero a menudo no llena el rect completo. Me gustaría ver algún tipo de colaboración sobre cómo mejorar este algoritmo para que cada uno puede beneficiarse de ella:Calcular el tamaño de fuente máximo que cabe en un rect?
-(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;
}
Cuando dices "llenar el rect completo" ¿solo quieres decir en horizontal? – Magnus