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";

//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;

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;


9 thoughts on “AS3 Simple Color Code Converter

  1. Returning a uint would be much more useful. TextFormat.color accepts an object and converts to a uint internally, but this won’t be the case with all classes that require a color.

    function fixColorCode( color:Object, hasAlpha:Boolean = false ):unit
    if( color is String )
    var pattern:RegExp = /#/;

    color = uint( color.toString().replace( pattern,”0x” ) );
    else if( !( color is Number ) )
    color = Number( color );

    var max:Number = ( hasAlpha ) ? 0xFFFFFFFF : 0xFFFFFF;
    return uint( Math.min( Math.max( color, 0 ), max ) );

  2. Thanks for posting this! It’s a very useful little utility. And thanks for the followup, Tink, you have a good point and a nice refinement on the original.

  3. thanks, great example, just note the return value type of uint, not unit 🙂

    function fixColorCode( color:Object, hasAlpha:Boolean = false ):uint

  4. If you can trust the passed value to be formatted like this: #F08000

    function GetColorValue( ColorCode:String ):Number
    return Number( “0x”+ColorCode.substring( 1 ) );

  5. Or keep it simple:

    function convertColor(pValue:String) :String {
    var hash:RegExp = new RegExp(“#”);
    return pValue.replace(hash, “0x”);

    trace(convertColor( “#FFCC44” ));

  6. var passedColor:String = “#FFCC00”;
    var outputColor:uint=0x000000;
    outputColor = uint(passedColor.split(“#”).join(“0x”));
    return outputColor;

Comments are closed.