Flash Explained

Learn Flash easily.

Creating gradient fills with ActionScript

October 12th, 2008 | Author: Luka | Category: ActionScript


Gradient fills are a little bit more complex than simple, plain color fills. But, they offer much more possibilites than the ordinary fills do.

1 Open a new document, call the first layer actions, click in its first keyframe, open the Actions panel and enter the following code:

_root.lineStyle(1, 0x000000, 100);
_root.moveTo(200, 100);
_root.lineTo(350, 100);
_root.lineTo(350, 200);
_root.lineTo(200, 200);
_root.lineTo(200, 100);

Test your movie and check that you obtained a rectangle looking like the one in the image below.

The rectangle drawn with ActionScript.

Note that this isn’t necessary – you could do without this border and just make the gradient fill define the shape. I put this step in to facilitate things, for you to more easily see the creation of a gradient fill.

2 Append your code with the lines shown in bold:

fillType = "linear";
colors = [0xFF0000, 0x0000FF];
alphas = [100, 100];
ratios = [0, 255];
matrix = {matrixType:"box", x:200, y:150, w:150, h:100, r:0/180*Math.PI};

_root.lineStyle(1, 0x000000, 100);
_root.beginGradientFill(fillType, colors, alphas, ratios, matrix);
_root.moveTo(200, 100);
_root.lineTo(350, 100);
_root.lineTo(350, 200);
_root.lineTo(200, 200);
_root.lineTo(200, 100);
_root.endFill();

Test your movie and you should see this kind of gradient fill appear in your rectangle:

The rectangle coloured with a gradient fill.

Let me explain you what the various pieces of code that you added mean. I’ll start with the easiest first, then I’ll go into detail. The line

_root.beginGradientFill(fillType, colors, alphas, ratios, matrix);

tells Flash to begin filling the drawing with the gradient of your choice. The beginGradientFill method is used with the following parameters:

  • fillType – the options available are "linear" or "radial". These are string (text) values, that is why they have to be written between quotation marks.
  • colors – the colors you want to use in your gradient. The maximum possible number of colors you can use is 15. The value is an array.
  • alphas – the transparency of colors you defined in the previous parameter. The possible values range from 0 (completely transparent) to 100 (completely opaque). If you specify a value less then 0, Flash will use 0. If you enter a value greater than 100, Flash will use 100. It makes sense, because you can’t have something more transparent than alpha put at 0, beacuse a color or a drawing with alpha 0 is invisible. This value is an array, too.
  • ratios – defines how the colours are blended together – when does the mixing with the other begin (more on this later). This value is likewise an array.
  • matrix – defines the gradient as a box, with its top left corner, width, height and rotation. The matrix parameter can also be defined as a 3×3 matrix, but this is beyond the scope of this tutorial.

The last line,

_root.endFill();

closes the fill, the same way as it does with ordinary, plain color fills.

Let’s explain the beginGradientFill method parameters in detail. First, I defined the parameters as variables. Variables are pieces of data, be that data numerical, textual (strings), boolean (true or false), or some other kind of data. Why did I do that? Because it’s much easier to define variables first (like I did in the first five lines of ActionScript code), and then employ them later. In that way, if you use the same values for your gradients later, you must only change the variable values, you don’t have to go into the parentheses of the beginGradientFill method and change them there. Besides, that would be really hard to read and edit. To show you what I mean, look at this line of code:

_root.beginGradientFill("linear", [0xFF0000, 0x0000FF], [100, 100], [0, 255], {matrixType:"box", x:200, y:150, w:150, h:100, r:0/180*Math.PI});

There isn’t any error in that line of coder, it can perfectly function. But it isn’t practical at all, is it?

So, I defined the variables which I’ll use later first:

fillType = "linear";
colors = [0xFF0000, 0x0000FF];
alphas = [100, 100];
ratios = [0, 255];
matrix = {matrixType:"box", x:200, y:150, w:150, h:100, r:0/180*Math.PI};

I didn’t need to call them fillType, colors, etc. I could have written transparency instead of alpha and it would be OK also. But, it is much better pratice to give variables names in accordance with the data they hold, in accordance with their meaning.

Always give your variables meaningful names. If you call a variable grcol2e for example (sounds really stupid, doesn’t it?), return to your code some months later because of some modification you or your client needs, you will waste time searching through the code for the meaning of that variable. Giving variables meaningful names makes working on your code much easier for you, and for someone who might continue working on your movie after you.

So, the first line,

fillType = "linear";

defines the type of fill – whether it will be a linear gradient fill or a radial one. Try typing in "radial" instead of "linear" and test your movie. You’ll see a nice radial fill. If you changed this, put it back to "linear" so I can explain you what the other parameters mean more easily.

colors = [0xFF0000, 0x0000FF];

With the colors variable, you define what colors your gradient will be composed of. This is an array type of value. That means the colors variable stores more than one value. These values have to be written between square brackets [ and ], and separated with commas. The values of the colors are hexadecimal values. If you need a more detailed explanation of these kinds of values, go see the tutorial on basic drawing with ActionScript. In this example, I chose red and blue colors – you can choose whichever you like.

alphas = [100, 100];

The alphas variable stores the data on transparency of the colors mentioned previously. This is an array, too. Important: the number of these values must match the number of the colors used in your gradient. In other words, you can’t have, let’s say, four colors defined for your gradient, but only two or three alpha values to match them. That simply won’t function. So, this example would create an error:

myColors = [0xFFC063, 0xEE006F, 0xC7E686, 0x0000FF];
myAlphas = [20, 100, 80];

The same thing goes for ratios. They must match the number of colors used.

ratios = [0, 255];

