【转】Actionscript 倒计时组件

来自ComingX:http://www.comingx.com/?p=1783

 

/**
 * ComingX.com
 * Copyright 2012. All rights reserved.
 *
 * @Author: Jingle
 * @Email: jingdongemail#gmail.com
 * @Created date: 2012-2-6
 */
package com.jingle.view.component
{
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.TimerEvent;
	import flash.text.TextLineMetrics;
	import flash.utils.Timer;
	import mx.controls.Label;
	import mx.core.UIComponent;
 
	[Event(name="timeUp", type="flash.events.Event")]
	public class TimeCounter extends UIComponent
	{
		private var timer:Timer;
		private var timeLabel:Label;
		/**
		 * 剩余时间,毫秒单位 
		 */		
		private var leftTime:Number;
 
		/**
		 * 时间到之后显示替代文本 
		 */		
		private static const TIME_UP:String = "时间到";
 
		/**
		 * 结束时间,毫秒单位
		 */
		private var _endTime:Number;
 
		/**
		 * 字体大小 
		 */		
		public var fontSize:Number = 20;
		/**
		 * 字体颜色 
		 */		
		public var fontColor:uint = 0x000000;
 
		public function TimeCounter()
		{
			super();
			timer = new Timer(1000);
			timer.addEventListener(TimerEvent.TIMER,onTimer);
 
		}
 
		public function get endTime():Number{
			return this._endTime;
		}
 
		public function set endTime(value:Number):void
		{
			if(value != this._endTime && value)
			{
				_endTime = value;
				var timeNow:Number = (new Date()).getTime();
				leftTime = _endTime - timeNow;
				timer.stop();
				timer.reset();
				timer.start();
			}
		}
 
		override protected function createChildren():void
		{
			if(!timeLabel)
			{
				timeLabel = new Label();
				addChild(timeLabel);
				this.setStyle("fontSize",fontSize);
				this.setStyle("color",fontColor);
				var lineMatrics:TextLineMetrics = measureText("00 : 00 : 00");
				timeLabel.width = lineMatrics.width + 10;
				timeLabel.height = lineMatrics.height + 4;
				timeLabel.setStyle("textAlign","center");
				timeLabel.setStyle("verticalAlign","middle");
			}
 
		}
 
		protected function onTimer(evt:TimerEvent):void
		{
			leftTime = leftTime - 1000;
			if(leftTime <= 0)
			{
				//到时间了
				timer.stop();
				dispatchEvent(new Event("timeUp"));
			}
			updateTimeLabel();
		}
 
		protected function updateTimeLabel():void
		{
			if(leftTime <= 0)
			{
				timeLabel.text = TimeCounter.TIME_UP;
				return;
			}
			var h:Number = Math.floor(leftTime / (1000 * 60 * 60) );
			var m:Number = Math.floor(leftTime % (1000 * 60 * 60) / (1000 * 60));
			var s:Number = Math.floor(leftTime % (1000 * 60) / 1000);
 
 
			timeLabel.text = oneToTow(h) + " : " + oneToTow(m) + " : " + oneToTow(s);
		}
 
		private function oneToTow(value:Number):String
		{
			var str:String;
			if(value < 10)
			{
				str = "0" + value;
			}
			else
			{
				str = "" + value;
			}
			return str;
 
		}
	}
}

 使用方法:

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

 

posted @ 2012-03-24 19:49  简道云  阅读(394)  评论(0编辑  收藏  举报