Simple Actionscript Color Separator Class

I saw a blog post discussing how to grab the separate composite colors from a unit in ActionScript. This has probably been addressed and solved many times, but there does not seem to be a built-in object to take care of this bit of functionality. You'd think that mx.utils.ColorUtil would be a natural place to find such things, but not so much.

So while the author chose to go with string manipulation, I figure it would be a good opportunity to do a little binary work and create a simple little class to keep everything tidy.

The general scheme is to perform a Right Shift and then an And. The color information is either 24 or 32 bit with the extra 8 bits in the latter describing the opacity of the pixel. Shifting makes the desired color channel the least significant amount and the logical and with 0xFF will remove any other remaining information. So, to get the channels, it would work out like the following:

COLOR = 0xeaeaea // Some Color

BLUE: (COLOR >> 0) & 0xFF
GREEN: (COLOR >> 8) & 0xFF
RED: (COLOR >> 16) & 0xFF
ALPHA: (COLOR >> 24) & 0xFF

So, a quick little class to implement this:

package com {
public class Color {
private var _color:uint = 0xFFFFFF;
            
public function Color(color:uint) {
_color = color;
}
        
public function get red():uint {
return (_color >
> 16) & 0xFF;
}
        
public function get green():uint {
return (_color >> 8) & 0xFF;
}
        
public function get blue():uint {
return _color & 0xFF;
}
        
public function get alpha():uint {
return (_color >> 24) & 0xFF;    
}
        
}
}

And it can be used easily enough. For example:

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute">

<mx:Script>
<![CDATA[
import com.Color;
import mx.controls.Alert;
import mx.utils.ObjectUtil;
        
private function test():void {
Alert.show( ObjectUtil.toString( new Color(cpTest.selectedColor) ) );
}
        
]]>

</mx:Script>

<mx:ColorPicker id="cpTest" top="10" />

<mx:Button label="test" click="test()" top="50" />
    
</mx:Application>

And here is working example of an ActionScript color separator.

Related Blog Entries

Comments (Comment Moderation is enabled. Your comment will not appear until approved.)
David's Gravatar Hi Jason,
Thanks for this example on the follow up on my blog.
Working with numbers as numbers always feels best.
Just need to learn more!
# Posted By David | 12/18/09 2:01 AM
BlogCFC was created by Raymond Camden. This blog is running version 5.9.1.001. Contact Blog Owner