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

TextField (Fix Width, Fit the height to the inner text)

Get Adobe Flash player
by octech 25 Sep 2009
/**
 * Copyright octech ( http://wonderfl.net/user/octech )
 * MIT License ( http://www.opensource.org/licenses/mit-license.php )
 * Downloaded from: http://wonderfl.net/c/7K0k
 */

package {
  import flash.display.Sprite;
  import flash.events.Event;
  import flash.events.TextEvent;
  import flash.filters.DropShadowFilter;
  import flash.text.TextField;
  import flash.text.TextFieldType;
  
  [SWF(backgroundColor="#ffffff", frameRate="25")]
  public class Main extends Sprite {
    public var  _textfield:TextField;
    
    public function Main():void {
      _textfield  = new TextField();
      _textfield.x    = 100;
      _textfield.y    = 10;
      _textfield.width  = 200;
      _textfield.type      = TextFieldType.INPUT;
      _textfield.multiline  = true;  // 複数行.
      _textfield.wordWrap    = true;  // 折り返し.
      _textfield.backgroundColor  = 0xffefd5;
      _textfield.background    = true;
      _textfield.filters  = [ new DropShadowFilter(4, 45, 0x000000, 0.5, 8, 8) ];
      addChild( _textfield );
      
      addEventListener( Event.ADDED_TO_STAGE, init );
      
      _textfield.addEventListener( Event.CHANGE, updateTextFieldHeight );
      // ↑でキャッチするイベントをTextEvent.TEXT_INPUTにすると、
      // 日本語入力時、BackSpace時に高さ変更処理がうまくできないみたい.
      //_textfield.addEventListener( TextEvent.TEXT_INPUT, updateTextFieldHeight );
    }
    
    private function init(e:Event = null):void {
      _textfield.text  = "文字の行数に合わせてテキストフィールドの高さを変えるテストです。"
        + "何か入力してみてください。> ";
      updateTextFieldHeight(null);
      
      // 行末にカーソル移動してswf起動時にフォーカスを持ってくる.
      // ※Wonderflじゃうまく動かないけど..
      var numString:int  = _textfield.text.length;
      _textfield.setSelection( numString, numString );
      stage.focus  = _textfield;
    }
    
    private function updateTextFieldHeight(e:Event) :void {
      _textfield.scrollV  = 1;
      _textfield.height  = _textfield.textHeight + 4;
    }
  }
}