DekGenius.com
[ Team LiB ] Previous Section Next Section

Recipe 4.3 Drawing a Rectangle

4.3.1 Problem

You want to draw a rectangle at runtime.

4.3.2 Solution

Create a custom MovieClip.drawSimpleRectangle( ) method using the Drawing API and invoke it on a movie clip.

4.3.3 Discussion

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 x 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.

4.3.4 See Also

See Recipe 4.4 for an enhanced rectangle-drawing routine that adds several features, such as optional rounded corners, offset, and rotation.

    [ Team LiB ] Previous Section Next Section