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

テキストのサイズを幅に合わせて変更する

bkzen先生に教わったのでメモメモ
/**
 * Copyright sakusan393 ( http://wonderfl.net/user/sakusan393 )
 * MIT License ( http://www.opensource.org/licenses/mit-license.php )
 * Downloaded from: http://wonderfl.net/c/izgM
 */

package 
{
    import flash.display.*;
    import flash.events.*;
    import flash.text.*;
    import flash.utils.*;

    public class TextSizeFitTest extends Sprite 
    {
        public function TextSizeFitTest() 
        {
            this.graphics.beginFill(0x339933, 0.5);
            this.graphics.drawRect(0, 0, 400, 10);
            
            var t:TextField = new TextField();
            var tf:TextFormat = new TextFormat("_ゴシック", 40, 0x339933, true);
            t.defaultTextFormat = tf;
            addChild(t);
            
            var timer:Timer = new Timer(200);
            timer.addEventListener(TimerEvent.TIMER, function():void { t.appendText("あ"); changeSize(t, tf); } );
            timer.start();
        }
        
        private function changeSize(t:TextField, tf:TextFormat, maxSize:int = 50,w:int = 400,h:int = 50):void
        {
            t.autoSize="left"
            for (; maxSize-- && t.width > w || t.height > h; ) tf.size = maxSize, t.setTextFormat(tf);
            t.x=w-t.width>>1,t.y=h-t.height>>1;    
        }
    }
}