How Do I Draw with Code?: Chapter 12 - ActionScript 3.0 Quick Reference Guide
Pages: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13

12.11 Using a Drawn Shape as a Dynamic Mask

Problem

You want to mask a display object with another display object created at runtime.

Solution

Draw the mask using the Graphics class, and then use the mask property of shape, sprite, and movie clip display objects.

Discussion

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.

Pages: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13

Next Pagearrow