This is an array also. The possible ratio value for a color goes between 0 and 255 (0 and 255 included). Enter any other value, and you will get an erroneus result – no gradient displayed at all.

The ratio defines where in your gradient the color it is associated with is at its 100% value. Or, the place where that color is pure and hasn’t started mixing with the other color(s) yet.

In this example, 0 is the ratio for red and 255 is the ratio for blue. That means that pure red is positioned at the beginning at the gradient fill, and blue at its end – look the image below for explanation.

The ratios for their associated colours.

Change the red colour’s ratio to 127, so that your ratios variable looks like this:

ratios = [127, 255];

The ratio 127 is at the middle of the gradient. You can clearly see on the image below how the red color continues at its fullest hue till that point, when it begins mixing with blue.

The modified ratio for the first color.

Just one more thing to remember for ratios: they must be written sequentially, in increasing order, like I just showed you. You can’t write them like this:

ratios = [240, 100, 40, 3];

OK? Cool 🙂 Put the ratio of red back to 1.

Now, there is one last question that needs to be answered – what is the matrix? Ask Morpheus :)))))) Seriously, here is the piece of code that needs to be explained:

matrix = {matrixType:"box", x:200, y:150, w:150, h:100, r:0/180*Math.PI};

First, if you are reading this on a smaller monitor, don’t be alarmed – the code above is a single line, it is only being wrapped by the browser.

The parameters of the matrix parameter are written between the { and } curly braces. The first one, matrixType, tells Flash that this is a box type of gradient. The second and thrid one, x and y, are the coordinates of the top left corner of the gradient box. After that, the width (w) and height (h) define the dimensions of the gradient. The last one, r, defines the rotation of the gradient, expressed in radians. So, if it’s expressed in radians, how do I make a rotation by 45 degrees, you may ask? Simply, of course 🙂 Using the simple mathematical conversion formula for converting degrees to radians – it is the one written in your code. The formula says:

radians = degrees of rotation / 180 * PI

So, in your code, you simply substitute the 0 for any number of degrees you want to rotate your gradient to, clockwise. Try 45, for example. The Math.PI command tells Flash to put the most incredible number PI there (so you don’t have to look up for all those decimals after 3.14 yourself).

matrix = {matrixType:"box", x:200, y:150, w:150, h:100, r:45/180*Math.PI};

Test your movie – you’ll see the gradient rotated by 45 degrees.

The gradient rotated by 45 degrees.

Be Sociable, Share!

Comments

Submit a comment

  • vinod Dec 12, 2008 at 9:26 am

    nice explanations, and interesting to read and study it, especially his humor sense in his teaching which leads to study without boring, in the words what is matrix? and he explains was so funny.

  • Shriram Feb 18, 2009 at 12:57 pm

    Hi

    The tutorials post on this site are really WOW, they are smple and clear to understand.

    Thanks alot

    Shriram

  • Leen Feb 23, 2009 at 6:27 pm

    Great Tutorial!. Is there any other option for the `matrixType`, or it´s only “box”?

    Thanks.

  • Victor Feb 25, 2009 at 6:56 pm

    Thanks a lot!

  • Rosuav Mar 10, 2009 at 9:05 am

    As an experienced programmer who’s only recently (a few months ago) started working with Flash and ActionScript, I find your tutorials most helpful. Thank you! One thing I would really like to see, though: Can you put some links at the bottom of the article to the official documentation for each of the classes/methods described? Then when I, and apparently Leen above, go curiously looking for more information, it’s right there and accessible.

    Thanks for the nice, readable tutorials. They are obviously aimed at novice programmers, but are still helpful to someone who knows code like the back of his hand (better, actually – who knows where that hand has been!). For reference, all this works just fine if you use swfmill and mtasc rather than actual CS4.

  • […] Last but not least, the matrix object stores many values which define the type, placement, size and rotation of your gradient fill. For a more detailed explanation of this and all the preceding parameters of your fill, check out my lesson that explains the creation of gradient fills with ActionScript. […]

  • Joey Apr 11, 2011 at 11:29 pm

    Hi Luka, I’ve been trying to create a circular button with a gradient. I can get a nice circle, and a gradient, but the gradient never wants to sit in the center.

    Any thoughts on what I’m doing wrong?

    function drawCircle(centerX, centerY, radius, sides){
    var myCircle:MovieClip = this.createEmptyMovieClip(“myCircle”, this.getNextHighestDepth());
    fillType = “radial”;
    colors = [0xFF0000, 0x0000FF];
    alphas = [100, 100];
    ratios = [0, 255];
    matrix = {matrixType:”box”, x:centerX, y:centerY, w:radius*2, h:radius*2, r:0/180*Math.PI};
    matrix.createGradientBox(100, 100, 0, 0, 0);
    myCircle.beginGradientFill(fillType, colors, alphas, ratios, matrix);

    myCircle.moveTo(centerX + radius, centerY);

    for(var i=0; i<=sides; i++){
    var pointRatio = i/sides;
    var xSteps = magicTrigFunctionX(pointRatio);
    var ySteps = magicTrigFunctionY(pointRatio);
    var pointX = centerX + xSteps * radius;
    var pointY = centerY + ySteps * radius;
    myCircle.lineTo(pointX, pointY);
    }
    }
    //
    lineStyle(0);
    //
    drawCircle(300, 150, 120, 360);
    //

  • brian May 4, 2011 at 4:51 pm

    autogenerate gradient matrices with this tool
    http://www.touchspin.com/Actionscript_Playground_Gradeint_Toolkit.php

    autogenerate affine transform matrices with this tool
    http://www.touchspin.com/Actionscript_Playground_Affine_Transformation.php

  • kiran patil Sep 15, 2011 at 5:04 am

    such a nice example for this website

You must log in to post a comment.