Actionscript 倒计时组件

  1 /**
2 * ComingX.com
3 * Copyright 2012. All rights reserved.
4 *
5 * @Author: Jingle
6 * @Email: jingdongemail#gmail.com
7 * @Created date: 2012-2-6
8 */
9 package com.jingle.view.component
10 {
11 import flash.display.Sprite;
12 import flash.events.Event;
13 import flash.events.TimerEvent;
14 import flash.text.TextLineMetrics;
15 import flash.utils.Timer;
16 import mx.controls.Label;
17 import mx.core.UIComponent;
18
19 [Event(name="timeUp", type="flash.events.Event")]
20 public class TimeCounter extends UIComponent
21 {
22 private var timer:Timer;
23 private var timeLabel:Label;
24 /**
25 * 剩余时间,毫秒单位
26 */
27 private var leftTime:Number;
28
29 /**
30 * 时间到之后显示替代文本
31 */
32 private static const TIME_UP:String = "时间到";
33
34 /**
35 * 结束时间,毫秒单位
36 */
37 private var _endTime:Number;
38
39 /**
40 * 字体大小
41 */
42 public var fontSize:Number = 20;
43 /**
44 * 字体颜色
45 */
46 public var fontColor:uint = 0x000000;
47
48 public function TimeCounter()
49 {
50 super();
51 timer = new Timer(1000);
52 timer.addEventListener(TimerEvent.TIMER,onTimer);
53
54 }
55
56 public function get endTime():Number{
57 return this._endTime;
58 }
59
60 public function set endTime(value:Number):void
61 {
62 if(value != this._endTime && value)
63 {
64 _endTime = value;
65 var timeNow:Number = (new Date()).getTime();
66 leftTime = _endTime - timeNow;
67 timer.stop();
68 timer.reset();
69 timer.start();
70 }
71 }
72
73 override protected function createChildren():void
74 {
75 if(!timeLabel)
76 {
77 timeLabel = new Label();
78 addChild(timeLabel);
79 this.setStyle("fontSize",fontSize);
80 this.setStyle("color",fontColor);
81 var lineMatrics:TextLineMetrics = measureText("00 : 00 : 00");
82 timeLabel.width = lineMatrics.width + 10;
83 timeLabel.height = lineMatrics.height + 4;
84 timeLabel.setStyle("textAlign","center");
85 timeLabel.setStyle("verticalAlign","middle");
86 }
87
88 timer.start();
89 }
90
91 protected function onTimer(evt:TimerEvent):void
92 {
93 leftTime = leftTime - 1000;
94 if(leftTime <= 0)
95 {
96 //到时间了
97 timer.stop();
98 dispatchEvent(new Event("timeUp"));
99 }
100 updateTimeLabel();
101 }
102
103 protected function updateTimeLabel():void
104 {
105 if(leftTime <= 0)
106 {
107 timeLabel.text = TimeCounter.TIME_UP;
108 return;
109 }
110 var h:Number = Math.floor(leftTime / (1000 * 60 * 60) );
111 var m:Number = Math.floor(leftTime % (1000 * 60 * 60) / (1000 * 60));
112 var s:Number = Math.floor(leftTime % (1000 * 60) / 1000);
113
114
115 timeLabel.text = oneToTow(h) + " : " + oneToTow(m) + " : " + oneToTow(s);
116 }
117
118 private function oneToTow(value:Number):String
119 {
120 var str:String;
121 if(value < 10)
122 {
123 str = "0" + value;
124 }
125 else
126 {
127 str = "" + value;
128 }
129 return str;
130
131 }
132 }
133 }

使用方法

<component:TimeCounter endTime="{model.deadline}" fontSize="30" timeUp="timeUpHandler(event)" />


博文链接

posted @ 2012-02-07 11:51  JingleHIT  阅读(868)  评论(0编辑  收藏  举报