Recipe 7.9.
Drawing a Triangle
Problem
You
want to draw a triangle at
runtime.
Solution
Use the Pen.drawTriangle( ) method.
Discussion
You can determine and plot the vertices of a
triangle, given the lengths of two sides and the angle between
them. This is a better approach than specifying the lengths of the
three sides, because knowing two sides and the angle between them
always determines a triangle, whereas three arbitrary sides may not
fit together to make a triangle.
The calculations involved in drawing a triangle
based on two sides and an angle are slightly complex, so the
simplest way to programmatically draw a triangle is to use the
drawTriangle( ) method
of the Pen class. The
drawTriangle( ) method accepts up to seven parameters,
described as follows:
x
-
The X coordinate of the centroid (the center
point) of the triangle.
y
-
The Y coordinate of the centroid of the
triangle.
ab
-
The length of the side formed between points
a and b.
ac
-
The length of the side formed between points
a and c.
angle
-
The angle (in degrees) between sides ab
and ac.
rotation
-
The rotation of the triangle in degrees. If 0 or
undefined, side ac parallels the x axis.
Once you've defined a Pen instance, you
can use the drawTriangle( ) method to quickly draw a
triangle, as in the following example:
var pen:Pen = new Pen(sampleSprite.graphics);
pen.drawTriangle(100, 100, 100, 200, 40);
You can precede drawTriangle( ) with a
call to beginFill( ),
beginGradientFill( ),
and beginBitmapFill( )
to apply a fill to the shape. Of course, you'll also want to then
call endFill( ) after the call to drawTriangle(
).
The following code draws a filled triangle
aligned to the upper left:
var pen:Pen = new Pen(sampleSprite.graphics);
pen.beginFill(0xFF0000);
pen.drawTriangle(100, 100, 100, 200, 40);
pen.endFill( );
See Also
Recipe
7.10 shows how to draw an isosceles triangle (and specify a
shape with three sides) using the drawRegularPolygon( )
method.
|