Recipe 7.10.
Drawing Regular Polygons
Problem
You want to draw a regular polygon (a polygon
where all sides are equal length) at runtime.
Solution
Use the Pen.drawRegularPolygon( )
method.
Discussion
You can create a method to draw a regular
polygon using basic trigonometric ratios to determine the necessary
angles and coordinates of the segments. Of course, since employing
those trigonometric ratios requires quite a lot of code and you
actually recall trigonometry, you'll likely find it much easier to
simply use the drawRegularPolygon( ) method of
the Pen class.
The drawRegularPolygon( ) accepts up to
five parameters, described as follows:
x
-
The x
coordinate of the center of the polygon.
y
-
The y
coordinate of the center of the polygon.
sides
-
The number of sides in the polygon.
length
-
The length of each side in pixels.
rotation
-
The number of degrees by which the polygon
should be rotated.
Once you have defined a Pen instance, you
can quickly draw regular polygons with any number of sides (with a
minimum of three sides, of course, to be a valid polygon):
var pen:Pen = new Pen(sampleSprite.graphics);
// Draw a pentagon in which the sides are each 50 pixels
pen.drawRegularPolygon(100, 100, 5, 50);
As with the other shape drawing methods in this
chapter, you can create a filled polygon by invoking beginFill(
), beginGradientFill( ), or beginBitmapFill( )
before drawRegularPolygon( ), and invoking endFill( )
after drawRegularPolygon( ):
var pen:Pen = new Pen(sampleSprite.graphics);
pen.beginFill(0xFF0000);
pen.drawRegularPolygon(100, 100, 5, 50);
pen.endFill( );
|