## With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

No credit card required

# Custom Graphical Classes

We've drawn lots of rectangles, circles, and triangles in this chapter. So many, that some of the examples we've studied have had a distinct "code smell": their code was repetitive, and therefore error-prone.

### Tip

To promote reuse and modularity when working with primitive shapes, we can move repetitive drawing routines into custom classes that extend the Shape class. Let's start with a custom Rectangle class, using an extremely simple approach that provides a very limited set of stroke and fill options, and does not allow the rectangle to be changed once drawn. Example 20-9 shows the code. (We'll expand on the Rectangle class's features in Chapter 25.)

Example 20-9. Rectangle, a simple shape subclass

```package {
import flash.display.Shape;

public class Rectangle extends Shape {
public function Rectangle (w:Number,
h:Number,
lineThickness:Number,
lineColor:uint,
fillColor:uint) {
graphics.lineStyle(lineThickness, lineColor);
graphics.beginFill(fillColor, 1);
graphics.drawRect(0, 0, w, h);
}
}
}```

Because Rectangle extends Shape, it inherits the Shape class's `graphics` variable, and can use it to draw the rectangular shape.

To create a new Rectangle, we use the following familiar code:

`var rect:Rectangle = new Rectangle(100, 50, 3, 0xFF0000, 0x0000FF);`

Because Shape is a DisplayObject descendant, Rectangle inherits the ability to be added to the display list (as ...

## With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

No credit card required