Sto tentando di trovare la dimensione massima del carattere che si adatta a un dato retto per una determinata stringa. L'obiettivo dell'algoritmo è riempire il più possibile il più possibile con un font il più grande possibile. Il mio approccio - che è stato modificato da quello che ho trovato online - fa un buon lavoro, ma spesso non riempie l'intero rect. Mi piacerebbe vedere un po 'di collaborazione su come migliorare questo algoritmo in modo che ognuno possa trarre beneficio da esso:Calcola la dimensione massima del carattere che si adatta a 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;
}
Quando si dice "riempi l'intero retto" si intende solo sull'orizzontale? – Magnus