public class Greeter extends MovieClip
{
public function Greeter()
{
addEventListener(Event.ADDED_TO_STAGE, go);
}
private function go(evt:Event):void
{
removeEventListener(Event.ADDED_TO_STAGE, go);
var _root:MovieClip = parent.parent as MovieClip;
var sp:Sprite = new Sprite();
// Desenhando com um objeto graphics
var g:Graphics = sp.graphics;
g.beginFill(0xFF0000, 1);
g.drawRect(10, 10, 300, 200);
g.endFill();
_root.addChild(sp);
}
}
mxml file:
<?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx" minWidth="1024" minHeight="768"
creationComplete="initApp()">
<fx:Script>
<![CDATA[
public function initApp():void
{
var greeter:Greeter = new Greeter();
}
]]>
</fx:Script>
</s:Application>
--answer:
Add to the stage using addElement and extends spark.core.SpriteVisualElement.
You need to add greeter to the stage
public function initApp():void
{
var greeter = new Greeter();
addChild( greeter );
}
When calling addChild( greeter ) it will trigger the event listener you added in the Greeter constructor and call the go method in which you draw your rectangle. Note that you don't need to do: _root.addChild( sp ); Since greeter is added to the stage in the initApp method, you can just add sp to greeter, by doing addChild( sp ) in the go method.