AS3 Simple Color Code Converter

I just finished writing my first AS3 application. Part of its functionality allowed a color code to be passed in as a variable. The problem I ran into was that the color code was being passed by web developers. Instead of “0xFFCC00″ they would pass “#FFCC00″. Understandable mistake, but garbage to Flash, so the custom color would never be applied.

Rather than require the RGB code to be passed in, I wrote a short function to check for the HTML Hex format and convert it if necessary. It uses a regular expression to delete any occurrence of ‘#’ and it adds “0x” to the beginning of the color code if it doesn’t already exist.

To see how it works, paste the following code into a blank Flash document and preview it:

//Create a text field and populate it
var myTextField:TextField = new TextField();
myTextField.text = "Hello World";
addChild(myTextField);

//Convert incorrectly formatted color string
var passedColor:String = "#FFCC00";
var newColor:String = fixColorCode(passedColor);
trace(newColor); //0xFFCC00 will be returned

//change color
var newFormat:TextFormat = new TextFormat();
newFormat.color = newColor;
myTextField.setTextFormat(newFormat);

function fixColorCode($color:String) :String
{
   var submittedColor:String = $color;
   var validColor:String;
   var pattern:RegExp = /#/;

   submittedColor = $color.replace(pattern,"");

   pattern = /0x/;
   if (submittedColor.substring(0,2) != "0x") {
      validColor = "0x"+submittedColor;
   } else {
      validColor = submittedColor;
   }

   return validColor;

}
as3, flash, quickTip

If you enjoyed this post, please consider to leave a comment or subscribe to the feed and get future articles delivered to your feed reader.

Comments

8 Responses to “AS3 Simple Color Code Converter”

Leave Comment

(required)

(required)