Here’s a pretty weak tip, but maybe somebody out there will find it useful. Often when working with colors, you need to format the text before displaying it, otherwise blue may display as “ff” and black as “0″. Here’s a semi-handy tip for making sure numbers display as hex values with at least six characters (and all uppercase, no less).
The following example uses a Slider to select a number between 0×000000 (black) and 0xFFFFFF (white) to use for the background color of a box. We use the slider’s tool tip to display our nicely formatted number, although we could have used a Label or anything else just as easy.
<
<?xml version="1.0" encoding="utf-8"?>
<!-- http://blog.flexexamples.com/2007/07/25/formatting-colors-as-strings-with-actionscript/ -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
layout="vertical"
verticalAlign="middle"
backgroundColor="white">
<mx:Script>
<![CDATA[
private function intToHex(color:int = 0):String {
var mask:String = "000000";
var str:String = mask + color.toString(16).toUpperCase()
return "#" + str.substr(str.length - 6);
}
]]>
</mx:Script>
<mx:Box id="box"
width="200"
height="100"
backgroundColor="{slider.value}" />
<mx:HSlider id="slider"
minimum="0x000000"
maximum="0xFFFFFF"
liveDragging="true"
dataTipFormatFunction="intToHex"
width="{box.width}" />
<mx:Label text="{intToHex(slider.value)}" />
</mx:Application>
View source is enabled in the following example.
Although quite uninteresting, this code works by taking the color as a numeric value, converting it to a hexadecimal string using toString(16), converting that string to uppercase and prefixing six zeros in front of that string. Now, to make sure we only return a maximum of six alpha-numeric digits, we use the substr() method to just grab the end of the string. Pretty easy, huh?




First post :-)
Hey nice work on this blog and keep it up!
I was wondering about a Flex colour picker component - have you ever heard of such a thing existing?
Ultraniblet,
There is a ColorPicker control in the Flex framework (look in the mx.controls package).
You can find the Flex 2.0.1 ColorPicker documentation online at http://livedocs.adobe.com/flex/201/langref/mx/controls/ColorPicker.html or the beta Flex 3 documentation at http://livedocs.adobe.com/labs/flex/3/langref/mx/controls/ColorPicker.html.
I also just wrote a brief post on it at: “Using the ColorPicker control’s colorField and labelField properties”.
Hope that helps,
Peter
wow, very nice
pretty helpful
Thanks for this example. I was wondering why you prefix 000000 to the String?
Nikos Katsikanis,
I prefixed with “000000″ so that the color black will display as #000000 instead of #0, and green would be #00FF00 instead of #FF00. Basically it was to ensure that the formatted number would always be six characters long.
Peter
Ah I see, thanks very much for you quick response. This is one of the best sities for learning flex, I’m going through every example.