How Do I Draw with Code?: Chapter 12 - ActionScript 3.0 Quick Reference Guide
Pages: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13

12.7 Drawing a Rectangle

Problem

You want to draw a rectangle.

Solution

Use the drawRect() method of the Graphics class.

Discussion

ActionScript 3.0 has added a few methods to draw geometric shapes, removing the need to build them with multiple line segments. Creating a rectangle is as easy as calling drawRect(), passing in the rectangle’s x and y location, followed by height and width.

var sp:Sprite = new Sprite();
addChild(sp);
sp.x = sp.y = 100;
var g:Graphics = sp.graphics;
g.lineStyle(1, 0x0000FF);
g.drawRect(0, 0, 100, 60);

All primitives in this chapter, except for a circle, are drawn down and to the right of the x and y coordinates specified. When drawing into a parent container, as in this example, this trait results in a registration point at the upper-left corner of the shape. To draw this rectangle around its center point, offset the x and y values passed into drawRect() by half the width and half the height, respectively. The following substitute line makes the rectangle center-aligned within its parent container, sp.

g.drawRect(−50, −30, 100, 60);

Pages: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13

Next Pagearrow