Drawing a rectangle using ActionScript

written by: Elis Frugalo; article published: year 2007, month 02;

In: Root » Computers and technology » Flash

  Share  
|
  PL  |  NL  |  FR  |  ES  |  PT  |  IT  |  DE  |  DK  |  NO  |  SE  |  FI  |  GR  |  JP  |  CN  |  KR  |  RU  |  AE


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

Share

Disclaimer

1) E-articles is not responsible for the information contained by this article as well for any and all copyright infringements by authors and writers. E-articles is a free information resource. If you suspect this article for any copyright infringement, please read the terms of service and contact us or use the "Report this article" button on this page to investigate the problem.
2) E-articles is not responsible for inaccuracies, falsehoods, or any other types of misinformation this article may contain and will not be liable for any loss or damage suffered by a user through the user's reliance on the information gained here.