In case Flash no longer exists; a copy of this site is included in the Flashpoint archive's "ultimate" collection.

Dead Code Preservation :: Archived AS3 works from wonderfl.net

adjustFontSizeToFitHeight

Get Adobe Flash player
by jw.wsod 30 Dec 2013
    Embed
/**
 * Copyright jw.wsod ( http://wonderfl.net/user/jw.wsod )
 * MIT License ( http://www.opensource.org/licenses/mit-license.php )
 * Downloaded from: http://wonderfl.net/c/vv27
 */

package {
    import flash.text.TextFieldType;
    import flash.text.TextFormat;
    import flash.text.TextField;
    import flash.display.Sprite;
    public class FlashTest extends Sprite {

        public var tf:TextField = new TextField();
        public function FlashTest() {
            // write as3 code here..
            tf.width = 150;
            tf.height = 100;
            tf.wordWrap = true;
            tf.border = true;
            tf.multiline = true;
            tf.type = TextFieldType.INPUT;
            tf.text = " Hello. This should be more than enough text to test my function. ";
            var fmt:TextFormat = tf.getTextFormat();
            fmt.size = 30;
            tf.setTextFormat(fmt);
            addChild(tf);
            adjustFontSizeToFitHeight(tf);
            var txt:String = tf.text;
            trim(tf, txt);
        }
        public static function adjustFontSizeToFitHeight(textObj:TextField, minFontSize:int = 10):void{
            var fmt:TextFormat = textObj.getTextFormat();
            var tHeight:Number = textObj.height;
            var loopMax:int = 30;
            if (tHeight > textObj.textHeight+5) return; 
            while (tHeight < textObj.textHeight+5 && fmt.size >= minFontSize && loopMax > 0) {
                fmt.size = Number(fmt.size) - 1;
                textObj.setTextFormat(fmt);
                textObj.defaultTextFormat = fmt;
                loopMax --;
            }
        }
        public static function trim(tf:TextField, tString:String):String{
            var loopMax:Number = 30;
            var char_array:Array = tString.split("");
            while(char_array[0] == " " && loopMax > 0){
                char_array.shift();
                loopMax--;
            }
            loopMax = 30;
            while(char_array[char_array.length-1] == " " && loopMax > 0){
                char_array.pop();
                loopMax--;
            }
            tf.text = char_array.join("");
            return char_array.join();
        }
    }
}