SimpleButtonソースサンプル

prokion2008-09-28

FlexフレームワークであるMXMLを捨ててActionScriptプロジェクトに切り替えて困るのは、手軽に使えるコンポーネント、コントロール等が使えなくなることです。特にボタンは非常に良く使われるので今回SimpleButton()から作成しました。TextField()を使い文字埋め込みの簡単なボタンをSimpleButtonクラスを拡張することで実装しました。

package {

  import flash.display.DisplayObject;
  import flash.display.Sprite;
  import flash.display.SimpleButton;
  import flash.text.TextField;
  import flash.text.TextFieldAutoSize;
  import flash.text.TextFormat;

  public class MindButtonLabel extends SimpleButton {

    private const wgap:Number = 5;            // 幅隙間
    private const upColor:uint   = 0xEBEBE9;  // 通常
    private const overColor:uint = 0xFFDD44;  // マウスが乗った
    private const downColor:uint = 0xFFEEAA;  // 押した時
    private const bdcolor:uint = 0x939A9D;    // 枠の色

    private const txtsize:uint = 10;          // テキストサイズ
    private var labeltxt:String;

    public var lw:Number;
    public var lh:Number;

    public function MindButtonLabel(mlabel:String) {
      labeltxt = mlabel;
      upState        = drawButton(upColor);
      downState      = drawButton(downColor);
      overState      = drawButton(overColor);
      hitTestState   = upState;
      useHandCursor  = true;
    }

    private function drawButton(color:uint):Sprite {
      var p:Sprite = new Sprite();
      // Text
      var txt:TextField = new TextField();
      txt.autoSize = TextFieldAutoSize.LEFT;
      var tf:TextFormat = new TextFormat();
      tf.size = txtsize;
      txt.defaultTextFormat = tf;
      txt.text = labeltxt;
      txt.x = wgap;
      p.addChild(txt);
      lw = txt.width + (wgap*2);
      lh = txt.height;
      // Button
      p.graphics.lineStyle(1, bdcolor);
      p.graphics.beginFill(color);
      p.graphics.drawRect(0, 0, lw, lh);
      p.graphics.endFill();
      return p;
    }
  }
}

ちょっとFlexのButtonコントロールに比べると見映え機能は劣るけど、とりあえずbuttonコントロールの代替になります。