public function ShowTimer(){
stage.scaleMode = StageScaleMode.NO_SCALE;
stage.align = StageAlign.TOP_LEFT;
initMc();
}
AS3裡新加了很多的常量來代替字串。這給我們帶來了很大的方便。比如要限制影片的縮放模式為固定尺寸,AS2時的代碼為
Stage.scaleMode = "noScale";
值是一個字串,在輸入的時候是沒有代碼提示的,很容易輸錯(我經常是到協助文檔裡把字串複製過來)。而在AS3裡的代碼為:
stage.scaleMode = StageScaleMode.NO_SCALE;
原來的字串 “noScale” 由常量 StageScaleMode.NO_SCALE 代替。這樣可以使用代碼提示自動完成,有效避免了因為輸錯而造成的程式bug(而且很方便 )。同樣的字串常量還有一些事件類型比如 MouseEvent.CLICK 代替”click” 等等。
複製代碼 代碼如下:private function initMc():void{
showTxt = new TextField();
addShow(showTxt,10,10,310,20);
addLabel(setDelayLabel,10,40,"delay:");
//...other code
}
添加文字框和按鈕。注意,需要再次引用的文字框必須顯式初始化,否則在其他地方引用此變數將返回 null 。
複製代碼 代碼如下:private function addLabel(txt:TextField,x:uint,y:uint,text:String):void{
txt = new TextField();
txt.x = x;
txt.y = y;
txt.text = text;
addChild(txt);
}
AS3裡所有的東西都是 new 出來的。僅僅 new 出來還不行,必須使用 addChild() 把它添加到顯示列表裡。
複製代碼 代碼如下:private function addBtn(mc:Sprite,...,clickHanlder:Function):void{
mc.mouseChildren = false;
mc.graphics.beginFill(0x000000,0.3);
mc.graphics.drawRect(0,0,w,h);
mc.buttonMode = true;
mc.addEventListener(MouseEvent.CLICK,clickHanlder);
addChild(mc);
//
txt = new TextField();
txt.name = "btnText";
mc.addChild(txt);
}
在AS3裡想要 mc 成為一個按鈕必須設定:
mc.buttonMode = true;
這時看到滑鼠經過mc時並沒有變成手形,原因在最後一行,把 txt 添加到了 mc 裡用來顯示按鈕文字,以致滑鼠事件的目標對象為txt而不是期望的mc。為瞭解決這個問題需要加上一句:
mc.mouseChildren = false;
以保證mc為滑鼠事件的目標對象(target objects)。
AS3裡所有的可見對象都是DisplayObject的子類,而DisplayObject是EventDispatcher的子類
Sprite → DisplayObjectContainer → InteractiveObject → DisplayObject → EventDispatcher → Object
也就是說所有的可見對象都可以直接addEventListener。
mc.addEventListener(MouseEvent.CLICK,clickHanlder);
這裡用常量 MouseEvent.CLICK 代替了事件類型 “click” 。此類常量以後不再贅述。
mc.graphics.beginFill(0x000000,0.3);
mc.graphics.drawRect(0,0,w,h);
AS3裡所有的繪圖方法都放在了 Graphics 裡。Sprite的graphics屬性就是一個Graphics。除了基本的 beginFill ,beginBitmapFill 之類,又增加了新的 drawCircle 、drawEllipse、drawRect 等方法,再也不用沒完沒了地 moveTo 、lineTo 了。
public function startTimer(event:MouseEvent):void{
//...code here
}
下面是主要的內容了:Timer。
var delay:uint = setDelayTxt.text;
var repeatCount:uint = setRepeatCountTxt.text;
if(timer == null){
timer = new Timer(delay,repeatCount);
}
uint是AS3新加的資料類型,表示32位的正整數(int 表示32位有符號的整數)。Timer的建構函式接受兩個參數,delay 是 “timer” 事件延遲的毫秒數,repeatCount 是迴圈的次數,預設為0,即一直迴圈下去直到 stop 或者 reset 。
timer.addEventListener(TimerEvent.TIMER,timerHandler);
timer.addEventListener(TimerEvent.TIMER_COMPLETE,timerCompleteHandler);
timer廣播兩個事件,每隔 delay 指定的毫秒廣播一次 “timer” 事件,迴圈repeatCount次之後廣播 “timerComplete” 事件。
timer.start();
startBtn.getChildByName("btnText").text = " stop ";
timer 在 start 之後開始執行,此時 running 屬性為 true 。把 startBtn 設定為 “stop”,注意AS3是拿不到startBtn的child的,因為 Sprite 不是動態類,無法聲明它的child。這時候想要拿到startBtn內的文字框就要使用 getChildByName 方法。當然要先給child一個name:
//function addBtn
txt.name = "btnText";
最後是 stop 和 reset 的區別:reset 在 stop 之後把 currentCount 屬性設為 0 。可以通過 最後編譯的swf 體會一下。
fla檔案下載Flash動畫線上播放