2010-11-03 11 views
7

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; 
} 
+0

Cuando dices "llenar el rect completo" ¿solo quieres decir en horizontal? – Magnus

Respuesta

4

utilizar el siguiente método para calcular el tipo de letra que puede caber, por un rect y cadena dada.

Puede cambiar la fuente a la que necesite. Además, si es necesario, puede agregar una altura de fuente predeterminada;

El método se explica por sí mismo.

-(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; 

} 
0

No hay necesidad de perder el tiempo haciendo bucles. En primer lugar, mida el ancho y el alto del texto en las configuraciones de punto de fuente máximo y mínimo. Dependiendo de lo que sea más restrictiva, anchura o altura, utilice el siguiente matemáticas:

Si la anchura es más restrictiva (es decir, maxPointWidth/rectWidth > maxPointHeight/rectHeight) Uso:

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

Else, si la altura es el uso más restrictiva:

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

Puede ser imposible llenar un rectángulo por completo.

Digamos que en un determinado tamaño de fuente tiene dos líneas de texto, ambas llenando la pantalla horizontalmente, pero verticalmente tiene casi tres líneas de espacio.

Si aumenta un poco el tamaño de la fuente, las líneas ya no caben, por lo que necesita tres líneas, pero tres líneas no se ajustan verticalmente.

Así que no tiene más remedio que vivir con la brecha vertical.

Cuestiones relacionadas