“But, I can do that without code.” This is true. Creating a gradient is a somewhat mundane task that is found in almost every graphics program on the market. Flash is no exception. So why would you want to create it with code? The initial and easy answer is file size. Accomplishing tasks through code is inherently lighter. But, given the negligible difference in file size here, I would use code for the flexibility it offers.
Do you own or have you ever played a PS3? If you have, you’ve probably noticed that the background of the menu screen is a gradient. However, the gradient is unique in that it changes its hues depending on the time of day. It’s a subtle aesthetic change that shows a bit of forethought on the designers part. I can guarantee you there aren’t little critters inside the PS3 with paintbrushes that change the gradient colors at the top of the hour. It’s done through code.
The Code
There’s nothing too revolutionary here. In fact, all we’re doing here is drawing out a rectangle the size of the stage and then applying the gradient to it. Note: I’ll just be using the dimensions 800 x 600 to show how this can be used for any size shape. It this was truly meant for a stage background you’d probably want to use stage.width and stage.height.
ActionScript 3.0:
package {
import flash.display.*;
import flash.geom.*;
public class DocClass extends Sprite {
private var _gradientBG:Shape;
private var _matrix:Matrix;
private var _gradient:String;
private var _colors:Array;
private var _alphas:Array;
private var _ratios:Array;
public function DocClass() {
//Instantiate
_gradientBG = new Shape();
//Gradient Properties
_matrix = new Matrix();
_gradient = GradientType.LINEAR;
_colors = [0xFF0000, 0x000000];
_alphas = [0, 1];
_ratios = [0, 255];
//Gradient Matrix
_matrix.createGradientBox(800, 600, deg2rad(90), 0, 0);
//Gradient Fills
_gradientBG.graphics.beginGradientFill(_gradient, _colors, _alphas, _ratios, _matrix);
//The shapes of the gradients
_gradientBG.graphics.drawRoundRect(0, 0, 800, 600, 0);
//Add to display list
addChild(_gradientBG);
}
private function deg2rad(deg:Number):Number {
return deg * (Math.PI/180);
}
}
}
There are a couple things to note here. I don’t ever write on the timeline, so you’ll notice that this package is called DocClass. That is simply the name I normally give to the, yup you guessed it, Document Class.
You’ll also notice that I use rounded rectangles in my code. You can, of course, just use drawRect(), but I like the option of adding rounded corners down the road.
I think the code is well written enough and commented out so that you shouldn’t have any problems getting this to work. Feel free to ask any questions in the comments if you get stuck. You can see how easy it would be to implement the PS3 example because you’d just have to change the _colors variable in relation to the time of day. Pretty sweet.
