Java Reference
In-Depth Information
In Listing 8-2, the Rectangle named rect is created with its fill property bound to a function called
createColor , which is passed to a variable named red and some constant values. The variable red is a
Number that is modified by the Timeline named anim . The magic is in the function createColor , as shown
in Listing 8-3.
Listing 8-3. createColor
function createColor(red:Number,green:Number,blue:Number,opacity:Number){
return Color{
red: zeroToOne(red)
green: zeroToOne(green)
blue: zeroToOne(blue)
opacity: zeroToOne(opacity)
}
}
In Listing 8-3, the function createColor simply takes the values passed in and creates a new color.
The function zeroToOne is a utility function that forces the values to be in the range 0.0 to 1.0. Color will
throw an exception if a value is outside of this range. However, I find it a useful technique with
animations, as it allows values outside of the legal range to be “modded” into the correct range.
Listing 8-4 shows the function zeroToOne .
Listing 8-4. zeroToOne
public function zeroToOne(number:Number):Number{
if (number > 1.0){
var whole:Integer = Math.round(Math.floor(number));
return number - whole;
} else if (number < 0.0){
var whole:Integer = Math.round(Math.floor(number));
return (number - whole) + 1;
} else {
return number;
}
}
The function zeroToOne takes a number and checks if it is geater than 1.0. If it is, it returns just the
fractional part of the number. If the number is less than 0.0, then the fractional part plus one is returned.
Thus given an input of -1.8, we would take the fractional part (-0.8) and add 1.0 to it, yielding 0.2. If the
number is neither greater than 1.0 nor less than 0.0, it is simply returned.
This example shows the basic technique of binding to a function in order to create a new object. The
next examples will expand on this technique so it can be used with the two types of gradients.