Create a custom MovieClip.drawSimpleRectangle( )
method using the Drawing API and invoke it on a
movie clip.
To draw a simple rectangle, specify the stroke’s
attributes
using the lineStyle(
)
method and then draw four lines using the
lineTo( )
method:
// Create rectangle_mc
with a depth of 1 on the main timeline.
_root.createEmptyMovieClip("rectangle_mc", 1);
// Specify a one-pixel, solid, black line.
rectangle_mc.lineStyle(1, 0x000000, 100);
// Draw four lines to form the perimeter of the rectangle.
rectangle_mc.lineTo(100, 0);
rectangle_mc.lineTo(100, 50);
rectangle_mc.lineTo( 0, 50);
rectangle_mc.lineTo( 0, 0);
Thus, drawing a simple rectangle is no huge feat. To draw multiple
rectangles with various dimensions, you should create a custom
drawSimpleRectangle( )
method for the
MovieClip
class, as follows:
// Define the custom method on MovieClip.prototype
so that it's available to all
// movie clip instances.
MovieClip.prototype.drawSimpleRectangle = function (width, height) {
this.lineTo(width, 0);
this.lineTo(width, height);
this.lineTo(0, height);
this.lineTo(0, 0);
}
// Invoke the custom method like this.
_root.createEmptyMovieClip("rectangle_mc", 1);
rectangle_mc.lineStyle(1, 0x000000, 100);
rectangle_mc.drawSimpleRectangle(100, 50);
The dimensions of the rectangle are 102 × 52 pixels due to the line thickness. Reduce the dimensions by two pixels in each direction to create a rectangle whose outside dimensions match the intended size.
See Recipe 4.4 for an enhanced rectangle-drawing routine that adds several features, such as optional rounded corners, offset, and rotation.
Get Actionscript Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.