AS3 Uint Colour Util – Update: Now with source

Since Flash works with colour in the hex format, I’m always finding it annoying how you have to convert to RGB to perform manipulations on colours. Most colour classes out there like Grant Skinners Color Matrix and the ColorMatrix by Quasimondo work with matrices and the ColourTransform class, which is OK sometimes. But I find they can be overly complicated when you just want to take a hex, do something to it, and then get a another hex in return which can be easily applied to anything you need. After a lot of research I couldn’t find anything that just works with taking and returning raw uints. So I decided to take it upon myself to make a class where you can pass in uints and get uints in return.

What I came up with is the ColourUtil class. I guess it’s kind of like StringUtil classes you see around the place which take a string, manipulate it and return another string. Except my class takes a colour in the form of a uint, and returns a uint. The class is still a work in progress but I have made a little demo below.

So far the class contains the following methods:

  • HexToRGB(hex:uint):Array – returns array with r,g,b values from a uint
  • RGBtoHSV(r:Number, g:Number, b:Number):Array- returns array with h,s,v values from RGB values
  • RGBToHex(r:uint, g:uint, b:uint):uint – returns a uint from RGB
  • HSVtoRGB(h:Number, s:Number, v:Number):Array – returns r,g,b values from HSV values
  • getAnalogousFromHex(c:uint,rot:Number):uint – returns new uint from a uint with rotation amount (rotates the hue)
  • HEXTriad(c:uint):Array – returns array with three triad colours
  • HEXTetrad(c:uint):Array- returns array with four tetrad colours
  • invertHEX(c:uint):uint – returns inverted uint
  • HEXtoString(c:uint,t:Boolean):String – returns hex value as string  (ie either 0xFFFFFF or #FFFFFF)
  • HEXStringToHEX(hex:String):uint – takes a string (ie #FFFFFF or 0xFFFFFF) and returns uint value
  • HEXtoGreyScale(c:uint):uint – returns greyscale uint
  • extractRedFromHEX(c:uint):uint – returns red values in uint
  • extractGreenFromHEX(c:uint):uint – returns green values in uint
  • extractBlueFromHEX(c:uint):uin t- returns blue values in uint

I am also working on the following methods:

  • darkenHEX(c:uint,a:Number):uint – darken uint by amount
  • lightenHEX(c:uint,a:Number):uint – lighten uint by amount
  • colouriseHEX(c:uint,r:Number,g:Number,b:Number):uint – colourise a uint

And I plan to add more too such as getting shades/monochrome arrays.

But enough chitty-chat, here is the demo. Click on the colour wheel to choose a colour and see the variation on the right panel. Drag the hue slider to rotate the hue.

Update 29-03-2011:

Download the class

Please note that the class is currently uncommented and pretty messy, and I haven’t done any optimisations on it yet. But I think all the methods are explained above anyway.

Get Adobe Flash player

Posted toActionScript Flash