This recipe adds only one significant new line to material covered in previous recipes. However, due to subtle changes (variable names, size, and fill style), the complete code has been collected here. This example combines two sprites, one with a rectangle with a solid fill, and another with a rectangle with a gradient fill. The solid rectangle is on the bottom and is 300 pixels wide by 300 pixels tall. The top rectangle contains a gradient of 100 percent alpha black to 0 percent alpha black (transparent), and measures only 100 × 100 pixels.
The last line of this recipe is the important one. To use one
display object to dynamically mask another, set the
mask property of the
maskee, to the mask.
var sp:Sprite = new Sprite(); addChild(sp); var g:Graphics = sp.graphics; g.lineStyle(); g.beginFill(0x000099, 1); g.drawRect(0, 0, 300, 300); g.endFill(); var gradType:String = GradientType.LINEAR; var colors:Array = [0x000000, 0x000000]; var alphas:Array = [1, 0]; var ratios:Array = [0, 255]; var matrix:Matrix = new Matrix(); matrix.createGradientBox(100, 100, 0, 0, 0); var spMask:Sprite = new Sprite(); addChild(spMask); spMask.x = spMask.y = 100; var gMask:Graphics = spMask.graphics; gMask.beginGradientFill(gradType, colors, alphas, ratios, matrix); gMask.drawRect(0, 0, 100, 100); gMask.endFill(); sp.mask = spMask;
Note that this minimal approach supports only 1-bit masks. That is, any non-transparent pixel, no matter what the alpha value of that pixel, is considered opaque and part of the mask. This example uses a gradient that changes from 100 percent alpha to 0 percent alpha to emphasize that the alpha data has no effect, by default, on the mask.
However, 8-bit masks, or masks with varying degrees of alpha values, are supported when using bitmap caching, as seen in the next recipe.
the section called “12.6 Defining a Fill Style” and the section called “12.10 Creating a Gradient Fill” for how to create a solid or gradient fill, and see the section called “12.12 Caching Vector as Bitmap” for how to cache a bitmap.