TDOT Blog Touchwood Creative

Register | Forgot password?

Author Info

Name
Ben Bishop

Job Title
Senior Interactive Developer



Touchwood is continuing to grow!

We are looking for talented Flex developers to join our Interactive Group. If you have any interest we would love to meet you. Please email your resume to us at:

jobs@touchwoodcreative.com


Actionscript 3: How to Draw a Shape with Flex 3

Problem:

You want to draw a square programmatically using Actionscript's drawing API.

Solution:

  1. Create an user interface that allows to user to specify the following attributes for the square: x, y, width, height, line width, line color, and fill color. We will use numeric steppers and color pickers to ensure the attributes are entered in the correct format.

    <mx:HBox width="100%" height="100%">

    <mx:VBox paddingLeft="10">

    <mx:Label text="Box Attributes:" fontWeight="bold"/>
    <mx:Label text="x:"/>
    <mx:NumericStepper id="x_ns" value="50" maximum="{drawing_cvs.width}"/>
    <mx:Label text="y:"/>
    <mx:NumericStepper id="y_ns" value="50" maximum="{drawing_cvs.height}"/>
    <mx:Label text="width:" />
    <mx:NumericStepper id="width_ns" value="50" maximum="{drawing_cvs.width}"/>
    <mx:Label text="height:" />
    <mx:NumericStepper id="height_ns" value="50" maximum="{drawing_cvs.height}"/>
    <mx:Label text="line width:" />
    <mx:NumericStepper id="lineWidth_ns" value="1"/>
    <mx:Label text="line color:" />
    <mx:ColorPicker id="line_cp" selectedColor="#000000"/>
    <mx:Label text="fill color:" />
    <mx:ColorPicker id="fill_cp" selectedColor="#FFFFFF"/>
    <mx:Button label="Draw" click="drawBox()"/>

    </mx:VBox>
    <mx:VBox width="100%" height="100%">

    <mx:Label text="Drawing Area:" fontWeight="bold"/>
    <mx:Canvas id="drawing_cvs" backgroundColor="#FFFFFF" width="500" height="500"/>

    </mx:VBox>

    </mx:HBox>

  2. Write the drawBox function that will create a new Shape and empty UIComponent, use the graphics object of the shape to draw a rectangle, and then attach it to our drawing_cvs canvas.

    import mx.containers.GridRow;
    import mx.core.UIComponent;
    private function drawBox():void{

    var aBox:Shape = new Shape();
    var c:UIComponent = new UIComponent();

    aBox.graphics.lineStyle(lineWidth_ns.value, line_cp.selectedColor);
    aBox.graphics.beginFill(fill_cp.selectedColor, 1);

    aBox.graphics.drawRect(x_ns.value, y_ns.value, width_ns.value, height_ns.value);
    aBox.graphics.endFill();
    c.addChild(aBox);
    drawing_cvs.addChild(c);

    }

  3. Viola!

The source files for this example are attached to this post. On a side note, the UIComponent that holds the Shape could've also been attached to another type of UI element like an image or HTMLControl just to name a couple instead of a Canvas object.

AttachmentSize
Drawing_API.zip333.95 KB
© Touchwood Creative 2007 | We use Firefox