as3中Timer类――Timer与时钟实例

作者:袖梨 2022-06-28

范例1:
没有哪个例子比一个时钟更加适合描述Timer类的基本应用。
步骤一:
flash舞台上放置一个钟面,再新建层画出时针、分针、秒针和轴心。3个指针分别命名为

hourPoint,minutePoint,secondPoint。这些指针的注册点在底部中央。如图:

下面我们来让它运转起来:
在属性面板中输入Clock。新建一个文档类Clock.as。代码如下:
代码:

代码如下 复制代码
[code]
package
{
import flash.display.Sprite;
import flash.display.MovieClip;
import flash.utils.Timer;
import flash.events.TimerEvent;
public class Clock extends Sprite
{
var clockTimer:Timer=new Timer(1000,0);
var bellSound:Bell=new Bell();
public function Clock()
{
refreshPoint(); //初始化指针
clockTimer.start(); //开始运行计时器
clockTimer.addEventListener(TimerEvent.TIMER,timerFunction); //添加事件
}

private function timerFunction(evtObj:TimerEvent):void
{
refreshPoint();
}

private function refreshPoint():void
{
var currentDate:Date=new Date();
//秒针每走一格旋转6度。
secondPoint.rotation=currentDate.seconds*6;
//分针每走一个旋转6度加上秒针对它的增量
minutePoint.rotation=currentDate.minutes*6+currentDate.seconds*6/60;
//使用取余数的方法把24小时制转化为12小时制,时针每走一格旋转30度加上分针对它的增量
var hour12:int=currentDate.hours%12;
hourPoint.rotation=hour12*30+currentDate.minutes*30/60;

//整点报时功能
if(currentDate.minutes==0 && currentDate.seconds==0)
{
if(hour12)
{
bellSound.play(0,hour12);
}
else
{
bellSound.play(0,12); //0点时敲12下
}
}
}
}
}

上述代码有两点需要阐明:
一、Date类是24小时制的,而时钟是12小时制的,转化的方法是取余数。currentDate.hours%12。
二、0点代表12点。当到达0点时要敲12下而不是0下。

相关文章

精彩推荐