Search code examples
actionscript-3colors

Is it possible to use color names in AS3?


I am trying to find out whether it is possible to use color alias in a string format("orange", 'blue') in Actionscript. Since the main purpose of AS is to produce SFW graphics, there has to be convenient ways to code in similar way as some other programming languages allow to do it.

I would expect this code to produce a blue rectangle:

package
{
    import flash.display.*;

    public class NewActionScriptDesktopProject extends Sprite
    {
        public function NewActionScriptDesktopProject()
        {
                    graphics.beginFill('blue');
                    graphics.drawRect(0,0,300,200);
        }
    }
}

Instead, the code should contain this:

graphics.beginFill(0xe0057B7);

Solution

  • No, but you have a couple of options here:

    1. Create a enum class with predefined values:
    public class Color {
      static public const SKY_BLUE:uint = 0x0099FF;
    }
    
    public class Main extends Sprite {
      public function Main() {
        graphics.beginFill(Color.SKY_BLUE)
      }
    }
    

    OR

    1. take it a step further and make a custom class that extends Shape (graphics class is not extendable) and implement custom graphics methods:
      import flash.display.Shape;
    
      public class GFX extends Shape {
        public function GFX() {
    
        }
    
        public function beginFill(colorName:String, alpha:Number=1.0):void {
          graphics.beginFill(colorStringToInt(colorName), alpha);
        }
    
        public function colorStringToInt(colorString:String):uint {
          if (colorString == "skyblue") {
            return 0x0099FF;
          } else if (colorString == "darkgrey") {
            return 0x3D3D3D;
          } // etc.
        }
      }
    

    Personally, I have taken a more complicated route of the first method and created a custom RGBA class with various color manipulation functions. It's very helpful. Take a look here for some examples on things you can do if you chose option 1.

    EDIT: I've committed my colors library in a separate repo along with a swc binary, feel free to use it if you want :)