Note that there are some explanatory texts on larger screens.

plurals
  1. POCalculate max font size that fits in a rect?
    primarykey
    data
    text
    <p>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 large of a font as possible. My approach -- which is modified from one I found online -- does a fair job, but it often doesn't fill the entire rect. I'd love to see some collaboration on how to improve this algorithm so that everyone might benefit from it:</p> <pre><code>-(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 &gt;= rect.size.height) { _fontSize -= fontDelta; stringSize = [_string sizeWithFont:[UIFont fontWithName:fontName size:_fontSize] constrainedToSize:tallerSize]; } return _fontSize; } </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload