12/16/2014

What Colour Is It? in AS3

Reproducing What Colour Is It?. Pretty simple...



Basically, it takes the current time, interpret it as a hex color, and then changes the background to that color. Some things to note in this code:

  • texts have blendMode set to Invert so it'll always be visible no matter the background color.
  • I did not bother with text fonts/size/etc, mostly just used default.
  • A Timer is used because it just needs to update every second
  • pad function is useful in many other occasions too
  • Date class provides current date and time.
  • no extra Sprite is needed for background color. Just draw in the graphics of this class - graphics will always be behind any children display objects.

import flash.text.TextField; import flash.utils.Timer; import flash.events.TimerEvent; import flash.display.BlendMode; import flash.text.TextFieldAutoSize; // declare variables var sw:int = stage.stageWidth; // because we'll use it a few times var sh:int = stage.stageHeight; var timer:Timer = new Timer(1000); var txt_time:TextField = new TextField(); var txt_hex:TextField = new TextField(); // set blend mode and center align text txt_hex.blendMode = txt_time.blendMode=BlendMode.INVERT; txt_hex.autoSize = txt_time.autoSize=TextFieldAutoSize.CENTER; txt_hex.text = "#000000"; txt_time.text = "00 : 00 : 00"; // position text fields txt_time.x = (sw-txt_time.width)/2; txt_time.y = (sh-txt_time.height)/2; txt_hex.x = (sw-txt_hex.width)/2; txt_hex.y = sh-txt_hex.height; addChild(txt_time); addChild(txt_hex); // set timer timer.addEventListener(TimerEvent.TIMER,timerFunc); timer.start(); // timer function function timerFunc(e:TimerEvent):void{ var now:Date = new Date(); var h:String = pad(now.hours,2,"0"); var m:String = pad(now.minutes,2,"0"); var s:String = pad(now.seconds,2,"0"); txt_time.text = h+" : "+m+" : "+s; txt_hex.text = "#"+h+m+s; this.graphics.clear(); this.graphics.beginFill(int("0x"+h+m+s)); this.graphics.drawRect(0,0,sw,sh); } // padding function function pad(n:int,len:int,wit:String):String{ var ret:String = String(n); while(ret.length<len){ ret = wit+ret; } return ret; }

No comments:

Post a Comment