Apr
20
2009

Using filters from the ActionScript level

To apply any filter from the ActionScript 3 we use the "filters" property of every display object. All the filters are available from the flash.filters package. The example below presents how simple is to apply a filter to the MovieClip instance.

Box is a MovieClip of square placed in library.

First we need to instantiate one of the filters. I created two variables that are instances of the GlowFilter and the DropShadowFilter respectively. The filters constructors take plenty of parameters (like color, alpha, strength, etc...), but if we don't pass any, defaults will be used. Flash Help provides list of all parameters and examples. If we want to add or change any filter parameters later we can do that by applying a new value to a object property like glow.color = 0xFFFFFF. But it's important to remember that when we assign the array of a filter instance to the MovieClip or any other display object, this is actually a cloning of this array. So after any change we made to the filter instances, we need to overwrite a filter property again to take effect.

Removing a filter from the display object is the same process as removing an element from an array. And again we need to overwrite filter property of an object.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
import flash.display.MovieClip;
import flash.filters.*;

public class Filters extends MovieClip
{
var box_mc:Box = new Box();

//default parameters are as follows:
/*DropShadowFilter(
distance:Number = 4.0, angle:Number = 45,
color:uint = 0, alpha:Number = 1.0,
blurX:Number = 4.0, blurY:Number = 4.0, strength:Number = 1.0,
quality:int = 1, inner:Boolean = false,
knockout:Boolean = false, hideObject:Boolean = false)*/

//Let me set up only the most important parameter for start
var myShadow:DropShadowFilter = new DropShadowFilter(
10, 10, 0xffff00, .5, 2, 2, 1);

//glow filter with defaults
var myGlow:GlowFilter = new GlowFilter();

var filtersArray:Array = new Array();

public function Filters()
{
box_mc.x = box_mc.y = 10;
addChild(box_mc);

//applying filters table in the following order:
box_mc.filters = [myShadow, myGlow];

//now it's time to change the shadow color from yellow to red:
myShadow.color = 0xff0000;
//reapplying filters table to take effect
box_mc.filters = [myShadow, myGlow];

//to remove myGlow effect we can use pop() method
//(as for removing last element from an array)
//first we need to clone a filters table
filtersArray = box_mc.filters;
filtersArray.pop();
//and then reassign it back to the MovieClip
box_mc.filters = filtersArray;
}
}

 

AS3 Tips

Follow me on Twitter