All pastes #2103786 Raw Edit

Someone

public text v1 · immutable
#2103786 ·published 2012-01-18 12:56 UTC
rendered paste body
public function adjustTextSize (o) {

  var j,k,v;
  
  var st:TextField = new TextField();
  st.type = TextFieldType.DYNAMIC;
  st.embedFonts = true;
  st.multiline = true;
  st.wordWrap = true;
  st.width = o.width; // the width of the fixed-size box we're fitting text into
  st.height = o.height; // and its height
  st.text = o.text;
  
  j = k = 256; // max size
  v = Math.floor(k/2);

  var tft:TextFormat = new TextFormat(usable_font_name, j, 0xFFFFFF);
  tft.align = "center";

  var vc = 0;
  
  while (true) {
    tft.size = j;
    st.setTextFormat(tft);
   
    if (st.textHeight > o.height-8) { // too big. subtract. (minus 8 because flash is a horrible horrible thing)
      j = j-v;
    } else { // not big enough. add
      k = j;
      j = j+v;
    }
    v = v/2;
    if (v <= 1) {
      vc++;
      if (vc >= 5) { // when 5, gets us to a size around +/- 0.03 of the optimal
        break;
      }
    }
  }
  
  if (k<12) {
    k = 12;
  }
  if (k>127) {
    k = 127;
  }
  o.size = k;
}