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.

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.