Scale text to fit in textField; scale TextField to fit text.


/ Published in: ActionScript 3
Save to your folder(s)



Copy this code and paste it in your HTML
  1. import flash.text.TextField;
  2.  
  3. function scaleTextToFitInTextField( txt : TextField ):void
  4. {
  5. var f:TextFormat = txt.getTextFormat();
  6. f.size = ( txt.width > txt.height ) ? txt.width : txt.height;
  7. txt.setTextFormat( f );
  8.  
  9. while ( txt.textWidth > txt.width - 4 || txt.textHeight > txt.height - 6 )
  10. {
  11. f.size = int( f.size ) - 1;
  12. txt.setTextFormat( f );
  13. }
  14. }
  15.  
  16. function scaleTextFieldToFitText( txt : TextField ) : void
  17. {
  18. //the 4s take into account Flash's default padding.
  19. //If I omit them, edges of character get cut off.
  20. txt.width = txt.textWidth + 4;
  21. txt.height = txt.textHeight + 4;
  22. }
  23.  
  24.  
  25. //demo
  26. var tf : TextField = new TextField();
  27. addChild( tf );
  28. tf.border = true;
  29. tf.width = Math.random() * 400 + 30;
  30. tf.height = Math.random() * 400 + 30;
  31. tf.text = "hello there";
  32. scaleTextToFitInTextField( tf );
  33. scaleTextFieldToFitText( tf );

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.