Actionscript 3: How to Draw a Shape with Flex 3
Submitted by ben.bishop on Sun, 11/11/2007 - 20:36.Problem:
You want to draw a square programmatically using Actionscript's drawing API.
Solution:
- 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>
- 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);}
- 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.
| Attachment | Size |
|---|---|
| Drawing_API.zip | 333.95 KB |
Reply
- Web page addresses and e-mail addresses turn into links automatically.
- Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd>
- Lines and paragraphs break automatically.
