ExpatTech is currently short-staffed due to increased corporate on-site work, and our office will often be closed. Please call +36705578849 to arrange an appointment time!

ExpatTech Techblog

Peter Todd 2010.09.27. 16:57

Flash Cookbook - Colors - Colors, R, G, B, and alpha, hex and dec, RGB, ARGB

In flash the color value is normally a uint.

var color:uint = 0xff1113;

This color is a simple RGB color. Now what do we do, if we want to get the green value out of it? We can start to parse it as a string , get the subtring and parse it more.

Now let's say we need both the hexadecimal and decimal representation. There is a quick way of doing this:

var r:int = color >> 16 & 0xff;
var g:int = color >> 8 & 0xff;
var b:int = color & 0xff;

These results are all integers, showing each value from 0 to 255. ">>" is the bitwise right shift operator (you can read more about it for example in Adobe's documentation), and "&" is the bitwise AND operator (doc).

To get the hexadecimal representation of these you simply use the toString method of int class:

r.toString(16). 16 means its radix is 16, since the original representation is hexadecimal.

Now, what if our color is ARGB? That is similar:

var color:uint = 0xaaff1113;

and so:

var a:int = color >> 24 & 0xff;
var r:int = color >> 16 & 0xff;
var g:int = color >> 8 & 0xff;
var b:int = color & 0xff;

Note, that the bitwise right shift does not modify the original color value, therefore if you are only interested in getting one channel, you can leave all the others out.

var color:uint = 0xaaff1113;
var r:int = color >> 16 & 0xff;

Getting the hexadecimal value is still the same:

var hex:String = a.toString(16);

Hit a trace on the values:

trace(a, a.toString(16), r, r.toString(16), g, g.toString(16), b, b.toString(16));

Result is:

(A dec - hex) 170 aa (R) 255 ff (G) 17 11 (B) 19 13