flash.displayFrameLabel The FrameLabel object contains properties that specify a frame number and the corresponding label name.Object The FrameLabel object contains properties that specify a frame number and the corresponding label name. The Scene class includes a labels property, which is an array of FrameLabel objects for the scene. Scene.labelsMovieClip.currentLabelMovieClip.currentSceneMovieClip.scenesMovieClip.gotoAndPlay()MovieClip.gotoAndStop()frame The frame number containing the label.int The frame number containing the label. name The name of the label.String The name of the label. InteractiveObject The InteractiveObject class is the abstract base class for all display objects with which the user can interact, using the mouse, keyboard, or other user input device.flash.display:DisplayObject The InteractiveObject class is the abstract base class for all display objects with which the user can interact, using the mouse, keyboard, or other user input device.

You cannot instantiate the InteractiveObject class directly. A call to the new InteractiveObject() constructor throws an ArgumentError exception.

The InteractiveObject class itself does not include any APIs for rendering content onscreen. To create a custom subclass of the InteractiveObject class, extend one of the subclasses that do have APIs for rendering content onscreen, such as the Sprite, SimpleButton, TextField, or MovieClip classes.

The following example uses the InteractiveObjectExample class, which in turn uses the ChildSprite class to draw a rectangle and then manipulate that rectangle based on various mouse events. This task is accomplished by performing the following steps:
  1. In the InteractiveObjectExample constructor, a new ChildSprite object of type Sprite called child is created, which calls the ChildSprite constructor method to draw the shape and add mouse events for the shape (as explained in the following steps). The child object is added to the top of the display list at coordinates x = 0, y = 0.
  2. In the ChildSprite class, declare the size and overSize properties that are used later in the draw() method and MouseEvent methods.
  3. Declare properties that set the background color to orange, the mouse-over color to dark yellow, and the mouse-down color to light blue.
  4. In the ChildSprite constructor, an orange square is drawn by using methods from the Graphics class and the draw() method.
  5. The constructor adds four MouseEvent event listener methods:
    • mouseOverHandler: redraws a larger 60 x 60 pixel square with a dark-yellow color at the original coordinates.
    • mouseOutHandler: returns the square to its original size and color.
    • mouseDownHandler: redraws a larger 60 x 60 pixel square with a light-blue color at the original coordinates.
    • mouseUpHandler: same as mouseOverHandler.
package { import flash.display.Sprite; public class InteractiveObjectExample extends Sprite { public function InteractiveObjectExample() { var child:Sprite = new ChildSprite(); addChild(child); } } } import flash.display.Sprite; import flash.events.MouseEvent; class ChildSprite extends Sprite { private var size:uint = 50; private var overSize:uint = 60; private var backgroundColor:uint = 0xFFCC00; private var overColor:uint = 0xCCFF00; private var downColor:uint = 0x00CCFF; public function ChildSprite() { buttonMode = true; draw(size, size, backgroundColor); addEventListener(MouseEvent.MOUSE_OVER, mouseOverHandler); addEventListener(MouseEvent.MOUSE_OUT, mouseOutHandler); addEventListener(MouseEvent.MOUSE_DOWN, mouseDownHandler); addEventListener(MouseEvent.MOUSE_UP, mouseUpHandler); } private function draw(w:uint, h:uint, bgColor:uint):void { graphics.clear(); graphics.beginFill(bgColor); graphics.drawRect(0, 0, w, h); graphics.endFill(); } public function mouseOverHandler(event:MouseEvent):void { trace("mouseOverHandler"); draw(overSize, overSize, overColor); } public function mouseOutHandler(event:MouseEvent):void { trace("mouseOutHandler"); draw(size, size, backgroundColor); } public function mouseDownHandler(event:MouseEvent):void { trace("mouseDownHandler"); draw(overSize, overSize, downColor); } public function mouseUpHandler(event:MouseEvent):void { trace("mouseUpHandler"); draw(overSize, overSize, overColor); } }
softKeyboardDeactivate Dispatched immediately after the soft keyboard is lowered.flash.events.SoftKeyboardEvent.SOFT_KEYBOARD_DEACTIVATEflash.events.SoftKeyboardEventDispatched immediately after the soft keyboard is lowered. Dispatched immediately after the soft keyboard is lowered. flash.events.SoftKeyboardEventsoftKeyboardActivate Dispatched immediately after the soft keyboard is raised.flash.events.SoftKeyboardEvent.SOFT_KEYBOARD_ACTIVATEflash.events.SoftKeyboardEventDispatched immediately after the soft keyboard is raised. Dispatched immediately after the soft keyboard is raised. flash.events.SoftKeyboardEventsoftKeyboardActivating Dispatched immediately before the soft keyboard is raised.flash.events.SoftKeyboardEvent.SOFT_KEYBOARD_ACTIVATINGflash.events.SoftKeyboardEventDispatched immediately before the soft keyboard is raised. Dispatched immediately before the soft keyboard is raised. flash.events.SoftKeyboardEventtextInput Dispatched when a user enters one or more characters of text.flash.events.TextEvent.TEXT_INPUTflash.events.TextEvent Dispatched when a user enters one or more characters of text. Various text input methods can generate this event, including standard keyboards, input method editors (IMEs), voice or speech recognition systems, and even the act of pasting plain text with no formatting or style information. imeStartComposition This event is dispatched to any client app that supports inline input with an IME flash.events.IMEEvent This event is dispatched to any client app that supports inline input with an IME contextMenu Dispatched when a user gesture triggers the context menu associated with this interactive object in an AIR application.flash.events.MouseEvent.CONTEXT_MENUflash.events.MouseEvent Dispatched when a user gesture triggers the context menu associated with this interactive object in an AIR application. contextMenunativeDragComplete Dispatched by the drag initiator InteractiveObject when the user releases the drag gesture.flash.events.NativeDragEvent.NATIVE_DRAG_COMPLETEflash.events.NativeDragEvent Dispatched by the drag initiator InteractiveObject when the user releases the drag gesture.

The event's dropAction property indicates the action set by the drag target object; a value of "none" (DragActions.NONE) indicates that the drop was canceled or was not accepted.

The nativeDragComplete event handler is a convenient place to update the state of the initiating display object, for example, by removing an item from a list (on a drag action of "move"), or by changing the visual properties.

nativeDragUpdate Dispatched during a drag operation by the InteractiveObject that is specified as the drag initiator in the DragManager.doDrag() call.flash.events.NativeDragEvent.NATIVE_DRAG_UPDATEflash.events.NativeDragEvent Dispatched during a drag operation by the InteractiveObject that is specified as the drag initiator in the DragManager.doDrag() call.

nativeDragUpdate events are not dispatched on Linux.

nativeDragStart Dispatched at the beginning of a drag operation by the InteractiveObject that is specified as the drag initiator in the DragManager.doDrag() call.flash.events.NativeDragEvent.NATIVE_DRAG_STARTflash.events.NativeDragEvent Dispatched at the beginning of a drag operation by the InteractiveObject that is specified as the drag initiator in the DragManager.doDrag() call. nativeDragExit Dispatched by an InteractiveObject when a drag gesture leaves its boundary.flash.events.NativeDragEvent.NATIVE_DRAG_EXITflash.events.NativeDragEvent Dispatched by an InteractiveObject when a drag gesture leaves its boundary. nativeDragDrop Dispatched by the target InteractiveObject when a dragged object is dropped on it and the drop has been accepted with a call to DragManager.acceptDragDrop().flash.events.NativeDragEvent.NATIVE_DRAG_DROPflash.events.NativeDragEvent Dispatched by the target InteractiveObject when a dragged object is dropped on it and the drop has been accepted with a call to DragManager.acceptDragDrop().

Access the dropped data using the event object clipboard property.

The handler for this event should set the DragManager.dropAction property to provide feedback to the initiator object about which drag action was taken. If no value is set, the DragManager will select a default value from the list of allowed actions.

nativeDragOver Dispatched by an InteractiveObject continually while a drag gesture remains within its boundary.flash.events.NativeDragEvent.NATIVE_DRAG_OVERflash.events.NativeDragEvent Dispatched by an InteractiveObject continually while a drag gesture remains within its boundary.

nativeDragOver events are dispatched whenever the mouse is moved. On Windows and Mac, they are also dispatched on a short timer interval even when the mouse has not moved.

Handle either the nativeDragOver or nativeDragEnter events to allow the display object to become the drop target.

To determine whether the dispatching display object can accept the drop, check the suitability of the data in clipboard property of the event object, and the allowed drag actions in the allowedActions property.

nativeDragEnter Dispatched by an InteractiveObject when a drag gesture enters its boundary.flash.events.NativeDragEvent.NATIVE_DRAG_ENTERflash.events.NativeDragEvent Dispatched by an InteractiveObject when a drag gesture enters its boundary.

Handle either the nativeDragEnter or nativeDragOver events to allow the display object to become the drop target.

To determine whether the dispatching display object can accept the drop, check the suitability of the data in clipboard property of the event object, and the allowed drag actions in the allowedActions property.

tabIndexChange Dispatched when the value of the object's tabIndex property changes.flash.events.Event.TAB_INDEX_CHANGEflash.events.Event Dispatched when the value of the object's tabIndex property changes. tabEnabledChange Dispatched when the object's tabEnabled flag changes.flash.events.Event.TAB_ENABLED_CHANGEflash.events.Event Dispatched when the object's tabEnabled flag changes. tabChildrenChange Dispatched when the value of the object's tabChildren flag changes.flash.events.Event.TAB_CHILDREN_CHANGEflash.events.Event Dispatched when the value of the object's tabChildren flag changes. keyUp Dispatched when the user releases a key.flash.events.KeyboardEvent.KEY_UPflash.events.KeyboardEvent Dispatched when the user releases a key. Mappings between keys and specific characters vary by device and operating system. This event type is generated after such a mapping occurs but before the processing of an input method editor (IME). IMEs are used to enter characters, such as Chinese ideographs, that the standard QWERTY keyboard is ill-equipped to produce. This event occurs after a keyDown event and has the following characteristics: keyDown Dispatched when the user presses a key.flash.events.KeyboardEvent.KEY_DOWNflash.events.KeyboardEvent Dispatched when the user presses a key. Mappings between keys and specific characters vary by device and operating system. This event type is generated after such a mapping occurs but before the processing of an input method editor (IME). IMEs are used to enter characters, such as Chinese ideographs, that the standard QWERTY keyboard is ill-equipped to produce. This event occurs before the keyUp event.

In AIR, canceling this event prevents the character from being entered into a text field.

rightMouseUp Dispatched when a user releases the pointing device button over an InteractiveObject instance.flash.events.MouseEvent.RIGHT_MOUSE_UPflash.events.MouseEvent Dispatched when a user releases the pointing device button over an InteractiveObject instance. rightMouseDown Dispatched when a user presses the pointing device button over an InteractiveObject instance.flash.events.MouseEvent.RIGHT_MOUSE_DOWNflash.events.MouseEvent Dispatched when a user presses the pointing device button over an InteractiveObject instance. rightClick Dispatched when a user presses and releases the right button of the user's pointing device over the same InteractiveObject.flash.events.MouseEvent.RIGHT_CLICKflash.events.MouseEvent Dispatched when a user presses and releases the right button of the user's pointing device over the same InteractiveObject. For a rightClick event to occur, it must always follow this series of events in the order of occurrence: rightMouseDown event, then rightMouseUp. The target object must be identical for both of these events; otherwise the rightClick event does not occur. Any number of other mouse events can occur at any time between the rightMouseDown or rightMouseUp events; the rightClick event still occurs. middleMouseUp Dispatched when a user releases the pointing device button over an InteractiveObject instance.flash.events.MouseEvent.MIDDLE_MOUSE_UPflash.events.MouseEvent Dispatched when a user releases the pointing device button over an InteractiveObject instance. middleMouseDown Dispatched when a user presses the middle pointing device button over an InteractiveObject instance.flash.events.MouseEvent.MIDDLE_MOUSE_DOWNflash.events.MouseEvent Dispatched when a user presses the middle pointing device button over an InteractiveObject instance. middleClick Dispatched when a user presses and releases the middle button of the user's pointing device over the same InteractiveObject.flash.events.MouseEvent.MIDDLE_CLICKflash.events.MouseEvent Dispatched when a user presses and releases the middle button of the user's pointing device over the same InteractiveObject. For a middleClick event to occur, it must always follow this series of events in the order of occurrence: middleMouseDown event, then middleMouseUp. The target object must be identical for both of these events; otherwise the middleClick event does not occur. Any number of other mouse events can occur at any time between the middleMouseDown or middleMouseUp events; the middleClick event still occurs. gestureSwipe Dispatched when the user performs a swipe gesture at a point of contact with an InteractiveObject instance (such as touching three fingers to a screen and then moving them in parallel over a display object on a mobile phone or tablet with a touch screen).flash.events.TransformGestureEvent.GESTURE_SWIPEflash.events.TransformGestureEvent Dispatched when the user performs a swipe gesture at a point of contact with an InteractiveObject instance (such as touching three fingers to a screen and then moving them in parallel over a display object on a mobile phone or tablet with a touch screen). Moving several fingers in parallel is a common swipe gesture, but each device and operating system can have its own requirements for a swipe. Some devices might also interpret this contact as a combination of several mouse events, as well.

Specifically, if a user moves a finger over an InteractiveObject, and then moves the fingers together, the InteractiveObject instance can dispatch a rollOver event and a rollOut event (among others), in addition to the gestureSwipe event, or all if the current environment supports it. Choose how you want to handle the user interaction. If you choose to handle the rollOver event, then the same event handler will run on a touch-enabled device and a mouse enabled device. However, if you choose to handle the gestureSwipe event, you can design your event handler to respond to the specific needs of a touch-enabled environment and provide users with a richer touch-enabled experience. You can also handle both events, separately, to provide a different response for a touch event than a mouse event.

When handling the properties of the event object, note that the localX and localY properties are set to the primary point of contact. The offsetX and offsetY properties are the distance to the point of contact where the swipe gesture is complete.

Note: While some devices using the Mac OS operating system can interpret a four-finger swipe, this API only supports a three-finger swipe.

The following example shows event handling for the GESTURE_SWIPE events. While the user performs a swipe gesture on the touch-enabled device, myTextField populates with the phase all, which is the only phase for swipe events. Multitouch.inputMode = MultitouchInputMode.GESTURE; var mySprite = new Sprite(); mySprite.addEventListener(TransformGestureEvent.GESTURE_SWIPE , onSwipe); mySprite.graphics.beginFill(0x336699); mySprite.graphics.drawRect(0, 0, 100, 80); var myTextField = new TextField(); myTextField.y = 200; addChild(mySprite); addChild(myTextField); function onSwipe(evt:TransformGestureEvent):void { if (evt.offsetX == 1 ) { myTextField.text = "right"; } if (evt.offsetY == -1) { myTextField.text = "up"; } myTextField.text = evt.phase; }
rollOver eventtouchOver eventflash.ui.Multitouch
gestureZoom Dispatched when the user performs a zoom gesture at a point of contact with an InteractiveObject instance (such as touching two fingers to a screen and then quickly spreading the fingers apart over a display object on a mobile phone or tablet with a touch screen).flash.events.TransformGestureEvent.GESTURE_ZOOMflash.events.TransformGestureEvent Dispatched when the user performs a zoom gesture at a point of contact with an InteractiveObject instance (such as touching two fingers to a screen and then quickly spreading the fingers apart over a display object on a mobile phone or tablet with a touch screen). Moving fingers apart is a common zoom gesture, but each device and operating system can have its own requirements to indicate zoom. Some devices might also interpret this contact as a combination of several mouse events, as well.

Specifically, if a user moves a finger over an InteractiveObject, and then moves the fingers apart, the InteractiveObject instance can dispatch a mouseOver event and a click event (among others), in addition to the gestureZoom event, or all if the current environment supports it. Choose how you want to handle the user interaction. Use the flash.ui.Multitouch class to manage touch event handling (enable touch gesture event handling, simple touch point event handling, or disable touch events so only mouse events are dispatched). If you choose to handle the mouseOver event, then the same event handler will run on a touch-enabled device and a mouse enabled device. However, if you choose to handle the gestureZoom event, you can design your event handler to respond to the specific needs of a touch-enabled environment and provide users with a richer touch-enabled experience. You can also handle both events, separately, to provide a different response for a touch event than a mouse event.

When handling the properties of the event object, note that the localX and localY properties are set to the primary point of contact. The offsetX and offsetY properties are the distance to the point of contact where the zoom gesture is complete.

Note: See the Multitouch class for environment compatibility information.

The following example shows event handling for the GESTURE_ZOOM events. While the user performs a zoom gesture on the touch-enabled device, myTextField populates with the current phase. Multitouch.inputMode = MultitouchInputMode.GESTURE; var mySprite = new Sprite(); mySprite.addEventListener(TransformGestureEvent.GESTURE_ZOOM , onZoom); mySprite.graphics.beginFill(0x336699); mySprite.graphics.drawRect(0, 0, 100, 80); var myTextField = new TextField(); myTextField.y = 200; addChild(mySprite); addChild(myTextField); function onZoom(evt:TransformGestureEvent):void { evt.target.scaleX++; if (evt.phase==GesturePhase.BEGIN) { myTextField.text = "Begin"; } if (evt.phase==GesturePhase.UPDATE) { myTextField.text = "Update"; } if (evt.phase==GesturePhase.END) { myTextField.text = "End"; } }
mouseOver eventtouchOver eventflash.ui.Multitouch
gestureRotate Dispatched when the user performs a rotation gesture at a point of contact with an InteractiveObject instance (such as touching two fingers and rotating them over a display object on a mobile phone or tablet with a touch screen).flash.events.TransformGestureEvent.GESTURE_ROTATEflash.events.TransformGestureEvent Dispatched when the user performs a rotation gesture at a point of contact with an InteractiveObject instance (such as touching two fingers and rotating them over a display object on a mobile phone or tablet with a touch screen). Two-finger rotation is a common rotation gesture, but each device and operating system can have its own requirements to indicate rotation. Some devices might also interpret this contact as a combination of several mouse events, as well.

Specifically, if a user moves a finger over an InteractiveObject, the InteractiveObject instance can dispatch a mouseOver event and a click event (among others), in addition to the gestureRotate event, or all if the current environment supports it. Choose how you want to handle the user interaction. Use the flash.ui.Multitouch class to manage touch event handling (enable touch gesture event handling, simple touch point event handling, or disable touch events so only mouse events are dispatched). If you choose to handle the mouseOver event, then the same event handler will run on a touch-enabled device and a mouse enabled device. However, if you choose to handle the gestureRotate event, you can design your event handler to respond to the specific needs of a touch-enabled environment and provide users with a richer touch-enabled experience. You can also handle both events, separately, to provide a different response for a touch event than a mouse event.

When handling the properties of the event object, note that the localX and localY properties are set to the primary point of contact. The offsetX and offsetY properties are the distance to the point of contact where the rotation gesture is complete.

Note: See the Multitouch class for environment compatibility information.

The following example shows event handling for the GESTURE_ROTATE events. While the user performs a rotation gesture on the touch-enabled device, mySprite rotates and myTextField populates with the current phase. Multitouch.inputMode = MultitouchInputMode.GESTURE; var mySprite = new Sprite(); mySprite.addEventListener(TransformGestureEvent.GESTURE_ROTATE , onRotate ); mySprite.graphics.beginFill(0x336699); mySprite.graphics.drawRect(0, 0, 100, 80); var myTextField = new TextField(); myTextField.y = 200; addChild(mySprite); addChild(myTextField); function onRotate(evt:TransformGestureEvent):void { evt.target.rotation -= 45; if (evt.phase==GesturePhase.BEGIN) { myTextField.text = "Begin"; } if (evt.phase==GesturePhase.UPDATE) { myTextField.text = "Update"; } if (evt.phase==GesturePhase.END) { myTextField.text = "End"; } }
mouseOver eventtouchOver eventflash.ui.Multitouch
gesturePressAndTap Dispatched when the user creates a point of contact with an InteractiveObject instance, then taps on a touch-enabled device (such as placing several fingers over a display object to open a menu and then taps one finger to select a menu item on a mobile phone or tablet with a touch screen).flash.events.PressAndTapGestureEvent.GESTURE_PRESS_AND_TAPflash.events.PressAndTapGestureEvent Dispatched when the user creates a point of contact with an InteractiveObject instance, then taps on a touch-enabled device (such as placing several fingers over a display object to open a menu and then taps one finger to select a menu item on a mobile phone or tablet with a touch screen). Some devices might also interpret this contact as a combination of several mouse events, as well.

Specifically, if a user moves a finger over an InteractiveObject, and then provides a secondary tap, the InteractiveObject instance can dispatch a mouseOver event and a click event (among others) as well as the gesturePressAndTap event, or all if the current environment supports it. Choose how you want to handle the user interaction. Use the flash.ui.Multitouch class to manage touch event handling (enable touch gesture event handling, simple touch point event handling, or disable touch events so only mouse events are dispatched). If you choose to handle the mouseOver event, then the same event handler will run on a touch-enabled device and a mouse enabled device. However, if you choose to handle the gesturePressAndTap event, you can design your event handler to respond to the specific needs of a touch-enabled environment and provide users with a richer touch-enabled experience. You can also handle both events, separately, to provide a different response for a touch event than a mouse event.

When handling the properties of the event object, note that the localX and localY properties are set to the primary point of contact (the "push"). The offsetX and offsetY properties are the distance to the secondary point of contact (the "tap").

mouseOver eventtouchOver eventflash.ui.Multitouch
gesturePan Dispatched when the user moves a point of contact over the InteractiveObject instance on a touch-enabled device (such as moving a finger from left to right over a display object on a mobile phone or tablet with a touch screen).flash.events.TransformGestureEvent.GESTURE_PANflash.events.TransformGestureEvent Dispatched when the user moves a point of contact over the InteractiveObject instance on a touch-enabled device (such as moving a finger from left to right over a display object on a mobile phone or tablet with a touch screen). Some devices might also interpret this contact as a mouseOver event and as a touchOver event.

Specifically, if a user moves a finger over an InteractiveObject, the InteractiveObject instance can dispatch a mouseOver event or a touchOver event or a gesturePan event, or all if the current environment supports it. Choose how you want to handle the user interaction. Use the flash.ui.Multitouch class to manage touch event handling (enable touch gesture event handling, simple touch point event handling, or disable touch events so only mouse events are dispatched). If you choose to handle the mouseOver event, then the same event handler will run on a touch-enabled device and a mouse enabled device. However, if you choose to handle the gesturePan event, you can design your event handler to respond to the specific needs of a touch-enabled environment and provide users with a richer touch-enabled experience. You can also handle both events, separately, to provide a different response for a touch event than a mouse event.

Note: See the Multitouch class for environment compatibility information.

The following example shows event handling for the GESTURE_PAN events. While the user performs a pan gesture on the touch-enabled device, myTextField populates with the current phase. Multitouch.inputMode = MultitouchInputMode.GESTURE; var mySprite = new Sprite(); mySprite.addEventListener(TransformGestureEvent.GESTURE_PAN , onPan); mySprite.graphics.beginFill(0x336699); mySprite.graphics.drawRect(0, 0, 100, 80); var myTextField = new TextField(); myTextField.y = 200; addChild(mySprite); addChild(myTextField); function onPan(evt:TransformGestureEvent):void { evt.target.localX++; if (evt.phase==GesturePhase.BEGIN) { myTextField.text = "Begin"; } if (evt.phase==GesturePhase.UPDATE) { myTextField.text = "Update"; } if (evt.phase==GesturePhase.END) { myTextField.text = "End"; } }
mouseOver eventtouchOver eventflash.ui.Multitouch
gestureTwoFingerTap Dispatched when the user presses two points of contact over the same InteractiveObject instance on a touch-enabled device (such as presses and releases two fingers over a display object on a mobile phone or tablet with a touch screen).flash.events.GestureEvent.GESTURE_TWO_FINGER_TAPflash.events.GestureEvent Dispatched when the user presses two points of contact over the same InteractiveObject instance on a touch-enabled device (such as presses and releases two fingers over a display object on a mobile phone or tablet with a touch screen). Some devices might also interpret this contact as a doubleClick event.

Specifically, if a user taps two fingers over an InteractiveObject, the InteractiveObject instance can dispatch a doubleClick event or a gestureTwoFingerTap event, or both if the current environment supports it. Choose how you want to handle the user interaction. Use the flash.ui.Multitouch class to manage touch event handling (enable touch gesture event handling, simple touch point event handling, or disable touch events so only mouse events are dispatched). If you choose to handle the doubleClick event, then the same event handler will run on a touch-enabled device and a mouse enabled device. However, if you choose to handle the gestureTwoFingerTap event, you can design your event handler to respond to the specific needs of a touch-enabled environment and provide users with a richer touch-enabled experience. You can also handle both events, separately, to provide a different response for a touch event than a mouse event.

Note: See the Multitouch class for environment compatibility information.

doubleClick eventflash.ui.Multitouch
touchTap Dispatched when the user lifts the point of contact over the same InteractiveObject instance on which the contact was initiated on a touch-enabled device (such as presses and releases a finger from a single point over a display object on a mobile phone or tablet with a touch screen).flash.events.TouchEvent.TOUCH_TAPflash.events.TouchEvent Dispatched when the user lifts the point of contact over the same InteractiveObject instance on which the contact was initiated on a touch-enabled device (such as presses and releases a finger from a single point over a display object on a mobile phone or tablet with a touch screen). Some devices might also interpret this contact as a click event.

Specifically, if a user taps a finger over an InteractiveObject, the InteractiveObject instance can dispatch a click event or a touchTap event, or both if the current environment supports it. Choose how you want to handle the user interaction. Use the flash.ui.Multitouch class to manage touch event handling (enable touch gesture event handling, simple touch point event handling, or disable touch events so only mouse events are dispatched). If you choose to handle the click event, then the same event handler will run on a touch-enabled device and a mouse enabled device. However, if you choose to handle the touchTap event, you can design your event handler to respond to the specific needs of a touch-enabled environment and provide users with a richer touch-enabled experience. You can also handle both events, separately, to provide a different response for a touch event than a mouse event.

Note: See the Multitouch class for environment compatibility information.

The following example displays a message when the square drawn on mySprite is tapped on a touch-enabled screen: Multitouch.inputMode=MultitouchInputMode.TOUCH_POINT; var mySprite:Sprite = new Sprite(); var myTextField:TextField = new TextField(); mySprite.graphics.beginFill(0x336699); mySprite.graphics.drawRect(0,0,40,40); addChild(mySprite); mySprite.addEventListener(TouchEvent.TOUCH_TAP, taphandler); function taphandler(e:TouchEvent): void { myTextField.text = "I've been tapped"; myTextField.y = 50; addChild(myTextField); }
click eventflash.ui.Multitouch
touchRollOver Dispatched when the user moves the point of contact over an InteractiveObject instance on a touch-enabled device (such as drags a finger from a point outside a display object to a point over a display object on a mobile phone or tablet with a touch screen).flash.events.TouchEvent.TOUCH_ROLL_OVERflash.events.TouchEvent Dispatched when the user moves the point of contact over an InteractiveObject instance on a touch-enabled device (such as drags a finger from a point outside a display object to a point over a display object on a mobile phone or tablet with a touch screen). Some devices might also interpret this contact as a rollOver event.

Specifically, if a user moves a finger over an InteractiveObject, the InteractiveObject instance can dispatch a rollOver event or a touchRollOver event, or both if the current environment supports it. Choose how you want to handle the user interaction. Use the flash.ui.Multitouch class to manage touch event handling (enable touch gesture event handling, simple touch point event handling, or disable touch events so only mouse events are dispatched). If you choose to handle the rollOver event, then the same event handler will run on a touch-enabled device and a mouse enabled device. However, if you choose to handle the touchRollOver event, you can design your event handler to respond to the specific needs of a touch-enabled environment and provide users with a richer touch-enabled experience. You can also handle both events, separately, to provide a different response for a touch event than a mouse event.

Note: See the Multitouch class for environment compatibility information.

rollOver eventflash.ui.Multitouch
touchRollOut Dispatched when the user moves the point of contact away from an InteractiveObject instance on a touch-enabled device (such as drags a finger from over a display object to a point outside the display object on a mobile phone or tablet with a touch screen).flash.events.TouchEvent.TOUCH_ROLL_OUTflash.events.TouchEvent Dispatched when the user moves the point of contact away from an InteractiveObject instance on a touch-enabled device (such as drags a finger from over a display object to a point outside the display object on a mobile phone or tablet with a touch screen). Some devices might also interpret this contact as a rollOut event.

Specifically, if a user moves a finger over an InteractiveObject, the InteractiveObject instance can dispatch a rollOut event or a touchRollOut event, or both if the current environment supports it. Choose how you want to handle the user interaction. Use the flash.ui.Multitouch class to manage touch event handling (enable touch gesture event handling, simple touch point event handling, or disable touch events so only mouse events are dispatched). If you choose to handle the rollOut event, then the same event handler will run on a touch-enabled device and a mouse enabled device. However, if you choose to handle the touchRollOut event, you can design your event handler to respond to the specific needs of a touch-enabled environment and provide users with a richer touch-enabled experience. You can also handle both events, separately, to provide a different response for a touch event than a mouse event.

Note: See the Multitouch class for environment compatibility information.

rollOut eventflash.ui.Multitouch
touchOver Dispatched when the user moves the point of contact over an InteractiveObject instance on a touch-enabled device (such as drags a finger from a point outside a display object to a point over a display object on a mobile phone or tablet with a touch screen).flash.events.TouchEvent.TOUCH_OVERflash.events.TouchEvent Dispatched when the user moves the point of contact over an InteractiveObject instance on a touch-enabled device (such as drags a finger from a point outside a display object to a point over a display object on a mobile phone or tablet with a touch screen). Some devices might also interpret this contact as a mouseOver event.

Specifically, if a user moves a finger over an InteractiveObject, the InteractiveObject instance can dispatch a mouseOver event or a touchOver event, or both if the current environment supports it. Choose how you want to handle the user interaction. Use the flash.ui.Multitouch class to manage touch event handling (enable touch gesture event handling, simple touch point event handling, or disable touch events so only mouse events are dispatched). If you choose to handle the mouseOver event, then the same event handler will run on a touch-enabled device and a mouse enabled device. However, if you choose to handle the touchOver event, you can design your event handler to respond to the specific needs of a touch-enabled environment and provide users with a richer touch-enabled experience. You can also handle both events, separately, to provide a different response for a touch event than a mouse event.

Note: See the Multitouch class for environment compatibility information.

mouseOver eventflash.ui.Multitouch
touchOut Dispatched when the user moves the point of contact away from InteractiveObject instance on a touch-enabled device (such as drags a finger from one display object to another on a mobile phone or tablet with a touch screen).flash.events.TouchEvent.TOUCH_OUTflash.events.TouchEvent Dispatched when the user moves the point of contact away from InteractiveObject instance on a touch-enabled device (such as drags a finger from one display object to another on a mobile phone or tablet with a touch screen). Some devices might also interpret this contact as a mouseOut event.

Specifically, if a user moves a finger across a touch screen, the InteractiveObject instance can dispatch a mouseOut event or a touchOut event, or both if the current environment supports it. Choose how you want to handle the user interaction. Use the flash.ui.Multitouch class to manage touch event handling (enable touch gesture event handling, simple touch point event handling, or disable touch events so only mouse events are dispatched). If you choose to handle the mouseOut event, then the same event handler will run on a touch-enabled device and a mouse enabled device. However, if you choose to handle the touchOut event, you can design your event handler to respond to the specific needs of a touch-enabled environment and provide users with a richer touch-enabled experience. You can also handle both events, separately, to provide a different response for a touch event than a mouse event.

Note: See the Multitouch class for environment compatibility information.

mouseOut eventflash.ui.Multitouch
touchMove Dispatched when the user moves the point of contact with a touch-enabled device (such as drags a finger across a mobile phone or tablet with a touch screen).flash.events.TouchEvent.TOUCH_MOVEflash.events.TouchEvent Dispatched when the user moves the point of contact with a touch-enabled device (such as drags a finger across a mobile phone or tablet with a touch screen). Some devices might also interpret this contact as a mouseMove event.

Specifically, if a user moves a finger across a touch screen, the InteractiveObject instance can dispatch a mouseMove event or a touchMove event, or both if the current environment supports it. Choose how you want to handle the user interaction. Use the flash.ui.Multitouch class to manage touch event handling (enable touch gesture event handling, simple touch point event handling, or disable touch events so only mouse events are dispatched). If you choose to handle the mouseMove event, then the same event handler will run on a touch-enabled device and a mouse enabled device. However, if you choose to handle the touchMove event, you can design your event handler to respond to the specific needs of a touch-enabled environment and provide users with a richer touch-enabled experience. You can also handle both events, separately, to provide a different response for a touch event than a mouse event.

Note: See the Multitouch class for environment compatibility information.

The following example shows event handling for the TOUCH_BEGIN, TOUCH_MOVE, and TOUCH_END events. While the point of contact moves across the screen (onTouchMove), the x-coordinate relative to the stage is traced to output. For the Sprite.startTouchDrag parameters in the onTouchBegin function, the value for touchPointID is the value assigned to the event object. The bounds parameter is the rectangle defining the boundaries of the parent display object (bg is a display object containing MySprite). Multitouch.inputMode = MultitouchInputMode.TOUCH_POINT; MySprite.addEventListener(TouchEvent.TOUCH_BEGIN, onTouchBegin); MySprite.addEventListener(TouchEvent.TOUCH_MOVE, onTouchMove); MySprite.addEventListener(TouchEvent.TOUCH_END, onTouchEnd); function onTouchBegin(eBegin:TouchEvent) { eBegin.target.startTouchDrag(eBegin.touchPointID, false, bg.getRect(this)); trace("touch begin"); } function onTouchMove(eMove:TouchEvent) { trace(eMove.stageX); } function onTouchEnd(eEnd:TouchEvent) { eEnd.target.stopTouchDrag(eEnd.touchPointID); trace("touch end"); }
mouseMove eventflash.ui.Multitouch
touchEnd Dispatched when the user removes contact with a touch-enabled device (such as lifts a finger off a mobile phone or tablet with a touch screen).flash.events.TouchEvent.TOUCH_ENDflash.events.TouchEvent Dispatched when the user removes contact with a touch-enabled device (such as lifts a finger off a mobile phone or tablet with a touch screen). Some devices might also interpret this contact as a mouseUp event.

Specifically, if a user lifts a finger from a touch screen, the InteractiveObject instance can dispatch a mouseUp event or a touchEnd event, or both if the current environment supports it. Choose how you want to handle the user interaction. Use the flash.ui.Multitouch class to manage touch event handling (enable touch gesture event handling, simple touch point event handling, or disable touch events so only mouse events are dispatched). If you choose to handle the mouseUp event, then the same event handler will run on a touch-enabled device and a mouse enabled device. However, if you choose to handle the touchEnd event, you can design your event handler to respond to the specific needs of a touch-enabled environment and provide users with a richer touch-enabled experience. You can also handle both events, separately, to provide a different response for a touch event than a mouse event.

Note: See the Multitouch class for environment compatibility information.

The following example shows event handling for the TOUCH_BEGIN, TOUCH_MOVE, and TOUCH_END events. While the point of contact moves across the screen (onTouchMove), the x-coordinate relative to the stage is traced to output. For the Sprite.startTouchDrag parameters in the onTouchBegin function, the value for touchPointID is the value assigned to the event object. The bounds parameter is the rectangle defining the boundaries of the parent display object (bg is a display object containing MySprite). Multitouch.inputMode = MultitouchInputMode.TOUCH_POINT; MySprite.addEventListener(TouchEvent.TOUCH_BEGIN, onTouchBegin); MySprite.addEventListener(TouchEvent.TOUCH_MOVE, onTouchMove); MySprite.addEventListener(TouchEvent.TOUCH_END, onTouchEnd); function onTouchBegin(eBegin:TouchEvent) { eBegin.target.startTouchDrag(eBegin.touchPointID, false, bg.getRect(this)); trace("touch begin"); } function onTouchMove(eMove:TouchEvent) { trace(eMove.stageX); } function onTouchEnd(eEnd:TouchEvent) { eEnd.target.stopTouchDrag(eEnd.touchPointID); trace("touch end"); }
mouseUp eventflash.ui.Multitouch
touchBegin Dispatched when the user first contacts a touch-enabled device (such as touches a finger to a mobile phone or tablet with a touch screen).flash.events.TouchEvent.TOUCH_BEGINflash.events.TouchEvent Dispatched when the user first contacts a touch-enabled device (such as touches a finger to a mobile phone or tablet with a touch screen). Some devices might also interpret this contact as a mouseDown event.

Specifically, if a user touches a finger to a touch screen, the InteractiveObject instance can dispatch a mouseDown event or a touchBegin event, or both if the current environment supports it. Choose how you want to handle the user interaction. Use the flash.ui.Multitouch class to manage touch event handling (enable touch gesture event handling, simple touch point event handling, or disable touch events so only mouse events are dispatched). If you choose to handle the mouseDown event, then the same event handler will run on a touch-enabled device and a mouse enabled device. However, if you choose to handle the touchBegin event, you can design your event handler to respond to the specific needs of a touch-enabled environment and provide users with a richer touch-enabled experience. You can also handle both events, separately, to provide a different response for a touch event than a mouse event.

Note: See the Multitouch class for environment compatibility information.

The following example shows event handling for the TOUCH_BEGIN, TOUCH_MOVE, and TOUCH_END events. While the point of contact moves across the screen (onTouchMove), the x-coordinate relative to the stage is traced to output. For the Sprite.startTouchDrag parameters in the onTouchBegin function, the value for touchPointID is the value assigned to the event object. The bounds parameter is the rectangle defining the boundaries of the parent display object (bg is a display object containing MySprite). Multitouch.inputMode = MultitouchInputMode.TOUCH_POINT; MySprite.addEventListener(TouchEvent.TOUCH_BEGIN, onTouchBegin); MySprite.addEventListener(TouchEvent.TOUCH_MOVE, onTouchMove); MySprite.addEventListener(TouchEvent.TOUCH_END, onTouchEnd); function onTouchBegin(eBegin:TouchEvent) { eBegin.target.startTouchDrag(eBegin.touchPointID, false, bg.getRect(this)); trace("touch begin"); } function onTouchMove(eMove:TouchEvent) { trace(eMove.stageX); } function onTouchEnd(eEnd:TouchEvent) { eEnd.target.stopTouchDrag(eEnd.touchPointID); trace("touch end"); }
mouseDown eventflash.ui.Multitouch
rollOver Dispatched when the user moves a pointing device over an InteractiveObject instance.flash.events.MouseEvent.ROLL_OVERflash.events.MouseEvent Dispatched when the user moves a pointing device over an InteractiveObject instance. The event target is the object under the pointing device or a parent of that object. The relatedObject is the object that was previously under the pointing device. The rollOver events are dispatched consecutively down the parent chain of the object, starting with the highest parent that is neither the root nor an ancestor of the relatedObject and ending with the object.

The purpose of the rollOver event is to simplify the coding of rollout behaviors for display object containers with children. When the mouse enters the area of a display object or the area of any of its children from an object that is not one of its children, the display object dispatches the rollOver event. This is different behavior than that of the mouseOver event, which is dispatched each time the mouse enters the area of any child object of the display object container, even if the mouse was already over another child object of the display object container.

rollOut Dispatched when the user moves a pointing device away from an InteractiveObject instance.flash.events.MouseEvent.ROLL_OUTflash.events.MouseEvent Dispatched when the user moves a pointing device away from an InteractiveObject instance. The event target is the object previously under the pointing device or a parent of that object. The relatedObject is the object that the pointing device has moved to. The rollOut events are dispatched consecutively up the parent chain of the object, starting with the object and ending with the highest parent that is neither the root nor an ancestor of the relatedObject.

The purpose of the rollOut event is to simplify the coding of rollover behaviors for display object containers with children. When the mouse leaves the area of a display object or the area of any of its children to go to an object that is not one of its children, the display object dispatches the rollOut event. This is different behavior than that of the mouseOut event, which is dispatched each time the mouse leaves the area of any child object of the display object container, even if the mouse remains over another child object of the display object container.

mouseWheel Dispatched when a mouse wheel is spun over an InteractiveObject instance.flash.events.MouseEvent.MOUSE_WHEELflash.events.MouseEvent Dispatched when a mouse wheel is spun over an InteractiveObject instance. If the target is a text field, the text scrolls as the default behavior. Only available on Microsoft Windows operating systems. mouseUp Dispatched when a user releases the pointing device button over an InteractiveObject instance.flash.events.MouseEvent.MOUSE_UPflash.events.MouseEvent Dispatched when a user releases the pointing device button over an InteractiveObject instance. If the target is a SimpleButton instance, the object displays the upState display object. If the target is a selectable text field, the text field ends selection as the default behavior. mouseOver Dispatched when the user moves a pointing device over an InteractiveObject instance.flash.events.MouseEvent.MOUSE_OVERflash.events.MouseEvent Dispatched when the user moves a pointing device over an InteractiveObject instance. The relatedObject is the object that was previously under the pointing device. If the target is a SimpleButton instance, the object displays the overState or upState display object, depending on whether the mouse button is down, as the default behavior.

The mouseOver event is dispatched each time the mouse enters the area of any child object of the display object container, even if the mouse was already over another child object of the display object container. This is different behavior than the purpose of the rollOver event, which is to simplify the coding of rollout behaviors for display object containers with children. When the mouse enters the area of a display object or the area of any of its children from an object that is not one of its children, the display object dispatches the rollOver event. The rollOver events are dispatched consecutively down the parent chain of the object, starting with the highest parent that is neither the root nor an ancestor of the relatedObject and ending with the object.

mouseOut Dispatched when the user moves a pointing device away from an InteractiveObject instance.flash.events.MouseEvent.MOUSE_OUTflash.events.MouseEvent Dispatched when the user moves a pointing device away from an InteractiveObject instance. The event target is the object previously under the pointing device. The relatedObject is the object the pointing device has moved to. If the target is a SimpleButton instance, the button displays the upState display object as the default behavior.

The mouseOut event is dispatched each time the mouse leaves the area of any child object of the display object container, even if the mouse remains over another child object of the display object container. This is different behavior than the purpose of the rollOut event, which is to simplify the coding of rollover behaviors for display object containers with children. When the mouse leaves the area of a display object or the area of any of its children to go to an object that is not one of its children, the display object dispatches the rollOut event.The rollOut events are dispatched consecutively up the parent chain of the object, starting with the object and ending with the highest parent that is neither the root nor an ancestor of the relatedObject.

mouseMove Dispatched when a user moves the pointing device while it is over an InteractiveObject.flash.events.MouseEvent.MOUSE_MOVEflash.events.MouseEvent Dispatched when a user moves the pointing device while it is over an InteractiveObject. If the target is a text field that the user is selecting, the selection is updated as the default behavior. mouseDown Dispatched when a user presses the pointing device button over an InteractiveObject instance.flash.events.MouseEvent.MOUSE_DOWNflash.events.MouseEvent Dispatched when a user presses the pointing device button over an InteractiveObject instance. If the target is a SimpleButton instance, the SimpleButton instance displays the downState display object as the default behavior. If the target is a selectable text field, the text field begins selection as the default behavior. doubleClick Dispatched when a user presses and releases the main button of a pointing device twice in rapid succession over the same InteractiveObject when that object's doubleClickEnabled flag is set to true.flash.events.MouseEvent.DOUBLE_CLICKflash.events.MouseEvent Dispatched when a user presses and releases the main button of a pointing device twice in rapid succession over the same InteractiveObject when that object's doubleClickEnabled flag is set to true. For a doubleClick event to occur, it must immediately follow the following series of events: mouseDown, mouseUp, click, mouseDown, mouseUp. All of these events must share the same target as the doubleClick event. The second click, represented by the second mouseDown and mouseUp events, must occur within a specific period of time after the click event. The allowable length of this period varies by operating system and can often be configured by the user. If the target is a selectable text field, the word under the pointer is selected as the default behavior. If the target InteractiveObject does not have its doubleClickEnabled flag set to true it receives two click events.

The doubleClickEnabled property defaults to false.

The double-click text selection behavior of a TextField object is not related to the doubleClick event. Use TextField.doubleClickEnabled to control TextField selections.

doubleClickEnabled
click Dispatched when a user presses and releases the main button of the user's pointing device over the same InteractiveObject.flash.events.MouseEvent.CLICKflash.events.MouseEvent Dispatched when a user presses and releases the main button of the user's pointing device over the same InteractiveObject. For a click event to occur, it must always follow this series of events in the order of occurrence: mouseDown event, then mouseUp. The target object must be identical for both of these events; otherwise the click event does not occur. Any number of other mouse events can occur at any time between the mouseDown or mouseUp events; the click event still occurs. mouseFocusChange Dispatched when the user attempts to change focus by using a pointer device.flash.events.FocusEvent.MOUSE_FOCUS_CHANGEflash.events.FocusEvent Dispatched when the user attempts to change focus by using a pointer device. The default behavior of this event is to change the focus and dispatch the corresponding focusIn and focusOut events.

This event is dispatched to the object that currently has focus. The related object for this event is the InteractiveObject instance that receives focus if you do not prevent the default behavior. You can prevent the change in focus by calling preventDefault() in an event listener that is properly registered with the target object. The shiftKey property is not used. Focus changes and focusIn and focusOut events are dispatched by default.

keyFocusChange Dispatched when the user attempts to change focus by using keyboard navigation.flash.events.FocusEvent.KEY_FOCUS_CHANGEflash.events.FocusEvent Dispatched when the user attempts to change focus by using keyboard navigation. The default behavior of this event is to change the focus and dispatch the corresponding focusIn and focusOut events.

This event is dispatched to the object that currently has focus. The related object for this event is the InteractiveObject instance that receives focus if you do not prevent the default behavior. You can prevent the change in focus by calling the preventDefault() method in an event listener that is properly registered with the target object. Focus changes and focusIn and focusOut events are dispatched by default.

focusOut Dispatched after a display object loses focus.flash.events.FocusEvent.FOCUS_OUTflash.events.FocusEvent Dispatched after a display object loses focus. This happens when a user highlights a different object with a pointing device or keyboard navigation. The object that loses focus is called the target object of this event, while the corresponding InteractiveObject instance that receives focus is called the related object. A reference to the related object is stored in the target object's relatedObject property. The shiftKey property is not used. This event precedes the dispatch of the focusIn event by the related object. focusIn Dispatched after a display object gains focus.flash.events.FocusEvent.FOCUS_INflash.events.FocusEvent Dispatched after a display object gains focus. This situation happens when a user highlights the object with a pointing device or keyboard navigation. The recipient of such focus is called the target object of this event, while the corresponding InteractiveObject instance that lost focus because of this change is called the related object. A reference to the related object is stored in the receiving object's relatedObject property. The shiftKey property is not used. This event follows the dispatch of the previous object's focusOut event. selectAll Dispatched when the user activates the platform-specific accelerator key combination for a select all operation or selects 'Select All' from the text context menu.flash.events.Event.SELECT_ALLflash.events.Event Dispatched when the user activates the platform-specific accelerator key combination for a select all operation or selects 'Select All' from the text context menu. This event is dispatched to the object that currently has focus. If the object that currently has focus is a TextField, the default behavior of this event is to cause all the contents of the text field to be selected. paste Dispatched when the user activates the platform-specific accelerator key combination for a paste operation or selects 'Paste' from the text context menu.flash.events.Event.PASTEflash.events.Event Dispatched when the user activates the platform-specific accelerator key combination for a paste operation or selects 'Paste' from the text context menu. This event is dispatched to the object that currently has focus. If the object that currently has focus is a TextField, the default behavior of this event is to cause the contents of the clipboard to be pasted into the text field at the current insertion point replacing any currently selected text in the text field. cut Dispatched when the user activates the platform-specific accelerator key combination for a cut operation or selects 'Cut' from the text context menu.flash.events.Event.CUTflash.events.Event Dispatched when the user activates the platform-specific accelerator key combination for a cut operation or selects 'Cut' from the text context menu. This event is dispatched to the object that currently has focus. If the object that currently has focus is a TextField, the default behavior of this event is to cause any currently selected text in the text field to be cut to the clipboard. copy Dispatched when the user activates the platform-specific accelerator key combination for a copy operation or selects 'Copy' from the text context menu.flash.events.Event.COPYflash.events.Event Dispatched when the user activates the platform-specific accelerator key combination for a copy operation or selects 'Copy' from the text context menu. This event is dispatched to the object that currently has focus. If the object that currently has focus is a TextField, the default behavior of this event is to cause any currently selected text in the text field to be copied to the clipboard. clear Dispatched when the user selects 'Clear' (or 'Delete') from the text context menu.flash.events.Event.CLEARflash.events.Event Dispatched when the user selects 'Clear' (or 'Delete') from the text context menu. This event is dispatched to the object that currently has focus. If the object that currently has focus is a TextField, the default behavior of this event is to cause any currently selected text in the text field to be deleted. InteractiveObject Calling the new InteractiveObject() constructor throws an ArgumentError exception. Calling the new InteractiveObject() constructor throws an ArgumentError exception. You can, however, call constructors for the following subclasses of InteractiveObject:
  • new SimpleButton()
  • new TextField()
  • new Loader()
  • new Sprite()
  • new MovieClip()
requestSoftKeyboard Raises a virtual keyboard.A value of true means that the soft keyboard request was granted; false means that the soft keyboard was not raised. BooleanIf the current context supports it, show the keyboard. Raises a virtual keyboard.

Calling this method focuses the InteractiveObject instance and raises the soft keyboard, if necessary. The needsSoftKeyboard must also be true. A keyboard is not raised if a hardware keyboard is available, or if the client system does not support virtual keyboards.

Note: This method is not supported in AIR applications on iOS.

needsSoftKeyboard
accessibilityImplementation The current accessibility implementation (AccessibilityImplementation) for this InteractiveObject instance.flash.accessibility:AccessibilityImplementation The current accessibility implementation (AccessibilityImplementation) for this InteractiveObject instance. flash.accessibility.AccessibilityImplementationcontextMenu Specifies the context menu associated with this object.flash.display:NativeMenuThe context menu associated with this object Specifies the context menu associated with this object.

For content running in Flash Player, this property is a ContextMenu object. In the AIR runtime, the ContextMenu class extends the NativeMenu class, however Flash Player only supports the ContextMenu class, not the NativeMenu class.

Note: TextField objects always include a clipboard menu in the context menu. The clipboard menu contains Cut, Copy, Paste, Clear, and Select All commands. You cannot remove these commands from the context menu for TextField objects. For TextField objects, selecting these commands (or their keyboard equivalents) does not generate clear, copy, cut, paste, or selectAll events.

The following example shows how you can add a custom context menu item to a Sprite object by setting the Sprite's contextMenu property to a ContextMenu object. Example provided by ActionScriptExamples.com. var red_cmi:ContextMenuItem = new ContextMenuItem("red"); red_cmi.addEventListener(ContextMenuEvent.MENU_ITEM_SELECT, cmi_menuItemSelect); var cm:ContextMenu = new ContextMenu(); cm.customItems.push(red_cmi); cm.hideBuiltInItems(); var spr:Sprite = new Sprite(); spr.contextMenu = cm; spr.graphics.beginFill(0x000000); spr.graphics.drawRect(0, 0, 120, 90); spr.graphics.endFill(); spr.x = 10; spr.y = 10; addChild(spr); function cmi_menuItemSelect(evt:ContextMenuEvent):void { spr.graphics.clear(); spr.graphics.beginFill(0xFF0000); spr.graphics.drawRect(0, 0, 120, 90); spr.graphics.endFill(); }
doubleClickEnabled Specifies whether the object receives doubleClick events.BooleanWhether this object receives double click messages. Specifies whether the object receives doubleClick events. The default value is false, which means that by default an InteractiveObject instance does not receive doubleClick events. If the doubleClickEnabled property is set to true, the instance receives doubleClick events within its bounds. The mouseEnabled property of the InteractiveObject instance must also be set to true for the object to receive doubleClick events.

No event is dispatched by setting this property. You must use the addEventListener() method to add an event listener for the doubleClick event.

doubleClickmouseEnabledflash.display.DisplayObjectContainer.mouseChildren
focusRect Specifies whether this object displays a focus rectangle.Object Specifies whether this object displays a focus rectangle. It can take one of three values: true, false, or null. Values of true and false work as expected, specifying whether or not the focus rectangle appears. A value of null indicates that this object obeys the stageFocusRect property of the Stage. mouseEnabled Specifies whether this object receives mouse, or other user input, messages.Boolean Specifies whether this object receives mouse, or other user input, messages. The default value is true, which means that by default any InteractiveObject instance that is on the display list receives mouse events or other user input events. If mouseEnabled is set to false, the instance does not receive any mouse events (or other user input events like keyboard events). Any children of this instance on the display list are not affected. To change the mouseEnabled behavior for all children of an object on the display list, use flash.display.DisplayObjectContainer.mouseChildren.

No event is dispatched by setting this property. You must use the addEventListener() method to create interactive functionality.

flash.display.DisplayObjectContainer.mouseChildren
needsSoftKeyboard Specifies whether a virtual keyboard (an on-screen, software keyboard) should display when this InteractiveObject instance receives focus.Boolean Specifies whether a virtual keyboard (an on-screen, software keyboard) should display when this InteractiveObject instance receives focus.

By default, the value is false and focusing an InteractiveObject instance does not raise a soft keyboard. If the needsSoftKeyboard property is set to true, the runtime raises a soft keyboard when the InteractiveObject instance is ready to accept user input. An InteractiveObject instance is ready to accept user input after a programmatic call to set the Stage focus property or a user interaction, such as a "tap." If the client system has a hardware keyboard available or does not support virtual keyboards, then the soft keyboard is not raised.

The InteractiveObject instance dispatches softKeyboardActivating, softKeyboardActivate, and softKeyboardDeactivate events when the soft keyboard raises and lowers.

Note: This property is not supported in AIR applications on iOS.

softKeyboardActivatingsoftKeyboardActivatesoftKeyboardDeactivate
softKeyboardInputAreaOfInterest Defines the area that should remain on-screen when a soft keyboard is displayed.flash.geom:RectangleSets the area to be displayed on-screen when the soft keyboard opens. Defines the area that should remain on-screen when a soft keyboard is displayed.

If the needsSoftKeyboard property of this InteractiveObject is true, then the runtime adjusts the display as needed to keep the object in view while the user types. Ordinarily, the runtime uses the object bounds obtained from the DisplayObject.getBounds() method. You can specify a different area using this softKeyboardInputAreaOfInterest property.

Specify the softKeyboardInputAreaOfInterest in stage coordinates.

Note: On Android, the softKeyboardInputAreaOfInterest is not respected in landscape orientations.

flash.display.DisplayObject.getBounds()
tabEnabled Specifies whether this object is in the tab order.BooleanWhether this object is in the tab order. Specifies whether this object is in the tab order. If this object is in the tab order, the value is true; otherwise, the value is false. By default, the value is false, except for the following:
  • For a SimpleButton object, the value is true.
  • For a TextField object with type = "input", the value is true.
  • For a Sprite object or MovieClip object with buttonMode = true, the value is true.
tabIndex Specifies the tab ordering of objects in a SWF file.intThe tab index for this object. Specifies the tab ordering of objects in a SWF file. The tabIndex property is -1 by default, meaning no tab index is set for the object.

If any currently displayed object in the SWF file contains a tabIndex property, automatic tab ordering is disabled, and the tab ordering is calculated from the tabIndex properties of objects in the SWF file. The custom tab ordering includes only objects that have tabIndex properties.

The tabIndex property can be a non-negative integer. The objects are ordered according to their tabIndex properties, in ascending order. An object with a tabIndex value of 1 precedes an object with a tabIndex value of 2. Do not use the same tabIndex value for multiple objects.

The custom tab ordering that the tabIndex property defines is flat. This means that no attention is paid to the hierarchical relationships of objects in the SWF file. All objects in the SWF file with tabIndex properties are placed in the tab order, and the tab order is determined by the order of the tabIndex values.

Note: To set the tab order for TLFTextField instances, cast the display object child of the TLFTextField as an InteractiveObject, then set the tabIndex property. For example:

	 InteractiveObject(tlfInstance.getChildAt(1)).tabIndex = 3;
	 
To reverse the tab order from the default setting for three instances of a TLFTextField object (tlfInstance1, tlfInstance2 and tlfInstance3), use:
	 InteractiveObject(tlfInstance1.getChildAt(1)).tabIndex = 3;
	 InteractiveObject(tlfInstance2.getChildAt(1)).tabIndex = 2;
	 InteractiveObject(tlfInstance3.getChildAt(1)).tabIndex = 1;
	 

GraphicsTrianglePath Defines an ordered set of triangles that can be rendered using either (u,v) fill coordinates or a normal fill.flash.display:IGraphicsPathflash.display:IGraphicsDataObject Defines an ordered set of triangles that can be rendered using either (u,v) fill coordinates or a normal fill. Each triangle in the path is represented by three sets of (x, y) coordinates, each of which is one point of the triangle.

The triangle vertices do not contain z coordinates and do not necessarily represent 3D faces. However a triangle path can be used to support the rendering of 3D geometry in a 2D space.

flash.display.Graphics.drawTriangles()GraphicsTrianglePath Creates a new GraphicsTrianglePath object.verticesnullA Vector of Numbers where each pair of numbers is treated as a point (an x, y pair). Required. indicesnullA Vector of integers or indexes, where every three indexes define a triangle. uvtDatanullA Vector of normalized coordinates used to apply texture mapping. cullingStringnoneSpecifies whether to render triangles that face in a given direction. Used to prevent the rendering of triangles that cannot be seen in the current view. Can be set to any value defined by the TriangleCulling class. Creates a new GraphicsTrianglePath object. cullingflash.display.TriangleCullingindices A Vector of integers or indexes, where every three indexes define a triangle. A Vector of integers or indexes, where every three indexes define a triangle. If the indexes parameter is null then every three vertices (six x,y pairs in the vertices Vector) defines a triangle. Otherwise each index refers to a vertex, which is a pair of numbers in the vertices Vector. For example indexes[1] refers to (vertices[2], vertices[3]). uvtData A Vector of normalized coordinates used to apply texture mapping. A Vector of normalized coordinates used to apply texture mapping. Each coordinate refers to a point on the bitmap used for the fill. There must be one UV or one UVT coordinate per vertex.

In UV coordinates, (0,0) is the upper left of the bitmap, and (1,1) is the lower right of the bitmap.

If the length of this vector is twice the length of the vertices vector then normalized coordinates are used without perspective correction.

If the length of this vector is three times the length of the vertices vector then the third coordinate is interpreted as 't', the distance from the eye to the texture in eye space. This helps the rendering engine correctly apply perspective when mapping textures in 3D.

vertices A Vector of Numbers where each pair of numbers is treated as a point (an x, y pair). A Vector of Numbers where each pair of numbers is treated as a point (an x, y pair). culling Specifies whether to render triangles that face in a given direction.String Specifies whether to render triangles that face in a given direction. Used to prevent the rendering of triangles that cannot be seen in the current view.

Can be set to any value defined by the TriangleCulling class.

flash.display.TriangleCulling
DisplayObject The DisplayObject class is the base class for all objects that can be placed on the display list.flash.display:IBitmapDrawableflash.events:EventDispatcher The DisplayObject class is the base class for all objects that can be placed on the display list. The display list manages all objects displayed in the Flash runtimes. Use the DisplayObjectContainer class to arrange the display objects in the display list. DisplayObjectContainer objects can have child display objects, while other display objects, such as Shape and TextField objects, are "leaf" nodes that have only parents and siblings, no children.

The DisplayObject class supports basic functionality like the x and y position of an object, as well as more advanced properties of the object such as its transformation matrix.

DisplayObject is an abstract base class; therefore, you cannot call DisplayObject directly. Invoking new DisplayObject() throws an ArgumentError exception.

All display objects inherit from the DisplayObject class.

The DisplayObject class itself does not include any APIs for rendering content onscreen. For that reason, if you want create a custom subclass of the DisplayObject class, you will want to extend one of its subclasses that do have APIs for rendering content onscreen, such as the Shape, Sprite, Bitmap, SimpleButton, TextField, or MovieClip class.

The DisplayObject class contains several broadcast events. Normally, the target of any particular event is a specific DisplayObject instance. For example, the target of an added event is the specific DisplayObject instance that was added to the display list. Having a single target restricts the placement of event listeners to that target and in some cases the target's ancestors on the display list. With broadcast events, however, the target is not a specific DisplayObject instance, but rather all DisplayObject instances, including those that are not on the display list. This means that you can add a listener to any DisplayObject instance to listen for broadcast events. In addition to the broadcast events listed in the DisplayObject class's Events table, the DisplayObject class also inherits two broadcast events from the EventDispatcher class: activate and deactivate.

Some properties previously used in the ActionScript 1.0 and 2.0 MovieClip, TextField, and Button classes (such as _alpha, _height, _name, _width, _x, _y, and others) have equivalents in the ActionScript 3.0 DisplayObject class that are renamed so that they no longer begin with the underscore (_) character.

For more information, see the "Display Programming" chapter of the ActionScript 3.0 Developer's Guide.

The following example uses the DisplayObjectExample class to draw an orange square in the corner of the Stage and then respond to events by displaying text information for each event. This task is accomplished by performing the following steps:
  1. Class properties are declared for the color and size of the square.
  2. The constructor calls the draw() method, which draws an orange square on the Stage at the default coordinates of x = 0, y = 0.
  3. The following event listener methods are attached to the square:
    • addedHandler() listens for added events, dispatched when the square is added to the display list.
    • enterFrameHandler() listens for enterFrame events, which have no real meaning in this example.
    • removedHandler() listens for removed events, dispatched when the square is removed from the display list, which happens when the square is clicked.
    • clickHandler() listens for click events, dispatched when the orange square is clicked.
    • renderHandler() listens for render events after the display list is updated.
package { import flash.display.Sprite; public class DisplayObjectExample extends Sprite { public function DisplayObjectExample() { var child:CustomDisplayObject = new CustomDisplayObject(); addChild(child); } } } import flash.display.DisplayObject; import flash.display.Sprite; import flash.display.Stage; import flash.display.StageAlign; import flash.display.StageScaleMode; import flash.events.*; class CustomDisplayObject extends Sprite { private var bgColor:uint = 0xFFCC00; private var size:uint = 80; public function CustomDisplayObject() { draw(); addEventListener(Event.ADDED, addedHandler); addEventListener(Event.ENTER_FRAME, enterFrameHandler); addEventListener(Event.REMOVED, removedHandler); addEventListener(MouseEvent.CLICK, clickHandler); addEventListener(Event.RENDER, renderHandler); } private function draw():void { graphics.beginFill(bgColor); graphics.drawRect(0, 0, size, size); graphics.endFill(); } private function clickHandler(event:MouseEvent):void { trace("clickHandler: " + event); parent.removeChild(this); } private function addedHandler(event:Event):void { trace("addedHandler: " + event); stage.scaleMode = StageScaleMode.NO_SCALE; stage.align = StageAlign.TOP_LEFT; stage.addEventListener("resize", resizeHandler); } private function enterFrameHandler(event:Event):void { trace("enterFrameHandler: " + event); removeEventListener("enterFrame", enterFrameHandler); } private function removedHandler(event:Event):void { trace("removedHandler: " + event); stage.removeEventListener("resize", resizeHandler); } private function renderHandler(event:Event):void { trace("renderHandler: " + event); } private function resizeHandler(event:Event):void { trace("resizeHandler: " + event); } }
flash.display.DisplayObjectContainerrender [broadcast event] Dispatched when the display list is about to be updated and rendered.flash.events.Event.RENDERflash.events.Event [broadcast event] Dispatched when the display list is about to be updated and rendered. This event provides the last opportunity for objects listening for this event to make changes before the display list is rendered. You must call the invalidate() method of the Stage object each time you want a render event to be dispatched. Render events are dispatched to an object only if there is mutual trust between it and the object that called Stage.invalidate(). This event is a broadcast event, which means that it is dispatched by all display objects with a listener registered for this event.

Note: This event is not dispatched if the display is not rendering. This is the case when the content is either minimized or obscured.

removedFromStage Dispatched when a display object is about to be removed from the display list, either directly or through the removal of a sub tree in which the display object is contained.flash.events.Event.REMOVED_FROM_STAGEflash.events.Event Dispatched when a display object is about to be removed from the display list, either directly or through the removal of a sub tree in which the display object is contained. Two methods of the DisplayObjectContainer class generate this event: removeChild() and removeChildAt().

The following methods of a DisplayObjectContainer object also generate this event if an object must be removed to make room for the new object: addChild(), addChildAt(), and setChildIndex().

removed Dispatched when a display object is about to be removed from the display list.flash.events.Event.REMOVEDflash.events.Event Dispatched when a display object is about to be removed from the display list. Two methods of the DisplayObjectContainer class generate this event: removeChild() and removeChildAt().

The following methods of a DisplayObjectContainer object also generate this event if an object must be removed to make room for the new object: addChild(), addChildAt(), and setChildIndex().

exitFrame [broadcast event] Dispatched when the playhead is exiting the current frame.flash.events.Event.EXIT_FRAMEflash.events.Event [broadcast event] Dispatched when the playhead is exiting the current frame. All frame scripts have been run. If the playhead is not moving, or if there is only one frame, this event is dispatched continuously in conjunction with the frame rate. This event is a broadcast event, which means that it is dispatched by all display objects with a listener registered for this event. frameConstructed [broadcast event] Dispatched after the constructors of frame display objects have run but before frame scripts have run.flash.events.Event.FRAME_CONSTRUCTEDflash.events.Event [broadcast event] Dispatched after the constructors of frame display objects have run but before frame scripts have run. If the playhead is not moving, or if there is only one frame, this event is dispatched continuously in conjunction with the frame rate. This event is a broadcast event, which means that it is dispatched by all display objects with a listener registered for this event. enterFrame [broadcast event] Dispatched when the playhead is entering a new frame.flash.events.Event.ENTER_FRAMEflash.events.Event [broadcast event] Dispatched when the playhead is entering a new frame. If the playhead is not moving, or if there is only one frame, this event is dispatched continuously in conjunction with the frame rate. This event is a broadcast event, which means that it is dispatched by all display objects with a listener registered for this event. addedToStage Dispatched when a display object is added to the on stage display list, either directly or through the addition of a sub tree in which the display object is contained.flash.events.Event.ADDED_TO_STAGEflash.events.Event Dispatched when a display object is added to the on stage display list, either directly or through the addition of a sub tree in which the display object is contained. The following methods trigger this event: DisplayObjectContainer.addChild(), DisplayObjectContainer.addChildAt(). flash.display.DisplayObjectContainer.addChild()flash.display.DisplayObjectContainer.addChildAt()added Dispatched when a display object is added to the display list.flash.events.Event.ADDEDflash.events.Event Dispatched when a display object is added to the display list. The following methods trigger this event: DisplayObjectContainer.addChild(), DisplayObjectContainer.addChildAt(). flash.display.DisplayObjectContainer.addChild()flash.display.DisplayObjectContainer.addChildAt()getBounds Returns a rectangle that defines the area of the display object relative to the coordinate system of the targetCoordinateSpace object.The rectangle that defines the area of the display object relative to the targetCoordinateSpace object's coordinate system. flash.geom:RectangletargetCoordinateSpaceflash.display:DisplayObjectThe display object that defines the coordinate system to use. Returns a rectangle that defines the area of the display object relative to the coordinate system of the targetCoordinateSpace object. Consider the following code, which shows how the rectangle returned can vary depending on the targetCoordinateSpace parameter that you pass to the method: var container:Sprite = new Sprite(); container.x = 100; container.y = 100; this.addChild(container); var contents:Shape = new Shape(); contents.graphics.drawCircle(0,0,100); container.addChild(contents); trace(contents.getBounds(container)); // (x=-100, y=-100, w=200, h=200) trace(contents.getBounds(this)); // (x=0, y=0, w=200, h=200)

Note: Use the localToGlobal() and globalToLocal() methods to convert the display object's local coordinates to display coordinates, or display coordinates to local coordinates, respectively.

The getBounds() method is similar to the getRect() method; however, the Rectangle returned by the getBounds() method includes any strokes on shapes, whereas the Rectangle returned by the getRect() method does not. For an example, see the description of the getRect() method.

getRect()globalToLocal()localToGlobal()
getRect Returns a rectangle that defines the boundary of the display object, based on the coordinate system defined by the targetCoordinateSpace parameter, excluding any strokes on shapes.The rectangle that defines the area of the display object relative to the targetCoordinateSpace object's coordinate system. flash.geom:RectangletargetCoordinateSpaceflash.display:DisplayObjectThe display object that defines the coordinate system to use. Returns a rectangle that defines the boundary of the display object, based on the coordinate system defined by the targetCoordinateSpace parameter, excluding any strokes on shapes. The values that the getRect() method returns are the same or smaller than those returned by the getBounds() method.

Note: Use localToGlobal() and globalToLocal() methods to convert the display object's local coordinates to Stage coordinates, or Stage coordinates to local coordinates, respectively.

The following example shows how the getBounds() method can return a larger rectangle than the getRect() method does, because of the additional area taken up by strokes. In this case, the triangle sprite includes extra strokes because of the width and jointStyle parameters of the lineStyle() method. The trace() output (in the last two lines) shows the differences between the getRect() and getBounds() rectangles: import flash.display.CapsStyle; import flash.display.JointStyle; import flash.display.LineScaleMode; import flash.display.Sprite; import flash.geom.Rectangle; var triangle:Sprite = new Sprite(); var color:uint = 0xFF0044; var width:Number = 20; var alpha:Number = 1.0; var pixelHinting:Boolean = true; var scaleMode:String = LineScaleMode.NORMAL; var caps:String = CapsStyle.SQUARE; var joints:String = JointStyle.MITER; triangle.graphics.lineStyle(width, color, alpha, pixelHinting, scaleMode, caps, joints); var triangleSide:Number = 100; triangle.graphics.moveTo(0, 0); triangle.graphics.lineTo(0, triangleSide); triangle.graphics.lineTo(triangleSide, triangleSide); triangle.graphics.lineTo(0, 0); addChild(triangle); trace(triangle.getBounds(this)); // (x=-10, y=-24.1, w=134.10000000000002, h=134.1) trace(triangle.getRect(this)); // (x=0, y=0, w=100, h=100)
getBounds()
globalToLocal3D Converts a two-dimensional point from the Stage (global) coordinates to a three-dimensional display object's (local) coordinates.A Vector3D object with coordinates relative to the three-dimensional display object. flash.geom:Vector3Dpointflash.geom:PointA two dimensional Point object representing global x and y coordinates. Converts a two-dimensional point from the Stage (global) coordinates to a three-dimensional display object's (local) coordinates.

To use this method, first create an instance of the Point class. The x and y values that you assign to the Point object represent global coordinates because they are relative to the origin (0,0) of the main display area. Then pass the Point object to the globalToLocal3D() method as the point parameter. The method returns three-dimensional coordinates as a Vector3D object containing x, y, and z values that are relative to the origin of the three-dimensional display object.

globalToLocal Converts the point object from the Stage (global) coordinates to the display object's (local) coordinates.A Point object with coordinates relative to the display object. flash.geom:Pointpointflash.geom:PointAn object created with the Point class. The Point object specifies the x and y coordinates as properties. Converts the point object from Stage (global) coordinates to the display object's (local) coordinates. Converts the point object from the Stage (global) coordinates to the display object's (local) coordinates.

To use this method, first create an instance of the Point class. The x and y values that you assign represent global coordinates because they relate to the origin (0,0) of the main display area. Then pass the Point instance as the parameter to the globalToLocal() method. The method returns a new Point object with x and y values that relate to the origin of the display object instead of the origin of the Stage.

The following code creates a Shape object and shows the result of calling the hitTestPoint() method, using different points as parameters. The globalToLocal() method converts the point from Stage coordinates to the coordinate space of the shape: import flash.display.Shape; import flash.geom.Point; var circle:Shape = new Shape(); circle.graphics.beginFill(0x0000FF); circle.graphics.drawCircle(40, 40, 40); circle.x = 10; addChild(circle); var point1:Point = new Point(0, 0); trace(circle.hitTestPoint(point1.x, point1.y, true)); // false trace(circle.hitTestPoint(point1.x, point1.y, false)); // false trace(circle.globalToLocal(point1)); // [x=-10, y=0] var point2:Point = new Point(10, 1); trace(circle.hitTestPoint(point2.x, point2.y, true)); // false trace(circle.hitTestPoint(point2.x, point2.y, false)); // true trace(circle.globalToLocal(point2)); // [x=0, y=1] var point3:Point = new Point(30, 20); trace(circle.hitTestPoint(point3.x, point3.y, true)); // true trace(circle.hitTestPoint(point3.x, point3.y, false)); // true trace(circle.globalToLocal(point3)); // [x=20, y=20]
localToGlobal()flash.geom.Point class
hitTestObject Evaluates the bounding box of the display object to see if it overlaps or intersects with the bounding box of the obj display object.true if the bounding boxes of the display objects intersect; false if not. Booleanobjflash.display:DisplayObjectThe display object to test against. Evaluates the bounding box of the display object to see if it overlaps or intersects with the bounding box of the display object passed as a parameter. Evaluates the bounding box of the display object to see if it overlaps or intersects with the bounding box of the obj display object. The following code creates three Shape objects and shows the result of calling the hitTestObject() method. Note that although circle2 and circle3 do not overlap, their bounding boxes do. Thus, the hit test of circle2 and circle3 returns true. import flash.display.Shape; var circle1:Shape = new Shape(); circle1.graphics.beginFill(0x0000FF); circle1.graphics.drawCircle(40, 40, 40); addChild(circle1); var circle2:Shape = new Shape(); circle2.graphics.beginFill(0x00FF00); circle2.graphics.drawCircle(40, 40, 40); circle2.x = 50; addChild(circle2); var circle3:Shape = new Shape(); circle3.graphics.beginFill(0xFF0000); circle3.graphics.drawCircle(40, 40, 40); circle3.x = 100; circle3.y = 67; addChild(circle3); trace(circle1.hitTestObject(circle2)); // true trace(circle1.hitTestObject(circle3)); // false trace(circle2.hitTestObject(circle3)); // true hitTestPoint Evaluates the display object to see if it overlaps or intersects with the point specified by the x and y parameters.true if the display object overlaps or intersects with the specified point; false otherwise. BooleanxNumberThe x coordinate to test against this object. yNumberThe y coordinate to test against this object. shapeFlagBooleanfalseWhether to check against the actual pixels of the object (true) or the bounding box (false). Evaluates the display object to see if it overlaps or intersects with a point specified by x and y. Evaluates the display object to see if it overlaps or intersects with the point specified by the x and y parameters. The x and y parameters specify a point in the coordinate space of the Stage, not the display object container that contains the display object (unless that display object container is the Stage). The following code creates a Shape object and shows the result of calling the hitTestPoint() method, using different points as parameters. The globalToLocal() method converts the point from Stage coordinates to the coordinate space of the shape: import flash.display.Shape; import flash.geom.Point; var circle:Shape = new Shape(); circle.graphics.beginFill(0x0000FF); circle.graphics.drawCircle(40, 40, 40); circle.x = 10; addChild(circle); var point1:Point = new Point(0, 0); trace(circle.hitTestPoint(point1.x, point1.y, true)); // false trace(circle.hitTestPoint(point1.x, point1.y, false)); // false trace(circle.globalToLocal(point1)); // [x=-10, y=0] var point2:Point = new Point(10, 1); trace(circle.hitTestPoint(point2.x, point2.y, true)); // false trace(circle.hitTestPoint(point2.x, point2.y, false)); // true trace(circle.globalToLocal(point2)); // [x=0, y=1] var point3:Point = new Point(30, 20); trace(circle.hitTestPoint(point3.x, point3.y, true)); // true trace(circle.hitTestPoint(point3.x, point3.y, false)); // true trace(circle.globalToLocal(point3)); // [x=20, y=20] opaqueBackgroundlocal3DToGlobal Converts a three-dimensional point of the three-dimensional display object's (local) coordinates to a two-dimensional point in the Stage (global) coordinates.A two-dimensional point representing a three-dimensional point in two-dimensional space. flash.geom:Pointpoint3dflash.geom:Vector3DA Vector3D object containing either a three-dimensional point or the coordinates of the three-dimensional display object. Converts a three-dimensional point of the three-dimensional display object's (local) coordinates to a two-dimensional point in the Stage (global) coordinates.

For example, you can only use two-dimensional coordinates (x,y) to draw with the display.Graphics methods. To draw a three-dimensional object, you need to map the three-dimensional coordinates of a display object to two-dimensional coordinates. First, create an instance of the Vector3D class that holds the x-, y-, and z- coordinates of the three-dimensional display object. Then pass the Vector3D object to the local3DToGlobal() method as the point3d parameter. The method returns a two-dimensional Point object that can be used with the Graphics API to draw the three-dimensional object.

This example draws a simple three-dimensional cube in a two dimensional space using display.Graphics methods. The location of this display object is offset, so the cube's registration point is in its center. A vector of Vector3D objects holds the cube's three dimensional coordinates. The top of the cube is draw first, the bottom is drawn second, and then the top and bottom four corners are connected. You need to add the cube to the display object container before drawing the cube in order to use the local3DToGlobal() method. package { import flash.display.MovieClip; import flash.display.Sprite; import flash.display.Graphics; import flash.geom.*; public class Local3DToGlobalExample extends MovieClip { private var myCube:Sprite = new Sprite(); private var v8:Vector.<Vector3D> = new Vector.<Vector3D>(8); public function Local3DToGlobalExample():void { this.x = -(this.stage.stageWidth / 2); this.y = -(this.stage.stageWidth / 2); v8[0] = new Vector3D(-40,-40,-40); v8[1] = new Vector3D(40,-40,-40); v8[2] = new Vector3D(40,-40,40); v8[3] = new Vector3D(-40,-40,40); v8[4] = new Vector3D(-40,100,-40); v8[5] = new Vector3D(40,100,-40); v8[6] = new Vector3D(40,100,40); v8[7] = new Vector3D(-40,100,40); myCube.x = (this.stage.stageWidth / 2); myCube.y = (this.stage.stageWidth / 2); myCube.z = 1; addChild(myCube); Cube(); } private function Cube():void { var ps:Point = new Point(0,0); myCube.graphics.lineStyle(2,0xFF0000); ps = myCube.local3DToGlobal(v8[0]); myCube.graphics.moveTo(ps.x, ps.y); ps = myCube.local3DToGlobal(v8[1]); myCube.graphics.lineTo(ps.x, ps.y); ps = myCube.local3DToGlobal(v8[2]); myCube.graphics.lineTo(ps.x, ps.y); ps = myCube.local3DToGlobal(v8[3]); myCube.graphics.lineTo(ps.x, ps.y); ps = myCube.local3DToGlobal(v8[0]); myCube.graphics.lineTo(ps.x, ps.y); ps = myCube.local3DToGlobal(v8[4]); myCube.graphics.moveTo(ps.x, ps.y); ps = myCube.local3DToGlobal(v8[5]); myCube.graphics.lineTo(ps.x, ps.y); ps = myCube.local3DToGlobal(v8[6]); myCube.graphics.lineTo(ps.x, ps.y); ps = myCube.local3DToGlobal(v8[7]); myCube.graphics.lineTo(ps.x, ps.y); ps = myCube.local3DToGlobal(v8[4]); myCube.graphics.lineTo(ps.x, ps.y); ps = myCube.local3DToGlobal(v8[0]); myCube.graphics.moveTo(ps.x, ps.y); ps = myCube.local3DToGlobal(v8[4]); myCube.graphics.lineTo(ps.x, ps.y); ps = myCube.local3DToGlobal(v8[1]); myCube.graphics.moveTo(ps.x, ps.y); ps = myCube.local3DToGlobal(v8[5]); myCube.graphics.lineTo(ps.x, ps.y); ps = myCube.local3DToGlobal(v8[2]); myCube.graphics.moveTo(ps.x, ps.y); ps = myCube.local3DToGlobal(v8[6]); myCube.graphics.lineTo(ps.x, ps.y); ps = myCube.local3DToGlobal(v8[3]); myCube.graphics.moveTo(ps.x, ps.y); ps = myCube.local3DToGlobal(v8[7]); myCube.graphics.lineTo(ps.x, ps.y); } } }
localToGlobal Converts the point object from the display object's (local) coordinates to the Stage (global) coordinates.A Point object with coordinates relative to the Stage. flash.geom:Pointpointflash.geom:PointThe name or identifier of a point created with the Point class, specifying the x and y coordinates as properties. Converts the point object from the display object's (local) coordinates to the Stage (global) coordinates.

This method allows you to convert any given x and y coordinates from values that are relative to the origin (0,0) of a specific display object (local coordinates) to values that are relative to the origin of the Stage (global coordinates).

To use this method, first create an instance of the Point class. The x and y values that you assign represent local coordinates because they relate to the origin of the display object.

You then pass the Point instance that you created as the parameter to the localToGlobal() method. The method returns a new Point object with x and y values that relate to the origin of the Stage instead of the origin of the display object.

The following code creates a Sprite object. The mouseX and mouseY properties of the sprite are in the coordinate space of the display object. This code uses the localToGlobal() method to translate these properties to the global (Stage) coordinates: import flash.display.Sprite; import flash.events.MouseEvent; import flash.geom.Point; var square:Sprite = new Sprite(); square.graphics.beginFill(0xFFCC00); square.graphics.drawRect(0, 0, 100, 100); square.x = 100; square.y = 200; addChild(square); square.addEventListener(MouseEvent.CLICK, traceCoordinates) function traceCoordinates(event:MouseEvent):void { var clickPoint:Point = new Point(square.mouseX, square.mouseY); trace("display object coordinates:", clickPoint); trace("stage coordinates:", square.localToGlobal(clickPoint)); }
globalToLocal()flash.geom.Point class
accessibilityProperties The current accessibility options for this display object.flash.accessibility:AccessibilityProperties The current accessibility options for this display object. If you modify the accessibilityProperties property or any of the fields within accessibilityProperties, you must call the Accessibility.updateProperties() method to make your changes take effect.

Note: For an object created in the Flash authoring environment, the value of accessibilityProperties is prepopulated with any information you entered in the Accessibility panel for that object.

The following example shows how the to attach a simple AccessibilityProperties object to a TextField instance: import flash.text.TextField; import flash.accessibility.AccessibilityProperties; import flash.accessibility.Accessibility; import flash.system.Capabilities; var tf:TextField = new TextField(); tf.text = "hello"; var accessProps:AccessibilityProperties = new AccessibilityProperties(); accessProps.name = "Greeting"; tf.accessibilityProperties = accessProps; if (Capabilities.hasAccessibility) { Accessibility.updateProperties(); } trace(tf.accessibilityProperties.name); // Greeting
flash.accessibility.Accessibility.updateProperties()flash.accessibility.AccessibilityProperties
alpha Indicates the alpha transparency value of the object specified.Number Indicates the alpha transparency value of the object specified. Valid values are 0 (fully transparent) to 1 (fully opaque). The default value is 1. Display objects with alpha set to 0 are active, even though they are invisible. The following code sets the alpha property of a sprite to 50% when the mouse rolls over the sprite: import flash.display.Sprite; import flash.events.MouseEvent; var circle:Sprite = new Sprite(); circle.graphics.beginFill(0xFF0000); circle.graphics.drawCircle(40, 40, 40); addChild(circle); circle.addEventListener(MouseEvent.MOUSE_OVER, dimObject); circle.addEventListener(MouseEvent.MOUSE_OUT, restoreObject); function dimObject(event:MouseEvent):void { event.target.alpha = 0.5; } function restoreObject(event:MouseEvent):void { event.target.alpha = 1.0; } blendMode A value from the BlendMode class that specifies which blend mode to use.String A value from the BlendMode class that specifies which blend mode to use. A bitmap can be drawn internally in two ways. If you have a blend mode enabled or an external clipping mask, the bitmap is drawn by adding a bitmap-filled square shape to the vector render. If you attempt to set this property to an invalid value, Flash runtimes set the value to BlendMode.NORMAL.

The blendMode property affects each pixel of the display object. Each pixel is composed of three constituent colors (red, green, and blue), and each constituent color has a value between 0x00 and 0xFF. Flash Player or Adobe AIR compares each constituent color of one pixel in the movie clip with the corresponding color of the pixel in the background. For example, if blendMode is set to BlendMode.LIGHTEN, Flash Player or Adobe AIR compares the red value of the display object with the red value of the background, and uses the lighter of the two as the value for the red component of the displayed color.

The following table describes the blendMode settings. The BlendMode class defines string values you can use. The illustrations in the table show blendMode values applied to a circular display object (2) superimposed on another display object (1).

BlendMode ConstantIllustrationDescriptionBlendMode.NORMALThe display object appears in front of the background. Pixel values of the display object override those of the background. Where the display object is transparent, the background is visible.BlendMode.LAYERForces the creation of a transparency group for the display object. This means that the display object is pre-composed in a temporary buffer before it is processed further. This is done automatically if the display object is pre-cached using bitmap caching or if the display object is a display object container with at least one child object with a blendMode setting other than BlendMode.NORMAL. Not supported under GPU rendering. BlendMode.MULTIPLYMultiplies the values of the display object constituent colors by the colors of the background color, and then normalizes by dividing by 0xFF, resulting in darker colors. This setting is commonly used for shadows and depth effects.

For example, if a constituent color (such as red) of one pixel in the display object and the corresponding color of the pixel in the background both have the value 0x88, the multiplied result is 0x4840. Dividing by 0xFF yields a value of 0x48 for that constituent color, which is a darker shade than the color of the display object or the color of the background.

BlendMode.SCREENMultiplies the complement (inverse) of the display object color by the complement of the background color, resulting in a bleaching effect. This setting is commonly used for highlights or to remove black areas of the display object.BlendMode.LIGHTENSelects the lighter of the constituent colors of the display object and the color of the background (the colors with the larger values). This setting is commonly used for superimposing type.

For example, if the display object has a pixel with an RGB value of 0xFFCC33, and the background pixel has an RGB value of 0xDDF800, the resulting RGB value for the displayed pixel is 0xFFF833 (because 0xFF > 0xDD, 0xCC < 0xF8, and 0x33 > 0x00 = 33). Not supported under GPU rendering.

BlendMode.DARKENSelects the darker of the constituent colors of the display object and the colors of the background (the colors with the smaller values). This setting is commonly used for superimposing type.

For example, if the display object has a pixel with an RGB value of 0xFFCC33, and the background pixel has an RGB value of 0xDDF800, the resulting RGB value for the displayed pixel is 0xDDCC00 (because 0xFF > 0xDD, 0xCC < 0xF8, and 0x33 > 0x00 = 33). Not supported under GPU rendering.

BlendMode.DIFFERENCECompares the constituent colors of the display object with the colors of its background, and subtracts the darker of the values of the two constituent colors from the lighter value. This setting is commonly used for more vibrant colors.

For example, if the display object has a pixel with an RGB value of 0xFFCC33, and the background pixel has an RGB value of 0xDDF800, the resulting RGB value for the displayed pixel is 0x222C33 (because 0xFF - 0xDD = 0x22, 0xF8 - 0xCC = 0x2C, and 0x33 - 0x00 = 0x33).

BlendMode.ADDAdds the values of the constituent colors of the display object to the colors of its background, applying a ceiling of 0xFF. This setting is commonly used for animating a lightening dissolve between two objects.

For example, if the display object has a pixel with an RGB value of 0xAAA633, and the background pixel has an RGB value of 0xDD2200, the resulting RGB value for the displayed pixel is 0xFFC833 (because 0xAA + 0xDD > 0xFF, 0xA6 + 0x22 = 0xC8, and 0x33 + 0x00 = 0x33).

BlendMode.SUBTRACTSubtracts the values of the constituent colors in the display object from the values of the background color, applying a floor of 0. This setting is commonly used for animating a darkening dissolve between two objects.

For example, if the display object has a pixel with an RGB value of 0xAA2233, and the background pixel has an RGB value of 0xDDA600, the resulting RGB value for the displayed pixel is 0x338400 (because 0xDD - 0xAA = 0x33, 0xA6 - 0x22 = 0x84, and 0x00 - 0x33 < 0x00).

BlendMode.INVERTInverts the background.BlendMode.ALPHAApplies the alpha value of each pixel of the display object to the background. This requires the blendMode setting of the parent display object to be set to BlendMode.LAYER. For example, in the illustration, the parent display object, which is a white background, has blendMode = BlendMode.LAYER. Not supported under GPU rendering.BlendMode.ERASEErases the background based on the alpha value of the display object. This requires the blendMode of the parent display object to be set to BlendMode.LAYER. For example, in the illustration, the parent display object, which is a white background, has blendMode = BlendMode.LAYER. Not supported under GPU rendering.BlendMode.OVERLAYAdjusts the color of each pixel based on the darkness of the background. If the background is lighter than 50% gray, the display object and background colors are screened, which results in a lighter color. If the background is darker than 50% gray, the colors are multiplied, which results in a darker color. This setting is commonly used for shading effects. Not supported under GPU rendering.BlendMode.HARDLIGHTAdjusts the color of each pixel based on the darkness of the display object. If the display object is lighter than 50% gray, the display object and background colors are screened, which results in a lighter color. If the display object is darker than 50% gray, the colors are multiplied, which results in a darker color. This setting is commonly used for shading effects. Not supported under GPU rendering.BlendMode.SHADERN/AAdjusts the color using a custom shader routine. The shader that is used is specified as the Shader instance assigned to the blendShader property. Setting the blendShader property of a display object to a Shader instance automatically sets the display object's blendMode property to BlendMode.SHADER. If the blendMode property is set to BlendMode.SHADER without first setting the blendShader property, the blendMode property is set to BlendMode.NORMAL. Not supported under GPU rendering.
The following code creates two sprite objects, a square and a circle, and sets the blend mode of the circle (in the foreground) to BlendMode.SUBTRACT when the pointer rolls over the circle: import flash.display.Sprite; import flash.display.BlendMode; import flash.events.MouseEvent; var square:Sprite = new Sprite(); square.graphics.beginFill(0xFF88CC); square.graphics.drawRect(0, 0, 80, 80); addChild(square); var circle:Sprite = new Sprite(); circle.graphics.beginFill(0xAA0022); circle.graphics.drawCircle(40, 40, 40); addChild(circle); circle.addEventListener(MouseEvent.MOUSE_OVER, dimObject); circle.addEventListener(MouseEvent.MOUSE_OUT, restoreObject); function dimObject(event:MouseEvent):void { event.target.blendMode = BlendMode.SUBTRACT; } function restoreObject(event:MouseEvent):void { event.target.blendMode = BlendMode.NORMAL; }
flash.display.BlendModeblendShader
cacheAsBitmapMatrix If non-null, this Matrix object defines how a display object is rendered when cacheAsBitmap is set to true.flash.geom:MatrixThe transformation matrix used when rendering a cached version of this display object's bitmap. If non-null, this Matrix object defines how a display object is rendered when cacheAsBitmap is set to true. The application uses this matrix as a transformation matrix that is applied when rendering the bitmap version of the display object.

AIR profile support: This feature is supported on mobile devices, but it is not supported on desktop operating systems. It also has limited support on AIR for TV devices. Specifically, on AIR for TV devices, supported transformations include scaling and translation, but not rotation and skewing. See AIR Profile Support for more information regarding API support across multiple profiles.

With cacheAsBitmapMatrix set, the application retains a cached bitmap image across various 2D transformations, including translation, rotation, and scaling. If the application uses hardware acceleration, the object will be stored in video memory as a texture. This allows the GPU to apply the supported transformations to the object. The GPU can perform these transformations faster than the CPU.

To use the hardware acceleration, set Rendering to GPU in the General tab of the iPhone Settings dialog box in Flash Professional CS5. Or set the renderMode property to gpu in the application descriptor file. Note that AIR for TV devices automatically use hardware acceleration if it is available.

For example, the following code sends an untransformed bitmap representation of the display object to the GPU:

matrix:Matrix = new Matrix(); // creates an identity matrix mySprite.cacheAsBitmapMatrix = matrix; mySprite.cacheAsBitmap = true;

Usually, the identity matrix (new Matrix()) suffices. However, you can use another matrix, such as a scaled-down matrix, to upload a different bitmap to the GPU. For example, the following example applies a cacheAsBitmapMatrix matrix that is scaled by 0.5 on the x and y axes. The bitmap object that the GPU uses is smaller, however the GPU adjusts its size to match the transform.matrix property of the display object:

matrix:Matrix = new Matrix(); // creates an identity matrix matrix.scale(0.5, 0.5); // scales the matrix mySprite.cacheAsBitmapMatrix = matrix; mySprite.cacheAsBitmap = true;

Generally, you should choose to use a matrix that transforms the display object to the size that it will appear in the application. For example, if your application displays the bitmap version of the sprite scaled down by a half, use a matrix that scales down by a half. If you application will display the sprite larger than its current dimensions, use a matrix that scales up by that factor.

Note: The cacheAsBitmapMatrix property is suitable for 2D transformations. If you need to apply transformations in 3D, you may do so by setting a 3D property of the object and manipulating its transform.matrix3D property. If the application is packaged using GPU mode, this allows the 3D transforms to be applied to the object by the GPU. The cacheAsBitmapMatrix is ignored for 3D objects.

The following example applies uses the cacheAsBitmapMatrix property to apply transformations to a bitmap version of the movie clip my_shape. import flash.geom.Matrix; import flash.display.*; import flash.utils.Timer; var my_shape:MovieClip = new MovieClip(); my_shape.graphics.beginFill(0xCCFF00); my_shape.graphics.drawRect(200, 0, 100, 100); addChild(my_shape); var my_timer:Timer = new Timer(250); my_timer.start(); my_timer.addEventListener(TimerEvent.TIMER, timerHandler); // make sure this Display Object remains cached for all 2D transforms my_shape.cacheAsBitmap = true; my_shape.cacheAsBitmapMatrix = new Matrix(); // rotation variables const initAngle:Number = 0; const pi:Number = 3.142; const incrAngle:Number = pi/10; // scaling variables const initScale:Number = 0.25; const incrScale: Number = 1.1; var initHeight : Number = my_shape.height; var initWidth : Number = my_shape.width; // translation variables var incrX : Number = root.width / 20; var incrY : Number = root.height / 10; // do some initial transforms var tempMat : Matrix = my_shape.transform.matrix; tempMat.rotate(initAngle); tempMat.scale(initScale, initScale); my_shape.transform.matrix = tempMat; function timerHandler(evt:TimerEvent):void { tempMat = my_shape.transform.matrix; tempMat.rotate(incrAngle); tempMat.translate(incrX, incrY); tempMat.scale(incrScale, incrScale); my_shape.transform.matrix = tempMat; // ensure we are still in a reasonable state or reset if(my_shape.height > stage.stageHeight/2) { my_shape.height = initHeight; } if(my_shape.width > stage.stageWidth/2) { my_shape.width = initWidth; } if(my_shape.x > stage.stageWidth) { my_shape.x = 0; } else if (my_shape.x < 0) { my_shape.x = stage.stageWidth; } if(my_shape.y > stage.stageHeight) { my_shape.y = 0; } else if (my_shape.y < 0) { my_shape.y = stage.stageHeight; } }
cacheAsBitmapflash.geom.Matrix3D
cacheAsBitmap If set to true, Flash runtimes cache an internal bitmap representation of the display object.BooleanWhether to cache this DisplayObject as a bitmap. If set to true, Flash runtimes cache an internal bitmap representation of the display object. This caching can increase performance for display objects that contain complex vector content.

All vector data for a display object that has a cached bitmap is drawn to the bitmap instead of the main display. If cacheAsBitmapMatrix is null or unsupported, the bitmap is then copied to the main display as unstretched, unrotated pixels snapped to the nearest pixel boundaries. Pixels are mapped 1 to 1 with the parent object. If the bounds of the bitmap change, the bitmap is recreated instead of being stretched.

If cacheAsBitmapMatrix is non-null and supported, the object is drawn to the off-screen bitmap using that matrix and the stretched and/or rotated results of that rendering are used to draw the object to the main display.

No internal bitmap is created unless the cacheAsBitmap property is set to true.

After you set the cacheAsBitmap property to true, the rendering does not change, however the display object performs pixel snapping automatically. The animation speed can be significantly faster depending on the complexity of the vector content.

The cacheAsBitmap property is automatically set to true whenever you apply a filter to a display object (when its filter array is not empty), and if a display object has a filter applied to it, cacheAsBitmap is reported as true for that display object, even if you set the property to false. If you clear all filters for a display object, the cacheAsBitmap setting changes to what it was last set to.

A display object does not use a bitmap even if the cacheAsBitmap property is set to true and instead renders from vector data in the following cases:

  • The bitmap is too large. In AIR 1.5 and Flash Player 10, the maximum size for a bitmap image is 8,191 pixels in width or height, and the total number of pixels cannot exceed 16,777,215 pixels. (So, if a bitmap image is 8,191 pixels wide, it can only be 2,048 pixels high.) In Flash Player 9 and earlier, the limitation is is 2880 pixels in height and 2,880 pixels in width.
  • The bitmap fails to allocate (out of memory error).

The cacheAsBitmap property is best used with movie clips that have mostly static content and that do not scale and rotate frequently. With such movie clips, cacheAsBitmap can lead to performance increases when the movie clip is translated (when its x and y position is changed).

The following example applies a drop shadow to a Shape instance. It then traces the value of the cacheAsBitmap property, which is set to true when the filter is applied: import flash.display.Sprite; import flash.filters.DropShadowFilter var circle:Sprite = new Sprite(); circle.graphics.beginFill(0xAA0022); circle.graphics.drawCircle(40, 40, 40); addChild(circle); trace(circle.cacheAsBitmap); // false var filter:DropShadowFilter = new DropShadowFilter(); circle.filters = [filter]; trace(circle.cacheAsBitmap); // true
cacheAsBitmapMatrixopaqueBackground
filters An indexed array that contains each filter object currently associated with the display object.ArrayWhen filters includes a ShaderFilter and the shader output type is not compatible with this operation (the shader must specify a pixel4 output). ArgumentErrorArgumentErrorWhen filters includes a ShaderFilter and the shader doesn't specify any image input or the first input is not an image4 input. ArgumentErrorArgumentErrorWhen filters includes a ShaderFilter and the shader specifies an image input that isn't provided. ArgumentErrorArgumentErrorWhen filters includes a ShaderFilter, a ByteArray or Vector.<Number> instance as a shader input, and the width and height properties aren't specified for the ShaderInput object, or the specified values don't match the amount of data in the input data. See the ShaderInput.input property for more information. ArgumentErrorArgumentError An indexed array that contains each filter object currently associated with the display object. The flash.filters package contains several classes that define specific filters you can use.

Filters can be applied in Flash Professional at design time, or at run time by using ActionScript code. To apply a filter by using ActionScript, you must make a temporary copy of the entire filters array, modify the temporary array, then assign the value of the temporary array back to the filters array. You cannot directly add a new filter object to the filters array.

To add a filter by using ActionScript, perform the following steps (assume that the target display object is named myDisplayObject):

  1. Create a new filter object by using the constructor method of your chosen filter class.
  2. Assign the value of the myDisplayObject.filters array to a temporary array, such as one named myFilters.
  3. Add the new filter object to the myFilters temporary array.
  4. Assign the value of the temporary array to the myDisplayObject.filters array.

If the filters array is undefined, you do not need to use a temporary array. Instead, you can directly assign an array literal that contains one or more filter objects that you create. The first example in the Examples section adds a drop shadow filter by using code that handles both defined and undefined filters arrays.

To modify an existing filter object, you must use the technique of modifying a copy of the filters array:

  1. Assign the value of the filters array to a temporary array, such as one named myFilters.
  2. Modify the property by using the temporary array, myFilters. For example, to set the quality property of the first filter in the array, you could use the following code: myFilters[0].quality = 1;
  3. Assign the value of the temporary array to the filters array.

At load time, if a display object has an associated filter, it is marked to cache itself as a transparent bitmap. From this point forward, as long as the display object has a valid filter list, the player caches the display object as a bitmap. This source bitmap is used as a source image for the filter effects. Each display object usually has two bitmaps: one with the original unfiltered source display object and another for the final image after filtering. The final image is used when rendering. As long as the display object does not change, the final image does not need updating.

The flash.filters package includes classes for filters. For example, to create a DropShadow filter, you would write:

import flash.filters.DropShadowFilter var myFilter:DropShadowFilter = new DropShadowFilter (distance, angle, color, alpha, blurX, blurY, quality, inner, knockout)

You can use the is operator to determine the type of filter assigned to each index position in the filter array. For example, the following code shows how to determine the position of the first filter in the filters array that is a DropShadowFilter:

import flash.text.TextField; import flash.filters.~~; var tf:TextField = new TextField(); var filter1:DropShadowFilter = new DropShadowFilter(); var filter2:GradientGlowFilter = new GradientGlowFilter(); tf.filters = [filter1, filter2]; tf.text = "DropShadow index: " + filterPosition(tf, DropShadowFilter).toString(); // 0 addChild(tf) function filterPosition(displayObject:DisplayObject, filterClass:Class):int { for (var i:uint = 0; i < displayObject.filters.length; i++) { if (displayObject.filters[i] is filterClass) { return i; } } return -1; }

Note: Since you cannot directly add a new filter object to the DisplayObject.filters array, the following code has no effect on the target display object, named myDisplayObject:

myDisplayObject.filters.push(myDropShadow);
flash.filters packageflash.display.ShaderInput.input
height Indicates the height of the display object, in pixels.Number Indicates the height of the display object, in pixels. The height is calculated based on the bounds of the content of the display object. When you set the height property, the scaleY property is adjusted accordingly, as shown in the following code: var rect:Shape = new Shape(); rect.graphics.beginFill(0xFF0000); rect.graphics.drawRect(0, 0, 100, 100); trace(rect.scaleY) // 1; rect.height = 200; trace(rect.scaleY) // 2;

Except for TextField and Video objects, a display object with no content (such as an empty sprite) has a height of 0, even if you try to set height to a different value.

The following code creates two TextField objects and adjusts the height property of each based on the textHeight property of each; it also positions the second text field by setting its y property: import flash.text.TextField; var tf1:TextField = new TextField(); tf1.text = "Text Field 1"; tf1.border = true; tf1.wordWrap = true; tf1.width = 40; tf1.height = tf1.textHeight + 5; addChild(tf1); var tf2:TextField = new TextField(); tf2.text = "Text Field 2"; tf2.border = true; tf2.wordWrap = true; tf2.width = 40; tf2.height = tf2.textHeight + 5; tf2.y = tf1.y + tf1.height + 5; addChild(tf2);
loaderInfo Returns a LoaderInfo object containing information about loading the file to which this display object belongs.flash.display:LoaderInfo Returns a LoaderInfo object containing information about loading the file to which this display object belongs. The loaderInfo property is defined only for the root display object of a SWF file or for a loaded Bitmap (not for a Bitmap that is drawn with ActionScript). To find the loaderInfo object associated with the SWF file that contains a display object named myDisplayObject, use myDisplayObject.root.loaderInfo.

A large SWF file can monitor its download by calling this.root.loaderInfo.addEventListener(Event.COMPLETE, func).

The following code assumes that this refers to a display object. The code outputs the URL of the root SWF file for the display object: trace (this.loaderInfo.url);
LoaderInfo class
mask The calling display object is masked by the specified mask object.flash.display:DisplayObjectSets a mask for the display object. The calling display object is masked by the specified mask object. To ensure that masking works when the Stage is scaled, the mask display object must be in an active part of the display list. The mask object itself is not drawn. Set mask to null to remove the mask.

To be able to scale a mask object, it must be on the display list. To be able to drag a mask Sprite object (by calling its startDrag() method), it must be on the display list. To call the startDrag() method for a mask sprite based on a mouseDown event being dispatched by the sprite, set the sprite's buttonMode property to true.

When display objects are cached by setting the cacheAsBitmap property to true an the cacheAsBitmapMatrix property to a Matrix object, both the mask and the display object being masked must be part of the same cached bitmap. Thus, if the display object is cached, then the mask must be a child of the display object. If an ancestor of the display object on the display list is cached, then the mask must be a child of that ancestor or one of its descendents. If more than one ancestor of the masked object is cached, then the mask must be a descendent of the cached container closest to the masked object in the display list.

Note: A single mask object cannot be used to mask more than one calling display object. When the mask is assigned to a second display object, it is removed as the mask of the first object, and that object's mask property becomes null.

The following code creates a TextField object as well as a Sprite object that is set as a mask for the TextField object. When the user clicks the text field, the drag() event listener function calls the startDrag() method of the mask Sprite object: import flash.text.TextField; import flash.display.Sprite; import flash.events.MouseEvent; var tf:TextField = new TextField(); tf.text = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, " + "sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. " tf.selectable = false; tf.wordWrap = true; tf.width = 150; addChild(tf); var square:Sprite = new Sprite(); square.graphics.beginFill(0xFF0000); square.graphics.drawRect(0, 0, 40, 40); addChild(square); tf.mask = square; tf.addEventListener(MouseEvent.MOUSE_DOWN, drag); tf.addEventListener(MouseEvent.MOUSE_UP, noDrag); function drag(event:MouseEvent):void { square.startDrag(); } function noDrag(event:MouseEvent):void { square.stopDrag(); }
mouseX Indicates the x coordinate of the mouse or user input device position, in pixels.Number Indicates the x coordinate of the mouse or user input device position, in pixels.

Note: For a DisplayObject that has been rotated, the returned x coordinate will reflect the non-rotated object.

The following code creates a Sprite object and traces the mouseX and mouseY positions when the user clicks the sprite: import flash.display.Sprite; import flash.events.MouseEvent; var square:Sprite = new Sprite(); square.graphics.beginFill(0xFF0000); square.graphics.drawRect(0, 0, 200, 200); addChild(square); square.addEventListener(MouseEvent.CLICK, traceCoordinates); function traceCoordinates(event:MouseEvent):void { trace(square.mouseX, square.mouseY); }
mouseY Indicates the y coordinate of the mouse or user input device position, in pixels.Number Indicates the y coordinate of the mouse or user input device position, in pixels.

Note: For a DisplayObject that has been rotated, the returned y coordinate will reflect the non-rotated object.

The following code creates a Sprite object and traces the mouseX and mouseY positions when the user clicks the sprite: import flash.display.Sprite; import flash.events.MouseEvent; var square:Sprite = new Sprite(); square.graphics.beginFill(0xFF0000); square.graphics.drawRect(0, 0, 200, 200); addChild(square); square.addEventListener(MouseEvent.CLICK, traceCoordinates); function traceCoordinates(event:MouseEvent):void { trace(square.mouseX, square.mouseY); }
name Indicates the instance name of the DisplayObject.StringIf you are attempting to set this property on an object that was placed on the timeline in the Flash authoring tool. IllegalOperationErrorflash.errors:IllegalOperationErrorThe name of this DisplayObject. Indicates the instance name of the DisplayObject. The object can be identified in the child list of its parent display object container by calling the getChildByName() method of the display object container. The following code creates two Sprite object and traces the associated name property when the user clicks either of the objects: import flash.display.Sprite; import flash.events.MouseEvent; var circle1:Sprite = new Sprite(); circle1.graphics.beginFill(0xFF0000); circle1.graphics.drawCircle(40, 40, 40); circle1.name = "circle1"; addChild(circle1); circle1.addEventListener(MouseEvent.CLICK, traceName); var circle2:Sprite = new Sprite(); circle2.graphics.beginFill(0x0000FF); circle2.graphics.drawCircle(140, 40, 40); circle2.name = "circle2"; addChild(circle2); circle2.addEventListener(MouseEvent.CLICK, traceName); function traceName(event:MouseEvent):void { trace(event.target.name); } opaqueBackground Specifies whether the display object is opaque with a certain background color.Object Specifies whether the display object is opaque with a certain background color. A transparent bitmap contains alpha channel data and is drawn transparently. An opaque bitmap has no alpha channel (and renders faster than a transparent bitmap). If the bitmap is opaque, you specify its own background color to use.

If set to a number value, the surface is opaque (not transparent) with the RGB background color that the number specifies. If set to null (the default value), the display object has a transparent background.

The opaqueBackground property is intended mainly for use with the cacheAsBitmap property, for rendering optimization. For display objects in which the cacheAsBitmap property is set to true, setting opaqueBackground can improve rendering performance.

The opaque background region is not matched when calling the hitTestPoint() method with the shapeFlag parameter set to true.

The opaque background region does not respond to mouse events.

The following code creates a Shape object with a blue circle and sets its opaqueBackground property to red (0xFF0000): import flash.display.Shape; var circle:Shape = new Shape(); circle.graphics.beginFill(0x0000FF); circle.graphics.drawCircle(40, 40, 40); circle.opaqueBackground = 0xFF0000; addChild(circle);
cacheAsBitmaphitTestPoint()
parent Indicates the DisplayObjectContainer object that contains this display object.flash.display:DisplayObjectContainerThe parent display object belongs to a security sandbox to which you do not have access. You can avoid this situation by having the parent movie call the Security.allowDomain() method. SecurityErrorSecurityError Indicates the DisplayObjectContainer object that contains this display object. Use the parent property to specify a relative path to display objects that are above the current display object in the display list hierarchy.

You can use parent to move up multiple levels in the display list as in the following:

this.parent.parent.alpha = 20;
The following code creates three Sprite objects and shows how the parent property reflects the display list hierarchy: import flash.display.Sprite; var sprite1:Sprite = new Sprite(); sprite1.name = "sprite1"; var sprite2:Sprite = new Sprite(); sprite2.name = "sprite2"; var sprite3:Sprite = new Sprite(); sprite3.name = "sprite3"; sprite1.addChild(sprite2); sprite2.addChild(sprite3); trace(sprite2.parent.name); // sprite1 trace(sprite3.parent.name); // sprite2 trace(sprite3.parent.parent.name); // sprite1
root For a display object in a loaded SWF file, the root property is the top-most display object in the portion of the display list's tree structure represented by that SWF file.flash.display:DisplayObjectReturn the root display object for this object. For a display object in a loaded SWF file, the root property is the top-most display object in the portion of the display list's tree structure represented by that SWF file. For a Bitmap object representing a loaded image file, the root property is the Bitmap object itself. For the instance of the main class of the first SWF file loaded, the root property is the display object itself. The root property of the Stage object is the Stage object itself. The root property is set to null for any display object that has not been added to the display list, unless it has been added to a display object container that is off the display list but that is a child of the top-most display object in a loaded SWF file.

For example, if you create a new Sprite object by calling the Sprite() constructor method, its root property is null until you add it to the display list (or to a display object container that is off the display list but that is a child of the top-most display object in a SWF file).

For a loaded SWF file, even though the Loader object used to load the file may not be on the display list, the top-most display object in the SWF file has its root property set to itself. The Loader object does not have its root property set until it is added as a child of a display object for which the root property is set.

The following code shows the difference between the root property for the Stage object, for a display object (a Loader object) that is not loaded (both before and after it has been added to the display list), and for a loaded object (a loaded Bitmap object): import flash.display.Loader; import flash.net.URLRequest; import flash.events.Event; trace(stage.root); // [object Stage] var ldr:Loader = new Loader(); trace (ldr.root); // null addChild(ldr); trace (ldr.root); // [object ...] var urlReq:URLRequest = new URLRequest("example.jpg"); ldr.load(urlReq); ldr.contentLoaderInfo.addEventListener(Event.COMPLETE, loaded); function loaded(event:Event):void { trace(ldr.content.root); // [object Bitmap] }
rotationX Indicates the x-axis rotation of the DisplayObject instance, in degrees, from its original orientation relative to the 3D parent container.Number Indicates the x-axis rotation of the DisplayObject instance, in degrees, from its original orientation relative to the 3D parent container. Values from 0 to 180 represent clockwise rotation; values from 0 to -180 represent counterclockwise rotation. Values outside this range are added to or subtracted from 360 to obtain a value within the range. In this example, two ellipses rotate using their rotationX and rotationY properties. The first ellipse's registration point is set to its center. It rotates around itself. The second ellipse rotates around an external point. package { import flash.display.MovieClip; import flash.display.Shape; import flash.geom.*; import flash.display.Graphics; import flash.events.TimerEvent; import flash.utils.Timer; public class RotationExample1 extends MovieClip { private var ellipse:Shape = new Shape(); private var speed:int = 10; private var ellipse1:Shape; private var ellipse2:Shape; public function RotationExample1():void { ellipse1 = drawEllipse(-50, -40, (this.stage.stageWidth / 2), (this.stage.stageHeight / 2)); ellipse2 = drawEllipse(30, 40, (this.stage.stageWidth / 2), (this.stage.stageHeight / 2)); this.addChild(ellipse1); this.addChild(ellipse2); var t:Timer = new Timer(50); t.addEventListener(TimerEvent.TIMER, timerHandler); t.start(); } private function drawEllipse(x1, y1, x2, y2):Shape { var e:Shape = new Shape(); e.graphics.beginFill(0xFF0000); e.graphics.lineStyle(2); e.graphics.drawEllipse(x1, y1, 100, 80); e.graphics.endFill(); e.x = x2; e.y = y2; e.z = 1; return e; } private function timerHandler(event:TimerEvent):void { ellipse1.rotationY += speed; ellipse1.rotationX -= speed; ellipse2.rotationY += speed; ellipse2.rotationX -= speed; } } } The following example shows how you can 3D rotate a Sprite object around its x-axis with Flash Professional, ActionScript 3.0, and Flash Player 10 by setting the object's rotationX property. Example provided by ActionScriptExamples.com. //Requires: // - Slider control UI component in Flash library. // - Publish for Flash Player 10. // [SWF(width="400", height="300")] import fl.controls.Slider; import fl.controls.SliderDirection; import fl.events.SliderEvent; var slider:Slider = new Slider(); slider.direction = SliderDirection.HORIZONTAL; slider.minimum = 0; slider.maximum = 360; slider.value = 45; slider.tickInterval = 45; slider.snapInterval = 1; slider.liveDragging = true; slider.addEventListener(SliderEvent.CHANGE, slider_change); slider.move(10, 10); addChild(slider); var spr:Sprite = new Sprite(); spr.graphics.lineStyle(2, 0xFF0000); spr.graphics.drawRect(0, 0, 100, 80); spr.x = Math.round((stage.stageWidth - spr.width)/2); spr.y = Math.round((stage.stageHeight - spr.height)/2); spr.rotationX = 45; addChild(spr); function slider_change(evt:SliderEvent):void { spr.rotationX = evt.value; } rotationY Indicates the y-axis rotation of the DisplayObject instance, in degrees, from its original orientation relative to the 3D parent container.Number Indicates the y-axis rotation of the DisplayObject instance, in degrees, from its original orientation relative to the 3D parent container. Values from 0 to 180 represent clockwise rotation; values from 0 to -180 represent counterclockwise rotation. Values outside this range are added to or subtracted from 360 to obtain a value within the range. In this example, two ellipses rotate using their rotationX and rotationY properties. The first ellipse's registration point is set to its center. It rotates around itself. The second ellipse rotates around an external point. package { import flash.display.MovieClip; import flash.display.Shape; import flash.geom.*; import flash.display.Graphics; import flash.events.TimerEvent; import flash.utils.Timer; public class RotationExample1 extends MovieClip { private var ellipse:Shape = new Shape(); private var speed:int = 10; private var ellipse1:Shape; private var ellipse2:Shape; public function RotationExample1():void { ellipse1 = drawEllipse(-50, -40, (this.stage.stageWidth / 2), (this.stage.stageHeight / 2)); ellipse2 = drawEllipse(30, 40, (this.stage.stageWidth / 2), (this.stage.stageHeight / 2)); this.addChild(ellipse1); this.addChild(ellipse2); var t:Timer = new Timer(50); t.addEventListener(TimerEvent.TIMER, timerHandler); t.start(); } private function drawEllipse(x1, y1, x2, y2):Shape { var e:Shape = new Shape(); e.graphics.beginFill(0xFF0000); e.graphics.lineStyle(2); e.graphics.drawEllipse(x1, y1, 100, 80); e.graphics.endFill(); e.x = x2; e.y = y2; e.z = 1; return e; } private function timerHandler(event:TimerEvent):void { ellipse1.rotationY += speed; ellipse1.rotationX -= speed; ellipse2.rotationY += speed; ellipse2.rotationX -= speed; } } } rotationZ Indicates the z-axis rotation of the DisplayObject instance, in degrees, from its original orientation relative to the 3D parent container.Number Indicates the z-axis rotation of the DisplayObject instance, in degrees, from its original orientation relative to the 3D parent container. Values from 0 to 180 represent clockwise rotation; values from 0 to -180 represent counterclockwise rotation. Values outside this range are added to or subtracted from 360 to obtain a value within the range. rotation Indicates the rotation of the DisplayObject instance, in degrees, from its original orientation.Number Indicates the rotation of the DisplayObject instance, in degrees, from its original orientation. Values from 0 to 180 represent clockwise rotation; values from 0 to -180 represent counterclockwise rotation. Values outside this range are added to or subtracted from 360 to obtain a value within the range. For example, the statement my_video.rotation = 450 is the same as my_video.rotation = 90. The following code creates a Sprite object and rotates the object when the user clicks it: import flash.display.Sprite; import flash.events.MouseEvent; var square:Sprite = new Sprite(); square.graphics.beginFill(0xFFCC00); square.graphics.drawRect(-50, -50, 100, 100); square.x = 150; square.y = 150; addChild(square); square.addEventListener(MouseEvent.CLICK, rotate); function rotate(event:MouseEvent):void { square.rotation += 15; } scale9Grid The current scaling grid that is in effect.flash.geom:RectangleIf you pass an invalid argument to the method. ArgumentErrorArgumentError The current scaling grid that is in effect. If set to null, the entire display object is scaled normally when any scale transformation is applied.

When you define the scale9Grid property, the display object is divided into a grid with nine regions based on the scale9Grid rectangle, which defines the center region of the grid. The eight other regions of the grid are the following areas:

  • The upper-left corner outside of the rectangle
  • The area above the rectangle
  • The upper-right corner outside of the rectangle
  • The area to the left of the rectangle
  • The area to the right of the rectangle
  • The lower-left corner outside of the rectangle
  • The area below the rectangle
  • The lower-right corner outside of the rectangle

You can think of the eight regions outside of the center (defined by the rectangle) as being like a picture frame that has special rules applied to it when scaled.

When the scale9Grid property is set and a display object is scaled, all text and gradients are scaled normally; however, for other types of objects the following rules apply:

  • Content in the center region is scaled normally.
  • Content in the corners is not scaled.
  • Content in the top and bottom regions is scaled horizontally only. Content in the left and right regions is scaled vertically only.
  • All fills (including bitmaps, video, and gradients) are stretched to fit their shapes.

If a display object is rotated, all subsequent scaling is normal (and the scale9Grid property is ignored).

For example, consider the following display object and a rectangle that is applied as the display object's scale9Grid:

The display object.

The red rectangle shows the scale9Grid.

When the display object is scaled or stretched, the objects within the rectangle scale normally, but the objects outside of the rectangle scale according to the scale9Grid rules:

Scaled to 75%:Scaled to 50%:Scaled to 25%:Stretched horizontally 150%:

A common use for setting scale9Grid is to set up a display object to be used as a component, in which edge regions retain the same width when the component is scaled.

The following code creates a Shape object with a rectangle drawn in its graphics property. The rectangle has a 20-pixel-thick line as the border and it is filled with a gradient. The timer event calls the scale() function, which scales the Shape object by adjusting the scaleX and scaleY properties. The scale9Grid applied to the Shape object prevents the rectangle's border line from scaling — only the gradient fill scales: import flash.display.Shape; import flash.display.GradientType; import flash.display.SpreadMethod; import flash.display.InterpolationMethod; import flash.geom.Matrix; import flash.geom.Rectangle; import flash.utils.Timer; import flash.events.TimerEvent; var square:Shape = new Shape(); square.graphics.lineStyle(20, 0xFFCC00); var gradientMatrix:Matrix = new Matrix(); gradientMatrix.createGradientBox(15, 15, Math.PI, 10, 10); square.graphics.beginGradientFill(GradientType.RADIAL, [0xffff00, 0x0000ff], [100, 100], [0, 0xFF], gradientMatrix, SpreadMethod.REFLECT, InterpolationMethod.RGB, 0.9); square.graphics.drawRect(0, 0, 100, 100); var grid:Rectangle = new Rectangle(20, 20, 60, 60); square.scale9Grid = grid ; addChild(square); var tim:Timer = new Timer(100); tim.start(); tim.addEventListener(TimerEvent.TIMER, scale); var scaleFactor:Number = 1.01; function scale(event:TimerEvent):void { square.scaleX *= scaleFactor; square.scaleY *= scaleFactor; if (square.scaleX > 2.0) { scaleFactor = 0.99; } if (square.scaleX < 1.0) { scaleFactor = 1.01; } }
flash.geom.Rectangle
scaleX Indicates the horizontal scale (percentage) of the object as applied from the registration point.Number Indicates the horizontal scale (percentage) of the object as applied from the registration point. The default registration point is (0,0). 1.0 equals 100% scale.

Scaling the local coordinate system changes the x and y property values, which are defined in whole pixels.

The following code creates a Sprite object with a rectangle drawn in its graphics property. When the user clicks the sprite, it scales by 10%: import flash.display.Sprite; import flash.events.MouseEvent; var square:Sprite = new Sprite(); square.graphics.beginFill(0xFFCC00); square.graphics.drawRect(0, 0, 100, 100); addChild(square); square.addEventListener(MouseEvent.CLICK, scale); function scale(event:MouseEvent):void { square.scaleX *= 1.10; square.scaleY *= 1.10; }
scaleY Indicates the vertical scale (percentage) of an object as applied from the registration point of the object.Number Indicates the vertical scale (percentage) of an object as applied from the registration point of the object. The default registration point is (0,0). 1.0 is 100% scale.

Scaling the local coordinate system changes the x and y property values, which are defined in whole pixels.

The following code creates a Sprite object with a rectangle drawn in its graphics property. When the user clicks the sprite, it scales by 10%: import flash.display.Sprite; import flash.events.MouseEvent; var square:Sprite = new Sprite(); square.graphics.beginFill(0xFFCC00); square.graphics.drawRect(0, 0, 100, 100); addChild(square); square.addEventListener(MouseEvent.CLICK, scale); function scale(event:MouseEvent):void { square.scaleX *= 1.10; square.scaleY *= 1.10; }
scaleZ Indicates the depth scale (percentage) of an object as applied from the registration point of the object.Number Indicates the depth scale (percentage) of an object as applied from the registration point of the object. The default registration point is (0,0). 1.0 is 100% scale.

Scaling the local coordinate system changes the x, y and z property values, which are defined in whole pixels.

z
scrollRect The scroll rectangle bounds of the display object.flash.geom:Rectangle The scroll rectangle bounds of the display object. The display object is cropped to the size defined by the rectangle, and it scrolls within the rectangle when you change the x and y properties of the scrollRect object.

The properties of the scrollRect Rectangle object use the display object's coordinate space and are scaled just like the overall display object. The corner bounds of the cropped window on the scrolling display object are the origin of the display object (0,0) and the point defined by the width and height of the rectangle. They are not centered around the origin, but use the origin to define the upper-left corner of the area. A scrolled display object always scrolls in whole pixel increments.

You can scroll an object left and right by setting the x property of the scrollRect Rectangle object. You can scroll an object up and down by setting the y property of the scrollRect Rectangle object. If the display object is rotated 90° and you scroll it left and right, the display object actually scrolls up and down.

The following example shows how the scrollRect property defines the scrolling area for a display object, circle. When you click the circle object, the clicked() event handler method adjusts the y property of the scrollRect property of the circle object, causing the object to scroll down: import flash.display.Sprite; import flash.geom.Rectangle; import flash.events.MouseEvent; var circle:Sprite = new Sprite(); circle.graphics.beginFill(0xFFCC00); circle.graphics.drawCircle(200, 200, 200); circle.scrollRect = new Rectangle(0, 0, 200, 200); addChild(circle); circle.addEventListener(MouseEvent.CLICK, clicked); function clicked(event:MouseEvent):void { var rect:Rectangle = event.target.scrollRect; rect.y -= 5; event.target.scrollRect = rect; }
flash.geom.Rectangle
stage The Stage of the display object.flash.display:Stage The Stage of the display object. A Flash runtime application has only one Stage object. For example, you can create and load multiple display objects into the display list, and the stage property of each display object refers to the same Stage object (even if the display object belongs to a loaded SWF file).

If a display object is not added to the display list, its stage property is set to null.

The following code creates two TextField objects and uses the width property of the Stage object to position the text fields: import flash.text.TextField; var tf1:TextField = new TextField(); tf1.text = "Text Field 1"; tf1.border = true; tf1.x = 10; addChild(tf1); tf1.width = tf1.stage.stageWidth / 2 - 10; var tf2:TextField = new TextField(); tf2.text = "Text Field 2"; tf2.border = true; tf2.x = tf1.x + tf1.width + 5; addChild(tf2); tf2.width = tf2.stage.stageWidth / 2 - 10; trace(stage.stageWidth);
transform An object with properties pertaining to a display object's matrix, color transform, and pixel bounds.flash.geom:Transform An object with properties pertaining to a display object's matrix, color transform, and pixel bounds. The specific properties — matrix, colorTransform, and three read-only properties (concatenatedMatrix, concatenatedColorTransform, and pixelBounds) — are described in the entry for the Transform class.

Each of the transform object's properties is itself an object. This concept is important because the only way to set new values for the matrix or colorTransform objects is to create a new object and copy that object into the transform.matrix or transform.colorTransform property.

For example, to increase the tx value of a display object's matrix, you must make a copy of the entire matrix object, then copy the new object into the matrix property of the transform object:


    var myMatrix:Matrix = myDisplayObject.transform.matrix;  
    myMatrix.tx += 10; 
    myDisplayObject.transform.matrix = myMatrix;  
    

You cannot directly set the tx property. The following code has no effect on myDisplayObject:


    myDisplayObject.transform.matrix.tx += 10;
    

You can also copy an entire transform object and assign it to another display object's transform property. For example, the following code copies the entire transform object from myOldDisplayObj to myNewDisplayObj:

myNewDisplayObj.transform = myOldDisplayObj.transform;

The resulting display object, myNewDisplayObj, now has the same values for its matrix, color transform, and pixel bounds as the old display object, myOldDisplayObj.

Note that AIR for TV devices use hardware acceleration, if it is available, for color transforms.

The following code sets up a square Sprite object. When the user clicks the sprite, the transformer() method adjusts the colorTransform and matrix properties of the transform property of the sprite: import flash.display.Sprite; import flash.geom.ColorTransform; import flash.geom.Matrix; import flash.geom.Transform; import flash.events.MouseEvent; var square:Sprite = new Sprite(); square.graphics.lineStyle(20, 0xFF2200); square.graphics.beginFill(0x0000DD); square.graphics.drawRect(0, 0, 100, 100); addChild(square); var resultColorTransform:ColorTransform = new ColorTransform(); resultColorTransform.alphaMultiplier = 0.5; resultColorTransform.redOffset = 155; resultColorTransform.greenMultiplier = 0.5; var skewMatrix:Matrix = new Matrix(1, 1, 0, 1); square.addEventListener(MouseEvent.CLICK, transformer); function transformer(event:MouseEvent):void { var transformation:Transform = square.transform; var tempMatrix:Matrix = square.transform.matrix; tempMatrix.concat(skewMatrix); square.transform.colorTransform = resultColorTransform; square.transform.matrix = tempMatrix; }
Transform class
visible Whether or not the display object is visible.Boolean Whether or not the display object is visible. Display objects that are not visible are disabled. For example, if visible=false for an InteractiveObject instance, it cannot be clicked. The following code uses a Timer object to call a function that periodically changes the visible property of a display object, resulting in a blinking effect: import flash.text.TextField; import flash.utils.Timer; import flash.events.TimerEvent; var tf:TextField = new TextField(); tf.text = "Hello."; addChild(tf); var tim:Timer = new Timer(250); tim.start(); tim.addEventListener(TimerEvent.TIMER, blinker); function blinker(event:TimerEvent):void { tf.visible = !tf.visible; } width Indicates the width of the display object, in pixels.Number Indicates the width of the display object, in pixels. The width is calculated based on the bounds of the content of the display object. When you set the width property, the scaleX property is adjusted accordingly, as shown in the following code: var rect:Shape = new Shape(); rect.graphics.beginFill(0xFF0000); rect.graphics.drawRect(0, 0, 100, 100); trace(rect.scaleX) // 1; rect.width = 200; trace(rect.scaleX) // 2;

Except for TextField and Video objects, a display object with no content (such as an empty sprite) has a width of 0, even if you try to set width to a different value.

The following code sets up a square Sprite object. When the user clicks the sprite, the widen() method increases the width property of the sprite: import flash.display.Sprite; import flash.events.MouseEvent; var square:Sprite = new Sprite(); square.graphics.beginFill(0xFF0000); square.graphics.drawRect(0, 0, 100, 100); addChild(square); square.addEventListener(MouseEvent.CLICK, widen); function widen(event:MouseEvent):void { square.width += 10; }
x Indicates the x coordinate of the DisplayObject instance relative to the local coordinates of the parent DisplayObjectContainer.Number Indicates the x coordinate of the DisplayObject instance relative to the local coordinates of the parent DisplayObjectContainer. If the object is inside a DisplayObjectContainer that has transformations, it is in the local coordinate system of the enclosing DisplayObjectContainer. Thus, for a DisplayObjectContainer rotated 90° counterclockwise, the DisplayObjectContainer's children inherit a coordinate system that is rotated 90° counterclockwise. The object's coordinates refer to the registration point position. The following code sets up a circle Sprite object. A Timer object is used to change the x property of the sprite every 50 milliseconds: import flash.display.Sprite; import flash.utils.Timer; import flash.events.TimerEvent; var circle:Sprite = new Sprite(); circle.graphics.beginFill(0xFF0000); circle.graphics.drawCircle(100, 100, 100); addChild(circle); var tim:Timer = new Timer(50); tim.start(); tim.addEventListener(TimerEvent.TIMER, bounce); var xInc:Number = 2; function bounce(event:TimerEvent):void { circle.x += xInc; if (circle.x > circle.width) { xInc = -2; } if (circle.x < 0) { xInc = 2; } } y Indicates the y coordinate of the DisplayObject instance relative to the local coordinates of the parent DisplayObjectContainer.Number Indicates the y coordinate of the DisplayObject instance relative to the local coordinates of the parent DisplayObjectContainer. If the object is inside a DisplayObjectContainer that has transformations, it is in the local coordinate system of the enclosing DisplayObjectContainer. Thus, for a DisplayObjectContainer rotated 90° counterclockwise, the DisplayObjectContainer's children inherit a coordinate system that is rotated 90° counterclockwise. The object's coordinates refer to the registration point position. The following code creates two TextField objects and adjusts the height property of each based on the textHeight property of each; it also positions the second text field by setting its y property: import flash.text.TextField; var tf1:TextField = new TextField(); tf1.text = "Text Field 1"; tf1.border = true; tf1.wordWrap = true; tf1.width = 40; tf1.height = tf1.textHeight + 5; addChild(tf1); var tf2:TextField = new TextField(); tf2.text = "Text Field 2"; tf2.border = true; tf2.wordWrap = true; tf2.width = 40; tf2.height = tf2.textHeight + 5; tf2.y = tf1.y + tf1.height + 5; addChild(tf2); z Indicates the z coordinate position along the z-axis of the DisplayObject instance relative to the 3D parent container.Number Indicates the z coordinate position along the z-axis of the DisplayObject instance relative to the 3D parent container. The z property is used for 3D coordinates, not screen or pixel coordinates.

When you set a z property for a display object to something other than the default value of 0, a corresponding Matrix3D object is automatically created. for adjusting a display object's position and orientation in three dimensions. When working with the z-axis, the existing behavior of x and y properties changes from screen or pixel coordinates to positions relative to the 3D parent container.

For example, a child of the _root at position x = 100, y = 100, z = 200 is not drawn at pixel location (100,100). The child is drawn wherever the 3D projection calculation puts it. The calculation is:

(x~~cameraFocalLength/cameraRelativeZPosition, y~~cameraFocalLength/cameraRelativeZPosition)

This example draws two ellipses and has them go back and forth (down and up the z axis) toward the vanishing point. One ellipse is set to move faster than the other. package { import flash.display.MovieClip; import flash.display.Shape; import flash.display.Graphics; import flash.events.Event; import flash.geom.*; public class ZAxisExample1 extends MovieClip { private var ellipse1Back:int = 1; private var ellipse2Back:int = 1; private var depth:int = 1000; public function ZAxisExample1():void { var ellipse1 = drawEllipse((this.stage.stageWidth / 2) - 100, (this.stage.stageHeight / 2), 100, 80, 10); var ellipse2 = drawEllipse((this.stage.stageWidth / 2) + 100, (this.stage.stageHeight / 2), 100, 80, 300); this.addChild(ellipse1); this.addChild(ellipse2); ellipse1.addEventListener(Event.ENTER_FRAME, ellipse1FrameHandler); ellipse2.addEventListener(Event.ENTER_FRAME, ellipse2FrameHandler); } private function drawEllipse(x:Number, y:Number, w:Number, h:Number, z:Number):Shape { var s:Shape = new Shape(); s.z = z; s.graphics.beginFill(0xFF0000); s.graphics.lineStyle(2); s.graphics.drawEllipse(x, y, w, h); s.graphics.endFill(); return s; } private function ellipse1FrameHandler(e:Event):void { ellipse1Back = setDepth(e, ellipse1Back); e.currentTarget.z += ellipse1Back * 10; } private function ellipse2FrameHandler(e:Event):void { ellipse2Back = setDepth(e, ellipse2Back); e.currentTarget.z += ellipse2Back * 20; } private function setDepth(e:Event, d:int):int { if(e.currentTarget.z > depth) { e.currentTarget.z = depth; d = -1; }else if (e.currentTarget.z < 0) { e.currentTarget.z = 0; d = 1; } return d; } } }
flash.geom.PerspectiveProjectionflash.geom.Matrix3Dtransform
blendShader Sets a shader that is used for blending the foreground and background.flash.display:ShaderWhen the shader output type is not compatible with this operation (the shader must specify a pixel4 output). ArgumentErrorArgumentErrorWhen the shader specifies fewer than two image inputs or the first two inputs are not image4 inputs. ArgumentErrorArgumentErrorWhen the shader specifies an image input that isn't provided. ArgumentErrorArgumentErrorWhen a ByteArray or Vector.<Number> instance is used as an input and the width and height properties aren't specified for the ShaderInput, or the specified values don't match the amount of data in the input object. See the ShaderInput.input property for more information. ArgumentErrorArgumentError Sets a shader that is used for blending the foreground and background. When the blendMode property is set to BlendMode.SHADER, the specified Shader is used to create the blend mode output for the display object.

Setting the blendShader property of a display object to a Shader instance automatically sets the display object's blendMode property to BlendMode.SHADER. If the blendShader property is set (which sets the blendMode property to BlendMode.SHADER), then the value of the blendMode property is changed, the blend mode can be reset to use the blend shader simply by setting the blendMode property to BlendMode.SHADER. The blendShader property does not need to be set again except to change the shader that's used for the blend mode.

The Shader assigned to the blendShader property must specify at least two image4 inputs. The inputs do not need to be specified in code using the associated ShaderInput objects' input properties. The background display object is automatically used as the first input (the input with index 0). The foreground display object is used as the second input (the input with index 1). A shader used as a blend shader can specify more than two inputs. In that case, any additional input must be specified by setting its ShaderInput instance's input property.

When you assign a Shader instance to this property the shader is copied internally. The blend operation uses that internal copy, not a reference to the original shader. Any changes made to the shader, such as changing a parameter value, input, or bytecode, are not applied to the copied shader that's used for the blend mode.

flash.display.BlendModeflash.display.Shaderflash.display.ShaderInput
Loader The Loader class is used to load SWF files or image (JPG, PNG, or GIF) files.flash.display:DisplayObjectContainer The Loader class is used to load SWF files or image (JPG, PNG, or GIF) files. Use the load() method to initiate loading. The loaded display object is added as a child of the Loader object.

Use the URLLoader class to load text or binary data.

The Loader class overrides the following methods that it inherits, because a Loader object can only have one child display object—the display object that it loads. Calling the following methods throws an exception: addChild(), addChildAt(), removeChild(), removeChildAt(), and setChildIndex(). To remove a loaded display object, you must remove the Loader object from its parent DisplayObjectContainer child array.

Note: The ActionScript 2.0 MovieClipLoader and LoadVars classes are not used in ActionScript 3.0. The Loader and URLLoader classes replace them.

When you use the Loader class, consider the Flash Player and Adobe AIR security model:

  • You can load content from any accessible source.
  • Loading is not allowed if the calling SWF file is in a network sandbox and the file to be loaded is local.
  • If the loaded content is a SWF file written with ActionScript 3.0, it cannot be cross-scripted by a SWF file in another security sandbox unless that cross-scripting arrangement was approved through a call to the System.allowDomain() or the System.allowInsecureDomain() method in the loaded content file.
  • If the loaded content is an AVM1 SWF file (written using ActionScript 1.0 or 2.0), it cannot be cross-scripted by an AVM2 SWF file (written using ActionScript 3.0). However, you can communicate between the two SWF files by using the LocalConnection class.
  • If the loaded content is an image, its data cannot be accessed by a SWF file outside of the security sandbox, unless the domain of that SWF file was included in a URL policy file at the origin domain of the image.
  • Movie clips in the local-with-file-system sandbox cannot script movie clips in the local-with-networking sandbox, and the reverse is also prevented.
  • You cannot connect to commonly reserved ports. For a complete list of blocked ports, see "Restricting Networking APIs" in the ActionScript 3.0 Developer's Guide.

However, in AIR, content in the application security sandbox (content installed with the AIR application) are not restricted by these security limitations.

For more information related to security, see the Flash Player Developer Center Topic: Security.

When loading a SWF file from an untrusted source (such as a domain other than that of the Loader object's root SWF file), you may want to define a mask for the Loader object, to prevent the loaded content (which is a child of the Loader object) from drawing to portions of the Stage outside of that mask, as shown in the following code:

import flash.display.~~; import flash.net.URLRequest; var rect:Shape = new Shape(); rect.graphics.beginFill(0xFFFFFF); rect.graphics.drawRect(0, 0, 100, 100); rect.graphics.endFill(); addChild(rect); var ldr:Loader = new Loader(); ldr.mask = rect; var url:String = "http://www.unknown.example.com/content.swf"; var urlReq:URLRequest = new URLRequest(url); ldr.load(urlReq); addChild(ldr);
The following example uses the LoaderExample class to illustrate how various event listeners are used. This task is accomplished by performing the following steps:
  1. A url property is created, which is the location and name of the image file
  2. In the LoaderExample constructor, a new Loader object named loader is created, which is then passed to the configureListeners() method, described in step 3.
  3. The constructor creates a new instance of a URLRequest object, request, with url passed so that the file name and location are known.
  4. The request object is passed to the loader object's load() method, which loads the image onto the display list.
  5. A clickHandler event listener is registered for the click event on the loader. After a mouse click, the loaded image is unloaded.
  6. The configureListeners() method adds seven event listeners by using the following methods:
    • The completeHandler() method executes when the image finishes loading.
    • The httpStatusHandler() method executes if the image is not loaded locally and only if the network request is made available and the Flash Player can detect it.
    • The initHandler() method executes before the completeHandler() method and after the progressHandler() method. Generally, the init event is more useful when loading SWF files.
    • The ioErrorHandler() method executes if the image file is not available or not accessible.
    • The openHandler() method executes when the image file is first opened.
    • The progressHandler() method executes when the image file starts to load and again when the image is finished loading.
    • The unLoadHandler() method executes when the image is unloaded by using the unload() method when the user clicks the image.

Keep in mind the following requirements:

  • This example requires that you place a file named Image.gif in the same directory as the compiled SWF file. Use an image that has an area that fits within the dimensions of the main SWF file.
  • Although this example makes use of all events available to the LoaderInfo object, most situations require only a subset. In particular, when loading only an image file, the complete event (and perhaps the ioError event) are sufficient when loading a local image.
package { import flash.display.Loader; import flash.display.Sprite; import flash.events.*; import flash.net.URLRequest; public class LoaderExample extends Sprite { private var url:String = "Image.gif"; public function LoaderExample() { var loader:Loader = new Loader(); configureListeners(loader.contentLoaderInfo); loader.addEventListener(MouseEvent.CLICK, clickHandler); var request:URLRequest = new URLRequest(url); loader.load(request); addChild(loader); } private function configureListeners(dispatcher:IEventDispatcher):void { dispatcher.addEventListener(Event.COMPLETE, completeHandler); dispatcher.addEventListener(HTTPStatusEvent.HTTP_STATUS, httpStatusHandler); dispatcher.addEventListener(Event.INIT, initHandler); dispatcher.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler); dispatcher.addEventListener(Event.OPEN, openHandler); dispatcher.addEventListener(ProgressEvent.PROGRESS, progressHandler); dispatcher.addEventListener(Event.UNLOAD, unLoadHandler); } private function completeHandler(event:Event):void { trace("completeHandler: " + event); } private function httpStatusHandler(event:HTTPStatusEvent):void { trace("httpStatusHandler: " + event); } private function initHandler(event:Event):void { trace("initHandler: " + event); } private function ioErrorHandler(event:IOErrorEvent):void { trace("ioErrorHandler: " + event); } private function openHandler(event:Event):void { trace("openHandler: " + event); } private function progressHandler(event:ProgressEvent):void { trace("progressHandler: bytesLoaded=" + event.bytesLoaded + " bytesTotal=" + event.bytesTotal); } private function unLoadHandler(event:Event):void { trace("unLoadHandler: " + event); } private function clickHandler(event:MouseEvent):void { trace("clickHandler: " + event); var loader:Loader = Loader(event.target); loader.unload(); } } }
flash.display.LoaderInfoflash.net.URLLoaderflash.display.DisplayObjectLoader Creates a Loader object that you can use to load files, such as SWF, JPEG, GIF, or PNG files. Creates a Loader object that you can use to load files, such as SWF, JPEG, GIF, or PNG files. Call the load() method to load the asset as a child of the Loader instance. You can then add the Loader object to the display list (for instance, by using the addChild() method of a DisplayObjectContainer instance). The asset appears on the Stage as it loads.

You can also use a Loader instance "offlist," that is without adding it to a display object container on the display list. In this mode, the Loader instance might be used to load a SWF file that contains additional modules of an application.

To detect when the SWF file is finished loading, you can use the events of the LoaderInfo object associated with the contentLoaderInfo property of the Loader object. At that point, the code in the module SWF file can be executed to initialize and start the module. In the offlist mode, a Loader instance might also be used to load a SWF file that contains components or media assets. Again, you can use the LoaderInfo object event notifications to detect when the components are finished loading. At that point, the application can start using the components and media assets in the library of the SWF file by instantiating the ActionScript 3.0 classes that represent those components and assets.

To determine the status of a Loader object, monitor the following events that the LoaderInfo object associated with the contentLoaderInfo property of the Loader object:

  • The open event is dispatched when loading begins.
  • The ioError or securityError event is dispatched if the file cannot be loaded or if an error occured during the load process.
  • The progress event fires continuously while the file is being loaded.
  • The complete event is dispatched when a file completes downloading, but before the loaded movie clip's methods and properties are available.
  • The init event is dispatched after the properties and methods of the loaded SWF file are accessible, so you can begin manipulating the loaded SWF file. This event is dispatched before the complete handler. In streaming SWF files, the init event can occur significantly earlier than the complete event. For most purposes, use the init handler.
flash.display.Loader.load()flash.display.LoaderInfo
close Cancels a load() method operation that is currently in progress for the Loader instance. Cancels a load() method operation that is currently in progress for the Loader instance. flash.display.Loader.load()loadBytes Loads from binary data stored in a ByteArray object.If the length property of the ByteArray object is not greater than 0. ArgumentErrorArgumentErrorIf the checkPolicyFile or securityDomain property of the context parameter are non-null. IllegalOperationErrorflash.errors:IllegalOperationErrorIf the requestedContentParent property of the context parameter is a Loader. IllegalOperationErrorflash.errors:IllegalOperationErrorIf the LoaderContext.parameters parameter is set to non-null and has some values which are not Strings. IllegalOperationErrorflash.errors:IllegalOperationErrorIf the provided applicationDomain property of the context property is from a disallowed domain. SecurityErrorSecurityErrorYou cannot connect to commonly reserved ports. For a complete list of blocked ports, see "Restricting Networking APIs" in the ActionScript 3.0 Developer's Guide. SecurityErrorSecurityErrorbytesflash.utils:ByteArrayA ByteArray object. The contents of the ByteArray can be any of the file formats supported by the Loader class: SWF, GIF, JPEG, or PNG. contextflash.system:LoaderContextnullA LoaderContext object. Only the applicationDomain property of the LoaderContext object applies; the checkPolicyFile and securityDomain properties of the LoaderContext object do not apply.

If the context parameter is not specified or refers to a null object, the content is loaded into the current security domain— a process referred to as "import loading" in Flash Player security documentation. Specifically, if the loading SWF file trusts the remote SWF by incorporating the remote SWF into its code, then the loading SWF can import it directly into its own security domain.

For more information related to security, see the Flash Player Developer Center Topic: Security.

Loads from binary data stored in a ByteArray object.

The loadBytes() method is asynchronous. You must wait for the "init" event before accessing the properties of a loaded object.

When you use this method, consider the Flash Player security model, which is described in the Loader class description.

flash.utils.ByteArrayflash.system.LoaderContext.applicationDomainasyncErrorflash.events:AsyncErrorEventDispatched by the contentLoaderInfo object if the LoaderContext.requestedContentParent property has been specified and it is not possible to add the loaded content as a child to the specified DisplayObjectContainer. This could happen if the loaded content is a flash.display.AVM1Movie or if the addChild() call to the requestedContentParent throws an error. Dispatched by the contentLoaderInfo object if the LoaderContext.requestedContentParent property has been specified and it is not possible to add the loaded content as a child to the specified DisplayObjectContainer.completeflash.events:EventDispatched by the contentLoaderInfo object when the operation is complete. The complete event is always dispatched after the init event. Dispatched by the contentLoaderInfo object when the operation is complete.initflash.events:EventDispatched by the contentLoaderInfo object when the properties and methods of the loaded data are accessible. The init event always precedes the complete event. Dispatched by the contentLoaderInfo object when the properties and methods of the loaded data are accessible.ioErrorflash.events:IOErrorEventDispatched by the contentLoaderInfo object when the runtime cannot parse the data in the byte array. Dispatched by the contentLoaderInfo object when the runtime cannot parse the data in the byte array.openflash.events:EventDispatched by the contentLoaderInfo object when the operation starts. Dispatched by the contentLoaderInfo object when the operation starts.progressflash.events:ProgressEventDispatched by the contentLoaderInfo object as data is transfered in memory. Dispatched by the contentLoaderInfo object as data is transfered in memory.securityErrorflash.events:SecurityErrorEventDispatched by the contentLoaderInfo object if the LoaderContext.requestedContentParent property has been specified and the security sandbox of the LoaderContext.requestedContentParent does not have access to the loaded SWF. Dispatched by the contentLoaderInfo object if the LoaderContext.requestedContentParent property has been specified and the security sandbox of the LoaderContext.requestedContentParent does not have access to the loaded SWF.unloadflash.events:EventDispatched by the contentLoaderInfo object when a loaded object is removed. Dispatched by the contentLoaderInfo object when a loaded object is removed.
loadFilePromise Loads an IFilePromise instance.If the requestedContentParent property of the context parameter is a Loader. IllegalOperationErrorflash.errors:IllegalOperationErrorIf the LoaderContext.parameters parameter is set to non-null and has some values which are not Strings. IllegalOperationErrorflash.errors:IllegalOperationErrorIf the IFilePromise object passed as parameter is null ArgumentErrorArgumentErrorpromiseflash.desktop:IFilePromiseA IFilePromise object. The data source of the object can be any of the file formats supported by the Loader class: SWF, GIF, JPEG, or PNG. contextflash.system:LoaderContextnullA LoaderContext object. Only the applicationDomain property of the LoaderContext object applies; the checkPolicyFile and securityDomain properties of the LoaderContext object do not apply.

If the context parameter is not specified or refers to a null object, the content is loaded into the current security domain— a process referred to as "import loading" in Flash Player security documentation. Specifically, if the loading SWF file trusts the remote SWF by incorporating the remote SWF into its code, then the loading SWF can import it directly into its own security domain.

For more information related to security, see the Flash Player Developer Center Topic: Security.

Loads an IFilePromise instance.

The loadFilePromise method takes an IFilePromise object and loads the binary data. If the data is a progressive stream, such as a video wait for the "init" or progress events before accessing the properties of the loaded object. Otherwise, wait for the complete event to make sure that the data is fully loaded.

When you use this method, consider the Flash Player security model, which is described in the Loader class description.

MediaPromiseCameraRoll.browseForImage()CameraUIasyncErrorflash.events:AsyncErrorEventDispatched by the contentLoaderInfo object if the LoaderContext.requestedContentParent property has been specified and it is not possible to add the loaded content as a child to the specified DisplayObjectContainer. This could happen if the loaded content is a flash.display.AVM1Movie or if the addChild() call to the requestedContentParent throws an error. Dispatched by the contentLoaderInfo object if the LoaderContext.requestedContentParent property has been specified and it is not possible to add the loaded content as a child to the specified DisplayObjectContainer.completeflash.events:EventDispatched by the contentLoaderInfo object when the operation is complete. The complete event is always dispatched after the init event. Dispatched by the contentLoaderInfo object when the operation is complete.initflash.events:EventDispatched by the contentLoaderInfo object when the properties and methods of the loaded data are accessible. The init event always precedes the complete event. Dispatched by the contentLoaderInfo object when the properties and methods of the loaded data are accessible.ioErrorflash.events:IOErrorEventDispatched by the contentLoaderInfo object when the runtime cannot parse the data in the data source or if the data source stream is not readable. Dispatched by the contentLoaderInfo object when the runtime cannot parse the data in the data source or if the data source stream is not readable.openflash.events:EventDispatched by the contentLoaderInfo object when the operation starts. Dispatched by the contentLoaderInfo object when the operation starts.progressflash.events:ProgressEventDispatched by the contentLoaderInfo object as data is transfered in memory. Dispatched by the contentLoaderInfo object as data is transfered in memory.securityErrorflash.events:SecurityErrorEventDispatched by the contentLoaderInfo object if the LoaderContext.requestedContentParent property has been specified and the security sandbox of the LoaderContext.requestedContentParent does not have access to the loaded SWF. Dispatched by the contentLoaderInfo object if the LoaderContext.requestedContentParent property has been specified and the security sandbox of the LoaderContext.requestedContentParent does not have access to the loaded SWF.unloadflash.events:EventDispatched by the contentLoaderInfo object when a loaded object is removed. Dispatched by the contentLoaderInfo object when a loaded object is removed.
load Loads a SWF, JPEG, progressive JPEG, unanimated GIF, or PNG file into an object that is a child of this Loader object.The digest property of the request object is not null. You should only set the digest property of a URLRequest object when calling the URLLoader.load() method when loading a SWZ file (an Adobe platform component). IOErrorflash.errors:IOErrorThe value of LoaderContext.securityDomain must be either null or SecurityDomain.currentDomain. This reflects the fact that you can only place the loaded media in its natural security sandbox or your own (the latter requires a policy file). SecurityErrorSecurityErrorLocal SWF files may not set LoaderContext.securityDomain to anything other than null. It is not permitted to import non-local media into a local sandbox, or to place other local media in anything other than its natural sandbox. SecurityErrorSecurityError You cannot connect to commonly reserved ports. For a complete list of blocked ports, see "Restricting Networking APIs" in the ActionScript 3.0 Developer's Guide. SecurityErrorSecurityErrorIf the applicationDomain or securityDomain properties of the context parameter are from a disallowed domain. SecurityErrorSecurityErrorIf a local SWF file is attempting to use the securityDomain property of the context parameter. SecurityErrorSecurityErrorIf the requestedContentParent property of the context parameter is a Loader. IllegalOperationErrorflash.errors:IllegalOperationErrorIf the LoaderContext.parameters parameter is set to non-null and has some values which are not Strings. IllegalOperationErrorflash.errors:IllegalOperationErrorrequestflash.net:URLRequest The absolute or relative URL of the SWF, JPEG, GIF, or PNG file to be loaded. A relative path must be relative to the main SWF file. Absolute URLs must include the protocol reference, such as http:// or file:///. Filenames cannot include disk drive specifications. contextflash.system:LoaderContextnullA LoaderContext object, which has properties that define the following:
  • Whether or not to check for the existence of a policy file upon loading the object
  • The ApplicationDomain for the loaded object
  • The SecurityDomain for the loaded object
  • The ImageDecodingPolicy for the loaded image object

If the context parameter is not specified or refers to a null object, the loaded content remains in its own security domain.

For complete details, see the description of the properties in the LoaderContext class.

Loads a SWF file or image file into a DisplayObject that is a child of this Loader instance.
Loads a SWF, JPEG, progressive JPEG, unanimated GIF, or PNG file into an object that is a child of this Loader object. If you load an animated GIF file, only the first frame is displayed. As the Loader object can contain only a single child, issuing a subsequent load() request terminates the previous request, if still pending, and commences a new load.

Note: In AIR 1.5 and Flash Player 10, the maximum size for a loaded image is 8,191 pixels in width or height, and the total number of pixels cannot exceed 16,777,215 pixels. (So, if an loaded image is 8,191 pixels wide, it can only be 2,048 pixels high.) In Flash Player 9 and earlier and AIR 1.1 and earlier, the limitation is 2,880 pixels in height and 2,880 pixels in width.

A SWF file or image loaded into a Loader object inherits the position, rotation, and scale properties of the parent display objects of the Loader object.

Use the unload() method to remove movies or images loaded with this method, or to cancel a load operation that is in progress.

You can prevent a SWF file from using this method by setting the allowNetworking parameter of the the object and embed tags in the HTML page that contains the SWF content.

When you use this method, consider the Flash Player security model, which is described in the Loader class description.

In Flash Player 10 and later, if you use a multipart Content-Type (for example "multipart/form-data") that contains an upload (indicated by a "filename" parameter in a "content-disposition" header within the POST body), the POST operation is subject to the security rules applied to uploads:

  • The POST operation must be performed in response to a user-initiated action, such as a mouse click or key press.
  • If the POST operation is cross-domain (the POST target is not on the same server as the SWF file that is sending the POST request), the target server must provide a URL policy file that permits cross-domain access.

Also, for any multipart Content-Type, the syntax must be valid (according to the RFC2046 standard). If the syntax appears to be invalid, the POST operation is subject to the security rules applied to uploads.

For more information related to security, see the Flash Player Developer Center Topic: Security.

contentLoaderInfoflash.net.URLRequestflash.display.DisplayObjectflash.display.Loader.unload()flash.display.LoaderInfoflash.system.LoaderContextasyncErrorflash.events:AsyncErrorEventDispatched by the contentLoaderInfo object if the LoaderContext.requestedContentParent property has been specified and it is not possible to add the loaded content as a child to the specified DisplayObjectContainer. This could happen if the loaded content is a flash.display.AVM1Movie or if the addChild() call to the requestedContentParent throws an error. Dispatched by the contentLoaderInfo object if the LoaderContext.requestedContentParent property has been specified and it is not possible to add the loaded content as a child to the specified DisplayObjectContainer.completeflash.events:EventDispatched by the contentLoaderInfo object when the file has completed loading. The complete event is always dispatched after the init event. Dispatched by the contentLoaderInfo object when the file has completed loading.httpStatusflash.events:HTTPStatusEventDispatched by the contentLoaderInfo object when a network request is made over HTTP and Flash Player can detect the HTTP status code. Dispatched by the contentLoaderInfo object when a network request is made over HTTP and Flash Player can detect the HTTP status code.initflash.events:EventDispatched by the contentLoaderInfo object when the properties and methods of the loaded SWF file are accessible. The init event always precedes the complete event. Dispatched by the contentLoaderInfo object when the properties and methods of the loaded SWF file are accessible.ioErrorflash.events:IOErrorEventDispatched by the contentLoaderInfo object when an input or output error occurs that causes a load operation to fail. Dispatched by the contentLoaderInfo object when an input or output error occurs that causes a load operation to fail.openflash.events:EventDispatched by the contentLoaderInfo object when the loading operation starts. Dispatched by the contentLoaderInfo object when the loading operation starts.progressflash.events:ProgressEventDispatched by the contentLoaderInfo object as data is received while load operation progresses. Dispatched by the contentLoaderInfo object as data is received while load operation progresses.securityErrorflash.events:SecurityErrorEventDispatched by the contentLoaderInfo object if a SWF file in the local-with-filesystem sandbox attempts to load content in the local-with-networking sandbox, or vice versa. Dispatched by the contentLoaderInfo object if a SWF file in the local-with-filesystem sandbox attempts to load content in the local-with-networking sandbox, or vice versa.securityErrorflash.events:SecurityErrorEventDispatched by the contentLoaderInfo object if the LoaderContext.requestedContentParent property has been specified and the security sandbox of the LoaderContext.requestedContentParent does not have access to the loaded SWF. Dispatched by the contentLoaderInfo object if the LoaderContext.requestedContentParent property has been specified and the security sandbox of the LoaderContext.requestedContentParent does not have access to the loaded SWF.unloadflash.events:EventDispatched by the contentLoaderInfo object when a loaded object is removed. Dispatched by the contentLoaderInfo object when a loaded object is removed.
unloadAndStop Attempts to unload child SWF file contents and stops the execution of commands from loaded SWF files.gcBooleantrueProvides a hint to the garbage collector to run on the child SWF objects (true) or not (false). If you are unloading many objects asynchronously, setting the gc paramter to false might improve application performance. However, if the parameter is set to false, media and display objects of the child SWF file might persist in memory after running the unloadAndStop() command. Attempts to unload child SWF file contents and stops the execution of commands from loaded SWF files. This method attempts to unload SWF files that were loaded using Loader.load() or Loader.loadBytes() by removing references to EventDispatcher, NetConnection, Timer, Sound, or Video objects of the child SWF file. As a result, the following occurs for the child SWF file and the child SWF file's display list:
  • Sounds are stopped.
  • Stage event listeners are removed.
  • Event listeners for enterFrame, frameConstructed, exitFrame, activate and deactivate are removed.
  • Timers are stopped.
  • Camera and Microphone instances are detached
  • Movie clips are stopped.
flash.display.DisplayObjectflash.display.Loader.load()
unload Removes a child of this Loader object that was loaded by using the load() method. Removes a child of this Loader object that was loaded by using the load() method. The property of the associated LoaderInfo object is reset to null. The child is not necessarily destroyed because other objects might have references to it; however, it is no longer a child of the Loader object.

As a best practice, before you unload a child SWF file, you should explicitly close any streams in the child SWF file's objects, such as LocalConnection, NetConnection, NetStream, and Sound objects. Otherwise, audio in the child SWF file might continue to play, even though the child SWF file was unloaded. To close streams in the child SWF file, add an event listener to the child that listens for the unload event. When the parent calls Loader.unload(), the unload event is dispatched to the child. The following code shows how you might do this:

function closeAllStreams(evt:Event) { 
    myNetStream.close();
    mySound.close();
    myNetConnection.close();
    myLocalConnection.close();
}

myMovieClip.loaderInfo.addEventListener(Event.UNLOAD, closeAllStreams);
Loader.load()flash.media.Sound.close()flash.net.LocalConnection.close()flash.net.NetConnection.close()flash.net.NetStream.close()delete operator
contentLoaderInfo Returns a LoaderInfo object corresponding to the object being loaded.flash.display:LoaderInfo Returns a LoaderInfo object corresponding to the object being loaded. LoaderInfo objects are shared between the Loader object and the loaded content object. The LoaderInfo object supplies loading progress information and statistics about the loaded file.

Events related to the load are dispatched by the LoaderInfo object referenced by the contentLoaderInfo property of the Loader object. The contentLoaderInfo property is set to a valid LoaderInfo object, even before the content is loaded, so that you can add event listeners to the object prior to the load.

To detect uncaught errors that happen in a loaded SWF, use the Loader.uncaughtErrorEvents property, not the Loader.contentLoaderInfo.uncaughtErrorEvents property.

The following example shows how you can load and position an image in ActionScript 3.0 using the Loader class and the complete event on the Loader object's contentLoaderInfo property. Example provided by ActionScriptExamples.com. var url:String = "http://www.helpexamples.com/flash/images/image2.jpg"; var urlRequest:URLRequest = new URLRequest(url); var loader:Loader = new Loader(); loader.contentLoaderInfo.addEventListener(Event.COMPLETE, loader_complete); loader.load(urlRequest); addChild(loader); function loader_complete(evt:Event):void { var target_mc:Loader = evt.currentTarget.loader as Loader; target_mc.x = (stage.stageWidth - target_mc.width) / 2; target_mc.y = (stage.stageHeight - target_mc.height) / 2; }
flash.display.LoaderInfo
content Contains the root display object of the SWF file or image (JPG, PNG, or GIF) file that was loaded by using the load() or loadBytes() methods.flash.display:DisplayObjectThe loaded SWF file or image file belongs to a security sandbox to which you do not have access. For a loaded SWF file, you can avoid this situation by having the file call the Security.allowDomain() method or by having the loading file specify a loaderContext parameter with its securityDomain property set to SecurityDomain.currentDomain when you call the load() or loadBytes() method. SecurityErrorSecurityError Contains the root display object of the SWF file or image (JPG, PNG, or GIF) file that was loaded by using the load() or loadBytes() methods. flash.display.DisplayObjectflash.display.Loader.load()uncaughtErrorEvents An object that dispatches an uncaughtError event when an unhandled error occurs in the SWF that's loaded by this Loader object.flash.events:UncaughtErrorEvents An object that dispatches an uncaughtError event when an unhandled error occurs in the SWF that's loaded by this Loader object. An uncaught error happens when an error is thrown outside of any try..catch blocks or when an ErrorEvent object is dispatched with no registered listeners.

Note that a Loader object's uncaughtErrorEvents property dispatches events that bubble through it, not events that it dispatches directly. It never dispatches an uncaughtErrorEvent in the target phase. It only dispatches the event in the capture and bubbling phases. To detect an uncaught error in the current SWF (the SWF in which the Loader object is defined) use the LoaderInfo.uncaughtErrorEvents property instead.

If the content loaded by the Loader object is an AVM1 (ActionScript 2) SWF file, uncaught errors in the AVM1 SWF file do not result in an uncaughtError event.

The following example demonstrates the use of an uncaught error event handler to detect uncaught errors in a loaded SWF. The example defines an uncaughtError event handler to detect uncaught errors.

In the constructor, the code creates a Loader object and registers a listener for the uncaughtError event dispatched by the Loader object's uncaughtErrorEvents property.

In the uncaughtErrorHandler() method, the code checks the data type of the error property and responds accordingly.

package { import flash.display.Loader; import flash.display.Sprite; import flash.events.ErrorEvent; import flash.events.UncaughtErrorEvent; import flash.net.URLRequest; public class LoaderUncaughtErrorEventExample extends Sprite { private var ldr:Loader; public function LoaderUncaughtErrorEventExample() { ldr = new Loader(); ldr.load(new URLRequest("child.swf")); ldr.uncaughtErrorEvents.addEventListener(UncaughtErrorEvent.UNCAUGHT_ERROR, uncaughtErrorHandler); } private function uncaughtErrorHandler(event:UncaughtErrorEvent):void { if (event.error is Error) { var error:Error = event.error as Error; // do something with the error } else if (event.error is ErrorEvent) { var errorEvent:ErrorEvent = event.error as ErrorEvent; // do something with the error } else { // a non-Error, non-ErrorEvent type was thrown and uncaught } } } }
UncaughtErrorEventLoaderInfo.uncaughtErrorEvents
NativeMenuItem The NativeMenuItem class represents a single item in a menu.flash.events:EventDispatcher The NativeMenuItem class represents a single item in a menu.

A menu item can be a command, a submenu, or a separator line:

  • To create a command item, call the NativeMenuItem constructor, passing in a string for the label and false for the isSeparator parameter.
  • To create a submenu, create a command item for the parent menu and assign the NativeMenu object of the submenu to the item's submenu property. You can also call the addSubmenu() method of the parent NativeMenu object to create the item and set the submenu property at the same time.
  • To create a separator, call the NativeMenuItem constructor, passing in an empty string for the label and true for the isSeparator parameter.

Listen for select events on an item or a parent menu to detect when a menu command is selected. Neither submenus nor separators dispatch select events. Listen for preparing events to determine when a menu item is about to be displayed or activated through a key equivalent.

flash.display.NativeMenuflash.display.NativeMenu.addSubmenu()preparing Dispatched by this NativeMenuItem object when its key equivalent is pressed and immediately before the containing menu is displayed.flash.events.Event.PREPARINGflash.events.Event Dispatched by this NativeMenuItem object when its key equivalent is pressed and immediately before the containing menu is displayed.

Listen to this event to update the item either before the containing menu is displayed, or when its key equivalent is pressed by the user. The preparing event is dispatched before the key equivalent is fully evaluated. You can enable, disable, or remove the item from the menu in the preparing event handler and those changes will be in effect when the key equivalent is processed. For example, if you remove or disable this menu item, then the sequence of events is effectively canceled and no select event is dispatched. A preparing event is also dispatched by the other items in a menu.

The preparing event supersedes the displaying event and provides additional functionality. Listen for the preparing event or the displaying event, but not both.

displaying Dispatched by this NativeMenuItem object immediately before the menu containing the item is displayed.flash.events.Event.DISPLAYINGflash.events.Event Dispatched by this NativeMenuItem object immediately before the menu containing the item is displayed.

The preparing event supersedes the displaying event and provides additional functionality. Listen for the preparing event or the displaying event, but not both.

select Dispatched whenever a menu item is selected by the user.flash.events.Event.SELECTflash.events.Event Dispatched whenever a menu item is selected by the user.

A select event bubbles from this item to its containing menu and on up through the parent menu chain to the root menu object. The target property of the event object references this NativeMenuItem object; the currentTarget property references the dispatching object (either this NativeMenuItem or an ancestral NativeMenu object).

Note: If the window containing the menu is in fullscreen mode (stage.displayState == StageDisplayState.FULL_SCREEN), the NativeMenuItem object does not dispatch a select event when the user enters a keyboard equivalent for a menu item.

NativeMenuItem Creates a new NativeMenuItem object.labelStringThe display label for the item, or an empty string for separators. isSeparatorBooleanfalseSet to true to create a separator; set to false otherwise. Creates a new NativeMenuItem object.

To create a menu command, set the label parameter to a string containing the display label and set isSeparator to false.

To create a submenu command, create a command item and then assign the NativeMenu object for the submenu to the item's submenu property. Add the item to the parent menu.

To create a separator, set the label parameter to an empty string and set isSeparator to true.

Add and remove items from a menu using the NativeMenu addItem() and removeItem() methods.

flash.display.NativeMenu.addSubmenu()
clone Creates a copy of the NativeMenuItem object.flash.display:NativeMenuItem Creates a copy of the NativeMenuItem object. toString Returns a string containing all the properties of the NativeMenuItem object.A string containing all the properties of the Event object. String Returns a string containing all the properties of the NativeMenuItem object. checked Controls whether this menu item displays a checkmark.Boolean Controls whether this menu item displays a checkmark. data An arbitrary data object associated with this menu item.Object An arbitrary data object associated with this menu item.

You can assign any object to this property. The assigned object is not used by the menu system, but is available to event handling code (through the target property of the event object). By default, the value of this property is null.

enabled Controls whether this menu item is enabled.Boolean Controls whether this menu item is enabled. isSeparator Reports whether this item is a menu separator line.Boolean Reports whether this item is a menu separator line.

Create a separator line by setting the isSeparator parameter in the NativeMenuItem constructor to true.

keyEquivalentModifiers The array of key codes for the key equivalent modifiers.Array The array of key codes for the key equivalent modifiers.

Use the constants defined in the Keyboard class to specify the modifier key codes. Valid modifier keys include:

  • Keyboard.ALTERNATE
  • Keyboard.COMMAND
  • Keyboard.CONTROL

If you do not assign any modifiers, then by default the Keyboard.CONTROL key is assigned on Windows or Linux and the Keyboard.COMMAND key is assigned on Mac OS X. If you do not want the key equivalent to include these modifiers, set this property to an empty array.

If you assign an uppercase letter to the keyEquivalent property, the Shift key is used as a modifier automatically. Setting keyEquivalentModifier to an empty array does not remove the Shift key as a modifier.

flash.ui.Keyboard
keyEquivalent The key equivalent for this menu item.String The key equivalent for this menu item.

Set the keyEquivalent with a lowercase letter to assign a shortcut without a Shift-key modifier. Set with an uppercase letter to assign a shortcut with the Shift-key modifier.

By default, a key equivalent modifier (Ctrl on Windows or Linux and Command on Mac OS X) is included as part of the key equivalent. If you want the key equivalent to be a key with no modifier, set the keyEquivalentModifiers property to an empty array.

label The display string of this menu item.String The display string of this menu item. menu The menu that contains this item.flash.display:NativeMenu The menu that contains this item. mnemonicIndex The position of the mnemonic character in the menu item label.int The position of the mnemonic character in the menu item label.

The character at the specified position is the mnemonic character for the menu item. The index is zero-based, so the first character has an index of 0.

This property is ignored on operating systems that do not use menu mnemonics.

name The name of this menu item.String The name of this menu item.

The name value is not displayed and can be used as a locale-independent identifier. A name is not assigned automatically.

submenu The submenu associated with this menu item.flash.display:NativeMenu The submenu associated with this menu item.

Assigning a NativeMenu object to this property changes the appearance and behavior of the menu item. A submenu item displays the submenu icon and no longer dispatches select events.

Note: Adding a menu as a submenu of itself (in a circular reference) can cause an application to hang.

flash.display.NativeMenu.addSubmenu()
NativeMenu The NativeMenu class contains methods and properties for defining native menus.flash.events:EventDispatcher The NativeMenu class contains methods and properties for defining native menus.

AIR profile support: This feature is supported on all desktop operating systems, but is not supported on mobile devices or AIR for TV devices. You can test for support at run time using the NativeMenu.isSupported property. See AIR Profile Support for more information regarding API support across multiple profiles.

A native menu is a menu that is controlled and drawn by the operating system rather than by your application. AIR supports the following types of native menus:

  • Application menus are supported on OS X. Use the NativeApplication.supportsMenu property to test whether application menus are supported on the host operating system. An application menu is displayed on the Menu bar at the top of the Mac desktop. OS X provides a default menu for every application, but many of the menu commands are not functional. You can add event listeners to the default items, replace individual menus and items, or even replace the default menu entirely. Access the application menu object using the NativeApplication menu property.
  • Window menus are supported on Windows and Linux. Use the NativeWindow.supportsMenu property to test whether window menus are supported on the host operating system. A window menu is displayed below the window title bar. The area occupied by the menu is not part of the window stage. Applications cannot draw into this area. Assign a menu to a window using the NativeWindow menu property.
  • Dock icon menus are supported on OS X. Use the NativeApplication.supportsDockIcon property to test whether dock icons are supported on the host operating system. Items in a dock icon menu are displayed above the default items provided by the operating system. The default items cannot be accessed by application code. Assign a menu to the menu property of the application's DockIcon object.
  • System tray icon menus are supported on Windows and most Linux operating systems. Use the NativeApplication.supportsSystemTrayIcon property to test whether system tray icons are supported on the host operating system. A system tray icon menu is displayed in response to a right-click on the icon, in much the same fashion as a context menu. Assign a menu to the menu property of the application's SystemTrayIcon object.
  • Context menus are supported on all operating systems. Context menus are displayed in response to a user interface event, such as a right-click or a command-click on an InteractiveObject displayed in the application. The UI mechanism for showing the menu varies by host operating system and hardware. Assign a menu to the contextMenu property of an InteractiveObject. In AIR, a context menu can be created with either the NativeMenu class or the ContextMenu class. In Flash Player, only the ContextMenu class can be used. ContextMenus in AIR do not have built-in items; a default context menu is not displayed.
  • Pop-up menus are supported on all operating systems. Pop-up menus are functionally the same as context menus, but are displayed using the menu display() method rather than as a response to a user interface event. A pop-up menu is not attached to any other object. Simply create the native menu and call the display() method.

A menu object contains menu items. A menu item can represent a command, a submenu, or a separator line. Add menu items to a menu using the addItem() or addItemAt() method. The display order of the menu items matches the order of the items in the menu's items array.

To create a submenu, add a menu item to the parent menu object. Assign the menu object representing the submenu to the submenu property of the matching menu item in the parent menu.

Note: The root menu of window and application menus must contain only submenu items; items that do not represent submenus may not be displayed and are contrary to user expectation for these types of menus.

Menus dispatch select events when a command item in the menu or one of its submenus is selected. (Submenu and separator items are not selectable.) The target property of the event object references the selected item.

Menus dispatch preparing events just before the menu is displayed and when a key equivalent attached to one of the items in the menu is pressed. You can use this event to update the contents of the menu based on the current state of the application.

Note: If you are using the Flex Framework, consider using the FlexNativeMenu class. It is typically easier to define menus declaratively in MXML than it is to write ActionScript code to create the menu structure item-by-item.

flash.display.InteractiveObject.contextMenuflash.display.NativeMenuItemflash.display.NativeWindow.menuflash.desktop.DockIconflash.desktop.SystemTrayIconflash.desktop.NativeApplication.menuflash.desktop.NativeApplication.iconmx.controls.FlexNativeMenupreparing Dispatched by the NativeMenu object when a key equivalent is pressed and immediately before the menu is displayed.flash.events.Event.PREPARINGflash.events.Event Dispatched by the NativeMenu object when a key equivalent is pressed and immediately before the menu is displayed.

Listen to this event to update the menu either before it is displayed, or when a key equivalent is pressed by the user. The preparing event is dispatched before the key equivalent is fully evaluated. You can enable, disable, add, or remove items from the menu in the preparing event handler and those changes will be in effect when the key equivalent is processed. For example, if you remove or disable the menu item assigned to the triggering key equivalent, then the sequence of events is effectively canceled and no select event is dispatched. A preparing event is also dispatched by the items in a menu.

The preparing event supersedes the displaying event and provides additional functionality. Listen for the preparing event or the displaying event, but not both.

displaying Dispatched by this NativeMenu object immediately before the menu is displayed.flash.events.Event.DISPLAYINGflash.events.Event Dispatched by this NativeMenu object immediately before the menu is displayed.

Listen to this event to update the menu before it is displayed. A displaying event is also dispatched by the items in a menu.

The preparing event supersedes the displaying event and provides additional functionality. Listen for the preparing event or the displaying event, but not both.

Note: On Mac OS X, prior to AIR 2.6, menus and menu items dispatched a displaying event when the user pressed a key equivalent. (This event was not dispatched for key equivalent interaction on other operating systems.) As of AIR 2.6, displaying events are no longer dispatched when the user presses a key equivalent. Use the preparing event instead.

select Dispatched by this NativeMenu object when one of its menu items or an item in one of its descendant submenus is selected.flash.events.Event.SELECTflash.events.Event Dispatched by this NativeMenu object when one of its menu items or an item in one of its descendant submenus is selected.

A select event bubbles from a menu item to its containing menu and on up through the parent menu chain to the root menu object. The target property of the event object references the selected NativeMenuItem object; the currentTarget property references this NativeMenu object.

NativeMenu Creates a new NativeMenu object. Creates a new NativeMenu object. addItemAt Inserts a menu item at the specified position.If item is null. ArgumentErrorArgumentErrorIf item is a member of another menu. ArgumentErrorArgumentErrorIf the index is outside the bounds of the menu's items array. RangeErrorRangeErrorflash.display:NativeMenuItemitemflash.display:NativeMenuItemThe NativeMenuItem object to insert. indexintThe (zero-based) position in menu at which to insert the menu item.

Note: Adding an item to a menu can cause an application to hang if the item's submenu is set to the menu itself (causing a circular reference).

Inserts a menu item at the specified position. The position is indexed from the top. Set the index parameter to zero to insert the item at the top of the menu. All types of menus: window, application, system tray icon, dock icon, context, and pop-up, index the menu position from the top.
addItem Adds a menu item at the bottom of the menu.If item is null. ArgumentErrorArgumentErrorIf item is a member of another menu. ArgumentErrorArgumentErrorflash.display:NativeMenuItemitemflash.display:NativeMenuItemThe NativeMenuItem object to add at the bottom of the menu. Adds a menu item at the bottom of the menu.

When creating a context menu, you can add either NativeMenuItem or ContextMenuItem objects. However, it is advisable to use only one type of object in a context menu so that all items in the menu have the same properties.

Note: Adding an item to a menu can cause an application to hang if the item's submenu is set to the menu itself (causing a circular reference).

addSubmenuAt Adds a submenu to the menu by inserting a new menu item at the specified position.The NativeMenuItem object created for the submenu. flash.display:NativeMenuItemsubmenuflash.display:NativeMenuThe NativeMenu object that defines the submenu to be added. indexintThe position in the items array of this menu at which to insert the menu item to be added. labelStringThe display label for the menu item to be added. Adds a submenu to the menu by inserting a new menu item at the specified position.

Calling the addSubMenuAt() method is equivalent to creating a new menu item, inserting it at the desired position in the menu, and assigning a NativeMenu object to the item's submenu property.

Note: Adding a menu as a submenu of itself (in a circular reference) can cause an application to hang.

addSubmenu Adds a submenu to the menu by inserting a new menu item.The NativeMenuItem object created for the submenu. flash.display:NativeMenuItemsubmenuflash.display:NativeMenuThe NativeMenu object that defines the submenu to be added. labelStringThe display label for the menu item to be added. Adds a submenu to the menu by inserting a new menu item.

Calling the addSubMenu() method is equivalent to creating a new menu item, adding it to the menu, and assigning a NativeMenu object to the item's submenu property.

Note: Adding a menu as a submenu of itself (in a circular reference) can cause an application to hang.

clone Creates a copy of the menu and all items.flash.display:NativeMenu Creates a copy of the menu and all items. containsItem Reports whether this menu contains the specified menu item.true if item is in this menu. Booleanitemflash.display:NativeMenuItemThe NativeMenuItem object to look up. Reports whether this menu contains the specified menu item. display Pops up this menu at the specified location.stageflash.display:StageThe Stage object on which to display this menu. stageXNumberThe number of horizontal pixels, relative to the origin of stage, at which to display this menu. stageYNumberThe number of vertical pixels, relative to the origin of stage, at which to display this menu. Pops up this menu at the specified location. getItemAt Gets the menu item at the specified index.If index is outside the bounds of the menu's items array. RangeErrorRangeErrorThe NativeMenuItem object at the specified position in the menu. flash.display:NativeMenuItemindexintThe (zero-based) position of the item to return. Gets the menu item at the specified index. getItemByName Gets the menu item with the specified name.The NativeMenuItem object with the specified name or null, if no such item exists in the menu. flash.display:NativeMenuItemnameStringThe string to look up. Gets the menu item with the specified name.

Note: The name property of menu items is not assigned by default.

getItemIndex Gets the position of the specified item.The (zero-based) position of the specified item in this menu or -1, if the item is not in this menu. intitemflash.display:NativeMenuItemThe NativeMenuItem object to look up. Gets the position of the specified item. removeAllItems Removes all items from the menu. Removes all items from the menu. removeItemAt Removes and returns the menu item at the specified index.If index is outside the bounds of this menu's items array. RangeErrorRangeErrorThe NativeMenuItem object removed. flash.display:NativeMenuItemindexintThe (zero-based) position of the item to remove. Removes and returns the menu item at the specified index. removeItem Removes the specified menu item.If the item is not in this menu RangeErrorRangeErrorflash.display:NativeMenuItemitemflash.display:NativeMenuItemThe NativeMenuItem object to remove from this menu. Removes the specified menu item. setItemIndex Moves a menu item to the specified position.If index is outside the bounds of the menu's items array. RangeErrorRangeErroritemflash.display:NativeMenuItemThe NativeMenuItem object to move. indexintThe (zero-based) position in the menu to which to move the item. Moves a menu item to the specified position. If the item is not already in the menu, calling this method adds the item to the menu. isSupported Indicates whether any form of native menu is supported on the client system.Boolean Indicates whether any form of native menu is supported on the client system. flash.display.NativeWindow.supportsMenuflash.desktop.NativeApplicationitems The array of NativeMenuItem objects in this menu.Array The array of NativeMenuItem objects in this menu.

The array is sorted in display order.

Note: This property is read-only in AIR 1.0. It became read/write in AIR 1.1.

numItems The number of NativeMenuItem objects in this menu.int The number of NativeMenuItem objects in this menu. parent The parent menu.flash.display:NativeMenu The parent menu.

The parent of the root (top-level) menu object is null.

StageOrientation The StageOrientation class defines constants enumerating the possible orientations of the stage and the device.The StageOrientation class provides values for the orientation property of the Stage class and for other properties and methods where Stage orientation is referenced. Object The StageOrientation class defines constants enumerating the possible orientations of the stage and the device. flash.display.Stage.orientationflash.display.Stage.setOrientation()flash.display.Stage.deviceOrientationflash.events.StageOrientationEvent.afterOrientationflash.events.StageOrientationEvent.beforeOrientationDEFAULT Specifies that the stage is currently in the default orientation of the device (right-side up).defaultString Specifies that the stage is currently in the default orientation of the device (right-side up). ROTATED_LEFT Specifies that the stage is currently rotated left relative to the default orientation.rotatedLeftString Specifies that the stage is currently rotated left relative to the default orientation.

Note: When the orientation of the device is rotated left, the orientation of the stage must be rotated right in order to remain upright.

ROTATED_RIGHT Specifies that the stage is currently rotated right relative to the default orientation.rotatedRightString Specifies that the stage is currently rotated right relative to the default orientation.

Note: When the orientation of the device is rotated right, the orientation of the stage must be rotated left in order to remain upright.

UNKNOWN Specifies that the device has not determined an orientation.unknownString Specifies that the device has not determined an orientation. This state can occur when the device is lying flat on a table and also while the application is initializing. UPSIDE_DOWN Specifies that the stage is currently upside down relative to the default orientation.upsideDownString Specifies that the stage is currently upside down relative to the default orientation.
DisplayObjectContainer The DisplayObjectContainer class is the base class for all objects that can serve as display object containers on the display list.The abstract base class for all display objects that can contain child objects. flash.display:InteractiveObject The DisplayObjectContainer class is the base class for all objects that can serve as display object containers on the display list. The display list manages all objects displayed in the Flash runtimes. Use the DisplayObjectContainer class to arrange the display objects in the display list. Each DisplayObjectContainer object has its own child list for organizing the z-order of the objects. The z-order is the front-to-back order that determines which object is drawn in front, which is behind, and so on.

DisplayObject is an abstract base class; therefore, you cannot call DisplayObject directly. Invoking new DisplayObject() throws an ArgumentError exception.

The DisplayObjectContainer class is an abstract base class for all objects that can contain child objects. It cannot be instantiated directly; calling the new DisplayObjectContainer() constructor throws an ArgumentError exception.

For more information, see the "Display Programming" chapter of the ActionScript 3.0 Developer's Guide.

The following example uses the class DisplayObjectContainerExample to create five orange squares in succession. This task is accomplished by performing the following steps:
  1. The constructor calls the configureAssets() method.
  2. The configureAssets() method creates child and lastChild Sprite objects.
  3. A for loop creates the five orange squares and positions them one after another.
  4. Each time a CustomSprite object is created, its constructor calls the draw() method of the CustomSprite object, which creates a 50-by-50-pixel square by calling the beginFill(), drawRect(), and endFill() methods of the Graphics class. The addChild() method adds each square to the display list.
package { import flash.display.DisplayObject; import flash.display.Sprite; public class DisplayObjectContainerExample extends Sprite { private var gutter:uint = 5; private var childCount:uint = 5; public function DisplayObjectContainerExample() { configureAssets(); } private function configureAssets():void { var child:Sprite = new CustomSprite(); var lastChild:Sprite = child; for (var i:uint = 1; i <= childCount; i++) { child = new CustomSprite(); child.x = lastChild.x + lastChild.width + gutter; addChild(child); lastChild = child; } } } } import flash.display.Sprite; class CustomSprite extends Sprite { private var size:uint = 50; private var bgColor:uint = 0xFFCC00; public function CustomSprite() { draw(size, size); } private function draw(w:uint, h:uint):void { graphics.beginFill(bgColor); graphics.drawRect(0, 0, w, h); graphics.endFill(); } }
flash.display.DisplayObjectDisplayObjectContainer Calling the new DisplayObjectContainer() constructor throws an ArgumentError exception. Calling the new DisplayObjectContainer() constructor throws an ArgumentError exception. You can, however, call constructors for the following subclasses of DisplayObjectContainer:
  • new Loader()
  • new Sprite()
  • new MovieClip()
addChildAt Adds a child DisplayObject instance to this DisplayObjectContainer instance.Throws if the index position does not exist in the child list. RangeErrorRangeErrorThrows if the child is the same as the parent. Also throws if the caller is a child (or grandchild etc.) of the child being added. ArgumentErrorArgumentErrorThe DisplayObject instance that you pass in the child parameter. flash.display:DisplayObjectchildflash.display:DisplayObjectThe DisplayObject instance to add as a child of this DisplayObjectContainer instance. indexintThe index position to which the child is added. If you specify a currently occupied index position, the child object that exists at that position and all higher positions are moved up one position in the child list. Adds a child object to this DisplayObjectContainer instance. Adds a child DisplayObject instance to this DisplayObjectContainer instance. The child is added at the index position specified. An index of 0 represents the back (bottom) of the display list for this DisplayObjectContainer object.

For example, the following example shows three display objects, labeled a, b, and c, at index positions 0, 2, and 1, respectively:

If you add a child object that already has a different display object container as a parent, the object is removed from the child list of the other display object container.

The following example creates a container display object container and adds a display objects circle1 to its display list. Then, by calling container.addChildAt(circle2, 0), it adds the circle2 object to index position zero (the back), and moves the circle1 object to index position 1: import flash.display.Sprite; var container:Sprite = new Sprite(); var circle1:Sprite = new Sprite(); var circle2:Sprite = new Sprite(); container.addChild(circle1); container.addChildAt(circle2, 0); trace(container.getChildAt(0) == circle2); // true trace(container.getChildAt(1) == circle1); // true
addChild()addedflash.events:EventDispatched when a display object is added to the display list. Dispatched when a display object is added to the display list.
addChild Adds a child DisplayObject instance to this DisplayObjectContainer instance.Throws if the child is the same as the parent. Also throws if the caller is a child (or grandchild etc.) of the child being added. ArgumentErrorArgumentErrorThe DisplayObject instance that you pass in the child parameter. flash.display:DisplayObjectchildflash.display:DisplayObjectThe DisplayObject instance to add as a child of this DisplayObjectContainer instance. Adds a child object to this DisplayObjectContainer instance. Adds a child DisplayObject instance to this DisplayObjectContainer instance. The child is added to the front (top) of all other children in this DisplayObjectContainer instance. (To add a child to a specific index position, use the addChildAt() method.)

If you add a child object that already has a different display object container as a parent, the object is removed from the child list of the other display object container.

Note: The command stage.addChild() can cause problems with a published SWF file, including security problems and conflicts with other loaded SWF files. There is only one Stage within a Flash runtime instance, no matter how many SWF files you load into the runtime. So, generally, objects should not be added to the Stage, directly, at all. The only object the Stage should contain is the root object. Create a DisplayObjectContainer to contain all of the items on the display list. Then, if necessary, add that DisplayObjectContainer instance to the Stage.

The following example sets up two Sprite objects named container1 and container2. A Sprite is a type of display object container. The example calls the addChild() method to set up the display hierarchy: container1 is a child of container2, and two other display objects, circle1 and circle2, are children of container1. The calls to the trace() method show the number of children of each object. Note that grandchildren are not included in the numChildren count: import flash.display.Sprite; var container1:Sprite = new Sprite(); var container2:Sprite = new Sprite(); var circle1:Sprite = new Sprite(); circle1.graphics.beginFill(0xFFCC00); circle1.graphics.drawCircle(40, 40, 40); var circle2:Sprite = new Sprite(); circle2.graphics.beginFill(0x00CCFF); circle2.graphics.drawCircle(80, 40, 40); container2.addChild(container1); container1.addChild(circle1); container1.addChild(circle2); trace(container1.numChildren); // 2 trace(container2.numChildren); // 1 trace(circle1.numChildren); // 0 trace(circle2.numChildren); // 0
addChildAt()addedflash.events:EventDispatched when a display object is added to the display list. Dispatched when a display object is added to the display list.
areInaccessibleObjectsUnderPoint Indicates whether the security restrictions would cause any display objects to be omitted from the list returned by calling the DisplayObjectContainer.getObjectsUnderPoint() method with the specified point point.true if the point contains child display objects with security restrictions. Booleanpointflash.geom:PointThe point under which to look. Indicates whether the security restrictions would cause any display objects to be omitted from the list returned by calling the DisplayObjectContainer.getObjectsUnderPoint() method with the specified point point. By default, content from one domain cannot access objects from another domain unless they are permitted to do so with a call to the Security.allowDomain() method. For more information, related to security, see the Flash Player Developer Center Topic: Security.

The point parameter is in the coordinate space of the Stage, which may differ from the coordinate space of the display object container (unless the display object container is the Stage). You can use the globalToLocal() and the localToGlobal() methods to convert points between these coordinate spaces.

The following code creates a display object container named container. The next block of code uses a Loader object to load a JPEG file named "test.jpg" from a remote file server. Note that the checkPolicyFile property of the LoaderContext object used as a parameter in the load() method is set to false. Once the file is loaded, the code calls the loaded() method, which in turn calls container.areInaccessibleObjectsUnderPoint(), which returns a value of true because the loaded content is assumed to be from an inaccessible domain: import flash.display.Sprite; import flash.display.Loader; import flash.system.LoaderContext; import flash.net.URLRequest; import flash.events.Event; import flash.geom.Point; var container:Sprite = new Sprite(); var urlReq:URLRequest = new URLRequest("http://localhost/RemoteFile.swf"); var ldr:Loader = new Loader(); var context:LoaderContext = new LoaderContext(); context.checkPolicyFile = false; ldr.load(urlReq, context); ldr.contentLoaderInfo.addEventListener(Event.COMPLETE, loaded); ldr.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, urlNotFound); function loaded(event:Event):void { var pt:Point = new Point(1, 1); trace(container.areInaccessibleObjectsUnderPoint(pt)); // true } function urlNotFound(event:Event):void { trace("The URL was not found."); } This example assumes that the SWF file produced by this code is loaded from a different domain than that of the JPEG file, and that the loaded JPEG file occupies the point (1, 1).
flash.system.Security.allowDomain()getObjectsUnderPoint()DisplayObject.globalToLocal()DisplayObject.localToGlobal()
contains Determines whether the specified display object is a child of the DisplayObjectContainer instance or the instance itself.true if the child object is a child of the DisplayObjectContainer or the container itself; otherwise false. Booleanchildflash.display:DisplayObjectThe child object to test. Determines whether the specified display object is a child of the DisplayObjectContainer instance or the instance itself. The search includes the entire display list including this DisplayObjectContainer instance. Grandchildren, great-grandchildren, and so on each return true. The following example sets up a number of Sprite objects and adds some to the child list of others. (A Sprite object is a type of display object container.) The relationship between various objects is shown by calling the contains() method: import flash.display.Sprite; var sprite1:Sprite = new Sprite(); var sprite2:Sprite = new Sprite(); var sprite3:Sprite = new Sprite(); var sprite4:Sprite = new Sprite(); sprite1.addChild(sprite2); sprite2.addChild(sprite3); trace(sprite1.contains(sprite1)); // true trace(sprite1.contains(sprite2)); // true trace(sprite1.contains(sprite3)); // true trace(sprite1.contains(sprite4)); // false getChildAt Returns the child display object instance that exists at the specified index.Throws if the index does not exist in the child list. RangeErrorRangeErrorThis child display object belongs to a sandbox to which you do not have access. You can avoid this situation by having the child movie call Security.allowDomain(). SecurityErrorSecurityErrorThe child display object at the specified index position. flash.display:DisplayObjectindexintThe index position of the child object. Returns the child display object instance that exists at the specified index. The following example creates a display object container named container and then adds a three display objects to the child list of the container object. The calls to the getChildAt() method then reveal the positions of the child objects: import flash.display.Sprite; var container:Sprite = new Sprite(); var sprite1:Sprite = new Sprite(); var sprite2:Sprite = new Sprite(); var sprite3:Sprite = new Sprite(); container.addChild(sprite1); container.addChild(sprite2); container.addChildAt(sprite3, 0); trace(container.getChildAt(0) == sprite3); // true trace(container.getChildAt(1) == sprite1); // true trace(container.getChildAt(2) == sprite2); // true getChildByName()getChildByName Returns the child display object that exists with the specified name.This child display object belongs to a sandbox to which you do not have access. You can avoid this situation by having the child movie call the Security.allowDomain() method. SecurityErrorSecurityErrorThe child display object with the specified name. flash.display:DisplayObjectnameStringThe name of the child to return. Returns the child display object that exists with the specified name. If more that one child display object has the specified name, the method returns the first object in the child list.

The getChildAt() method is faster than the getChildByName() method. The getChildAt() method accesses a child from a cached array, whereas the getChildByName() method has to traverse a linked list to access a child.

The following example creates a display object container named container and then adds two child display objects to the container. Then, the code calls the getChildByName() and getChildIndex() methods to return the index position of the child of the container object that has the name "sprite1". import flash.display.Sprite; import flash.display.DisplayObject; var container:Sprite = new Sprite(); var sprite1:Sprite = new Sprite(); sprite1.name = "sprite1"; var sprite2:Sprite = new Sprite(); sprite2.name = "sprite2"; container.addChild(sprite1); container.addChild(sprite2); var target:DisplayObject = container.getChildByName("sprite1"); trace(container.getChildIndex(target)); // 0
getChildAt()flash.display.DisplayObject.name
getChildIndex Returns the index position of a child DisplayObject instance.Throws if the child parameter is not a child of this object. ArgumentErrorArgumentErrorThe index position of the child display object to identify. intchildflash.display:DisplayObjectThe DisplayObject instance to identify. Returns the index number of a child DisplayObject instance. Returns the index position of a child DisplayObject instance. The following example creates a display object container named container and then adds two child display objects to the container. Then, the code calls the getChildByName() and getChildIndex() methods to return the index position of the child of the container object that has the name "sprite1". import flash.display.Sprite; import flash.display.DisplayObject; var container:Sprite = new Sprite(); var sprite1:Sprite = new Sprite(); sprite1.name = "sprite1"; var sprite2:Sprite = new Sprite(); sprite2.name = "sprite2"; container.addChild(sprite1); container.addChild(sprite2); var target:DisplayObject = container.getChildByName("sprite1"); trace(container.getChildIndex(target)); // 0 getObjectsUnderPoint Returns an array of objects that lie under the specified point and are children (or grandchildren, and so on) of this DisplayObjectContainer instance.An array of objects that lie under the specified point and are children (or grandchildren, and so on) of this DisplayObjectContainer instance. Arraypointflash.geom:PointThe point under which to look. Returns an array of objects that lie under the specified point and are children (or grandchildren, and so on) of this DisplayObjectContainer instance. Any child objects that are inaccessible for security reasons are omitted from the returned array. To determine whether this security restriction affects the returned array, call the areInaccessibleObjectsUnderPoint() method.

The point parameter is in the coordinate space of the Stage, which may differ from the coordinate space of the display object container (unless the display object container is the Stage). You can use the globalToLocal() and the localToGlobal() methods to convert points between these coordinate spaces.

The following example creates a display object container named container and then adds two overlapping child display objects to the container. Then the code calls the getObjectsUnderPoint() twice — first using a point that touches only one object, then using a point where the objects overlap — and the length of the return Array shows the number of objects at each point in the container: import flash.display.Sprite; import flash.geom.Point; var container:Sprite = new Sprite(); var square1:Sprite = new Sprite(); square1.graphics.beginFill(0xFFCC00); square1.graphics.drawRect(0, 0, 40, 40); var square2:Sprite = new Sprite(); square2.graphics.beginFill(0x00CCFF); square2.graphics.drawRect(20, 0, 30, 40); container.addChild(square1); container.addChild(square2); var pt:Point = new Point(10, 20); var objects:Array = container.getObjectsUnderPoint(pt); trace(objects.length); // 1 pt = new Point(35, 20); objects = container.getObjectsUnderPoint(pt); trace(objects.length); // 2
areInaccessibleObjectsUnderPoint()DisplayObject.globalToLocal()DisplayObject.localToGlobal()
removeChildAt Removes a child DisplayObject from the specified index position in the child list of the DisplayObjectContainer.This child display object belongs to a sandbox to which the calling object does not have access. You can avoid this situation by having the child movie call the Security.allowDomain() method. SecurityErrorSecurityErrorThrows if the index does not exist in the child list. RangeErrorRangeErrorThe DisplayObject instance that was removed. flash.display:DisplayObjectindexintThe child index of the DisplayObject to remove. Removes a child display object, at the specified index position, from the DisplayObjectContainer instance. Removes a child DisplayObject from the specified index position in the child list of the DisplayObjectContainer. The parent property of the removed child is set to null, and the object is garbage collected if no other references to the child exist. The index positions of any display objects above the child in the DisplayObjectContainer are decreased by 1.

The garbage collector reallocates unused memory space. When a variable or object is no longer actively referenced or stored somewhere, the garbage collector sweeps through and wipes out the memory space it used to occupy if no other references to it exist.

The following example creates a display object container named container and then adds two child display objects to the container. The code then shows that when you call the removeChildAt() method to remove the child at the lowest index position (0), any other child object in the list moves down one position: import flash.display.Sprite; var container:Sprite = new Sprite(); var sprite1:Sprite = new Sprite(); sprite1.name = "sprite1"; var sprite2:Sprite = new Sprite(); sprite2.name = "sprite2"; container.addChild(sprite1); container.addChild(sprite2); trace(container.numChildren) // 2 container.removeChildAt(0); trace(container.numChildren) // 1 trace(container.getChildAt(0).name); // sprite2
removeChild Removes the specified child DisplayObject instance from the child list of the DisplayObjectContainer instance.Throws if the child parameter is not a child of this object. ArgumentErrorArgumentErrorThe DisplayObject instance that you pass in the child parameter. flash.display:DisplayObjectchildflash.display:DisplayObjectThe DisplayObject instance to remove. Removes a child display object from the DisplayObjectContainer instance. Removes the specified child DisplayObject instance from the child list of the DisplayObjectContainer instance. The parent property of the removed child is set to null , and the object is garbage collected if no other references to the child exist. The index positions of any display objects above the child in the DisplayObjectContainer are decreased by 1.

The garbage collector reallocates unused memory space. When a variable or object is no longer actively referenced or stored somewhere, the garbage collector sweeps through and wipes out the memory space it used to occupy if no other references to it exist.

The following example creates a display object container named container and then adds two child display objects to the container. An event listener is added to the container object, so that when the user clicks a child object of the container, the removeChild() method removes the child clicked from the child list of the container: import flash.display.DisplayObject; import flash.display.Sprite; import flash.events.MouseEvent; var container:Sprite = new Sprite(); addChild(container); var circle1:Sprite = new Sprite(); circle1.graphics.beginFill(0xFFCC00); circle1.graphics.drawCircle(40, 40, 40); var circle2:Sprite = new Sprite(); circle2.graphics.beginFill(0x00CCFF); circle2.graphics.drawCircle(120, 40, 40); container.addChild(circle1); container.addChild(circle2); container.addEventListener(MouseEvent.CLICK, clicked); function clicked(event:MouseEvent):void { container.removeChild(DisplayObject(event.target)); }
setChildIndex Changes the position of an existing child in the display object container.Throws if the index does not exist in the child list. RangeErrorRangeErrorThrows if the child parameter is not a child of this object. ArgumentErrorArgumentErrorchildflash.display:DisplayObjectThe child DisplayObject instance for which you want to change the index number. indexintThe resulting index number for the child display object. Changes the index number of an existing child. Changes the position of an existing child in the display object container. This affects the layering of child objects. For example, the following example shows three display objects, labeled a, b, and c, at index positions 0, 1, and 2, respectively:

When you use the setChildIndex() method and specify an index position that is already occupied, the only positions that change are those in between the display object's former and new position. All others will stay the same. If a child is moved to an index LOWER than its current index, all children in between will INCREASE by 1 for their index reference. If a child is moved to an index HIGHER than its current index, all children in between will DECREASE by 1 for their index reference. For example, if the display object container in the previous example is named container, you can swap the position of the display objects labeled a and b by calling the following code:

container.setChildIndex(container.getChildAt(1), 0);

This code results in the following arrangement of objects:

The following example creates a display object container named container and then adds three slightly overlapping child display objects to the container. When the user clicks any of these objects, the clicked() method calls the setChildIndex() method to move the clicked object to the top-most position in the child list of the container object: import flash.display.Sprite; import flash.events.MouseEvent; var container:Sprite = new Sprite(); addChild(container); var circle1:Sprite = new Sprite(); circle1.graphics.beginFill(0xFF0000); circle1.graphics.drawCircle(40, 40, 40); circle1.addEventListener(MouseEvent.CLICK, clicked); var circle2:Sprite = new Sprite(); circle2.graphics.beginFill(0x00FF00); circle2.graphics.drawCircle(100, 40, 40); circle2.addEventListener(MouseEvent.CLICK, clicked); var circle3:Sprite = new Sprite(); circle3.graphics.beginFill(0x0000FF); circle3.graphics.drawCircle(70, 80, 40); circle3.addEventListener(MouseEvent.CLICK, clicked); container.addChild(circle1); container.addChild(circle2); container.addChild(circle3); addChild(container); function clicked(event:MouseEvent):void { var circle:Sprite = Sprite(event.target); var topPosition:uint = container.numChildren - 1; container.setChildIndex(circle, topPosition); }
addChildAt()getChildIndex()
swapChildrenAt Swaps the z-order (front-to-back order) of the child objects at the two specified index positions in the child list.If either index does not exist in the child list. RangeErrorRangeErrorindex1intThe index position of the first child object. index2intThe index position of the second child object. Swaps the z-order (front-to-back order) of the child objects at the two specified index positions in the child list. All other child objects in the display object container remain in the same index positions. The following example creates a display object container named container, then adds three child display objects to the container, and then shows how a call to the swapChildrenAt() method rearranges the child list of the display object container: import flash.display.Sprite; var container:Sprite = new Sprite(); var sprite1:Sprite = new Sprite(); sprite1.name = "sprite1"; var sprite2:Sprite = new Sprite(); sprite2.name = "sprite2"; var sprite3:Sprite = new Sprite(); sprite3.name = "sprite3"; container.addChild(sprite1); container.addChild(sprite2); container.addChild(sprite3); trace(container.getChildAt(0).name); // sprite1 trace(container.getChildAt(1).name); // sprite2 trace(container.getChildAt(2).name); // sprite3 container.swapChildrenAt(0, 2); trace(container.getChildAt(0).name); // sprite3 trace(container.getChildAt(1).name); // sprite2 trace(container.getChildAt(2).name); // sprite1 swapChildren Swaps the z-order (front-to-back order) of the two specified child objects.Throws if either child parameter is not a child of this object. ArgumentErrorArgumentErrorchild1flash.display:DisplayObjectThe first child object. child2flash.display:DisplayObjectThe second child object. Swaps the z-order (front-to-back order) of the two specified child objects. All other child objects in the display object container remain in the same index positions. The following example creates a display object container named container, then adds two child display objects to the container, and then shows the effect of a call to the swapChildren() method: import flash.display.Sprite; var container:Sprite = new Sprite(); var sprite1:Sprite = new Sprite(); sprite1.name = "sprite1"; var sprite2:Sprite = new Sprite(); sprite2.name = "sprite2"; container.addChild(sprite1); container.addChild(sprite2); trace(container.getChildAt(0).name); // sprite1 trace(container.getChildAt(1).name); // sprite2 container.swapChildren(sprite1, sprite2); trace(container.getChildAt(0).name); // sprite2 trace(container.getChildAt(1).name); // sprite1 mouseChildren Determines whether or not the children of the object are mouse, or user input device, enabled.Boolean Determines whether or not the children of the object are mouse, or user input device, enabled. If an object is enabled, a user can interact with it by using a mouse or user input device. The default is true.

This property is useful when you create a button with an instance of the Sprite class (instead of using the SimpleButton class). When you use a Sprite instance to create a button, you can choose to decorate the button by using the addChild() method to add additional Sprite instances. This process can cause unexpected behavior with mouse events because the Sprite instances you add as children can become the target object of a mouse event when you expect the parent instance to be the target object. To ensure that the parent instance serves as the target objects for mouse events, you can set the mouseChildren property of the parent instance to false.

No event is dispatched by setting this property. You must use the addEventListener() method to create interactive functionality.

The following example sets up a Sprite object (a type of display object container) named container and shows that when you set its mouseChildren property to false, the target of a mouseClick event is the container object, not any one of its child objects: import flash.display.Sprite; import flash.events.MouseEvent; var container:Sprite = new Sprite(); container.name = "container"; addChild(container); var circle:Sprite = new Sprite(); circle.name = "circle"; circle.graphics.beginFill(0xFFCC00); circle.graphics.drawCircle(40, 40, 40); container.addChild(circle); container.mouseChildren = false; container.addEventListener(MouseEvent.CLICK, clicked); function clicked(event:MouseEvent):void { trace(event.target.name); // container }
flash.display.Sprite.buttonModeflash.events.EventDispatcher.addEventListener()
numChildren Returns the number of children of this object.int Returns the number of children of this object. The following example sets up two Sprite objects named container1 and container2. A Sprite is a type of display object container. The example calls the addChild() method to set up the display hierarchy: container1 is a child of container2, and two other display objects, circle1 and circle2, are children of container1. The calls to the trace() method show the number of children of each object. Note that grandchildren are not included in the numChildren count: import flash.display.Sprite; var container1:Sprite = new Sprite(); var container2:Sprite = new Sprite(); var circle1:Sprite = new Sprite(); circle1.graphics.beginFill(0xFFCC00); circle1.graphics.drawCircle(40, 40, 40); var circle2:Sprite = new Sprite(); circle2.graphics.beginFill(0x00CCFF); circle2.graphics.drawCircle(80, 40, 40); container2.addChild(container1); container1.addChild(circle1); container1.addChild(circle2); trace(container1.numChildren); // 2 trace(container2.numChildren); // 1 trace(circle1.numChildren); // 0 trace(circle2.numChildren); // 0 tabChildren Determines whether the children of the object are tab enabled.BooleanCalling this property of the Stage object throws an exception. The Stage object does not implement this property. IllegalOperationErrorflash.errors:IllegalOperationError Determines whether the children of the object are tab enabled. Enables or disables tabbing for the children of the object. The default is true.

Note: Do not use the tabChildren property with Flex. Instead, use the mx.core.UIComponent.hasFocusableChildren property.

The following example creates a container1 display object container and adds two display objects, circle1 and circle2, to its child list. The example sets tabChildren to false for the children so it can manage its own tab order using tabIndex: import flash.display.Sprite; var container:Sprite = new Sprite(); container.tabChildren = false; var circle1:Sprite = new Sprite(); circle1.graphics.beginFill(0xFFCC00); circle1.graphics.drawCircle(40, 40, 40); circle1.tabIndex = 1; var circle2:Sprite = new Sprite(); circle2.graphics.beginFill(0x00CCFF); circle2.graphics.drawCircle(120, 40, 40); circle2.tabIndex = 0; container.addChild(circle1); container.addChild(circle2); To see the results of this example, compile and run the file. When you select one of the circles, you can press the TAB key to switch the display object that has focus (indicated by a yellow highlight rectangle).
textSnapshot Returns a TextSnapshot object for this DisplayObjectContainer instance.flash.text:TextSnapshot Returns a TextSnapshot object for this DisplayObjectContainer instance. The following example works only in the Flash authoring environment. Flex does not include any ways of adding static text to a file. To prepare the Flash file for this example, add one or more static text fields in the first frame of a movie. Then insert the following script into the first frame and run the file. The output will be the static text that you added: trace(this.textSnapshot.getText(0, this.textSnapshot.charCount)); flash.text.TextSnapshot
GraphicsGradientFill Defines a gradient fill.flash.display:IGraphicsFillflash.display:IGraphicsDataObject Defines a gradient fill.

Use a GraphicsGradientFill object with the Graphics.drawGraphicsData() method. Drawing a GraphicsGradientFill object is the equivalent of calling the Graphics.beginGradientFill() method.

flash.display.Graphics.beginGradientFill()flash.display.Graphics.drawGraphicsData()GraphicsGradientFill Creates a new GraphicsGradientFill object.typeStringlinearA value from the GradientType class that specifies which gradient type to use: GradientType.LINEAR or GradientType.RADIAL. colorsArraynullAn array of RGB hexadecimal color values used in the gradient; for example, red is 0xFF0000, blue is 0x0000FF, and so on. You can specify up to 15 colors. For each color, specify a corresponding value in the alphas and ratios parameters. alphasArraynullAn array of alpha values for the corresponding colors in the colors array; valid values are 0 to 1. If the value is less than 0, 0 is used. If the value is greater than 1, 1 is used. ratiosArraynullAn array of color distribution ratios; valid values are 0-255. This value defines the percentage of the width where the color is sampled at 100%. The value 0 represents the left position in the gradient box, and 255 represents the right position in the gradient box. matrixnullA transformation matrix as defined by the flash.geom.Matrix class. The flash.geom.Matrix class includes a createGradientBox() method, which lets you conveniently set up the matrix for use with the beginGradientFill() method. spreadMethodpadA value from the SpreadMethod class that specifies which spread method to use, either: SpreadMethod.PAD, SpreadMethod.REFLECT, or SpreadMethod.REPEAT. interpolationMethodStringrgbA value from the InterpolationMethod class that specifies which value to use: InterpolationMethod.LINEAR_RGB or InterpolationMethod.RGB focalPointRatioNumber0.0A number that controls the location of the focal point of the gradient. A value of 0 sets the focal point in the center. A value of 1 sets the focal point at one border of the gradient circle. A value of -1 sets the focal point at the other border of the gradient circle. A value less than -1 or greater than 1 is rounded to -1 or 1, respectively. Creates a new GraphicsGradientFill object. flash.display.Graphics.beginGradientFill()flash.display.GradientTypeflash.geom.Matrixflash.display.SpreadMethodflash.display.InterpolationMethodalphas An array of alpha values for the corresponding colors in the colors array.Array An array of alpha values for the corresponding colors in the colors array. Valid values are between 0 and 1. If the value is less than 0, 0 is used. If the value is greater than 1, 1 is used. colors An array of RGB hexadecimal color values to use in the gradient.Array An array of RGB hexadecimal color values to use in the gradient. For example, red is 0xFF0000, blue is 0x0000FF, and so on. You can specify up to 15 colors. For each color, specify a corresponding value in the alphas and ratios properties. focalPointRatio A number that controls the location of the focal point of the gradient.Number A number that controls the location of the focal point of the gradient. A value of 0 sets the focal point in the center. A value of 1 means that the focal point is at one border of the gradient circle.A value of -1 sets the focal point at the other border of the gradient circle. A value of less than -1 or greater than 1 is rounded to -1 or 1, respectively. For example, the following shows a focalPointRatio set to 0.75:

matrix A transformation matrix as defined by the Matrix class.flash.geom:Matrix A transformation matrix as defined by the Matrix class. The flash.geom.Matrix class includes a createGradientBox() method to set up the matrix for use with the beginGradientFill() method. flash.geom.Matrix.createGradientBox()ratios An array of color distribution ratios.Array An array of color distribution ratios. Valid values are between 0 and 255. This value defines the percentage of the width where the color is sampled at 100%. The value 0 represents the left position in the gradient box, and the value 255 represents the right position in the gradient box.

Note: This value represents positions in the gradient box, not the coordinate space of the final gradient which can be wider or thinner than the gradient box. Specify a value for corresponding to each value in the colors property.

For example, for a linear gradient that includes two colors (blue and green) the following example illustrates the placement of the colors in the gradient based on different values in the ratios array:

ratiosGradient[0, 127][0, 255][127, 255]

The values in the array must increase sequentially; for example, [0, 63, 127, 190, 255].

interpolationMethod A value from the InterpolationMethod class that specifies which value to use.String A value from the InterpolationMethod class that specifies which value to use. Valid values are: InterpolationMethod.LINEAR_RGB or InterpolationMethod.RGB

For example, the following shows a simple linear gradient between two colors (with the spreadMethod parameter set to SpreadMethod.REFLECT). The different interpolation methods change the appearance as follows:

InterpolationMethod.LINEAR_RGBInterpolationMethod.RGB
flash.display.InterpolationMethod
spreadMethod A value from the SpreadMethod class that specifies which spread method to use.String A value from the SpreadMethod class that specifies which spread method to use. Valid values are: SpreadMethod.PAD, SpreadMethod.REFLECT, or SpreadMethod.REPEAT.

For example, the following shows a simple linear gradient between two colors:

import flash.geom.* import flash.display.* var fillType:String = GradientType.LINEAR; var colors:Array = [0xFF0000, 0x0000FF]; var alphas:Array = [1, 1]; var ratios:Array = [0x00, 0xFF]; var matr:Matrix = new Matrix(); matr.createGradientBox(20, 20, 0, 0, 0); var spreadMethod:String = SpreadMethod.PAD; this.graphics.beginGradientFill(fillType, colors, alphas, ratios, matr, spreadMethod); this.graphics.drawRect(0,0,100,100);

This example uses SpreadMethod.PAD for the spread method, and the gradient fill looks like the following:

If you use SpreadMethod.REFLECT for the spread method, the gradient fill looks like the following:

If you use SpreadMethod.REPEAT for the spread method, the gradient fill looks like the following:

flash.display.SpreadMethod
type A value from the GradientType class that specifies which gradient type to use.String A value from the GradientType class that specifies which gradient type to use. Values are GradientType.LINEAR or GradientType.RADIAL. flash.display.GradientType
Sprite The Sprite class is a basic display list building block: a display list node that can display graphics and can also contain children.The basic display object for ActionScript created objects. flash.display:DisplayObjectContainer The Sprite class is a basic display list building block: a display list node that can display graphics and can also contain children.

A Sprite object is similar to a movie clip, but does not have a timeline. Sprite is an appropriate base class for objects that do not require timelines. For example, Sprite would be a logical base class for user interface (UI) components that typically do not use the timeline.

The Sprite class is new in ActionScript 3.0. It provides an alternative to the functionality of the MovieClip class, which retains all the functionality of previous ActionScript releases to provide backward compatibility.

The following example uses the SpriteExample class to draw an orange square on the stage, and then dispatches events whenever the user clicks or drags the square. This task is accomplished by performing the following steps:
  1. Declare the size property (100 x 100 pixels) and the background color (orange) for later use in drawing the square.
  2. The constructor then creates a new child Sprite object and uses it to add two event listeners and their associated methods: mouseDownHandler() and mouseUpHandler().
  3. The child Sprite object is then passed to the draw() method, which draws the orange square.
  4. The child is then placed on the display list by a call to the addChild() method.
  5. The event listeners work as follows:
    • mouseDownHandler(): when the user clicks the Sprite object, this method adds a mouseMove event listener, the mouseMoveHandler() method, which processes the mouse moves. Then the startDrag() method is called, which allows the Sprite object to be dragged.
    • mouseUpHandler(): when the mouse button is released, the mouseMove event listener is removed and the stopDrag() method is called, which freezes the orange square in place.
    • mouseMoveHandler: as long as the left mouse button is being held down, this method instructs the player to continuously redraw the orange square.

Note: Each of the event listener methods declares a local sprite variable, which is assigned the target property of the event.

package { import flash.display.Sprite; import flash.events.*; public class SpriteExample extends Sprite { private var size:uint = 100; private var bgColor:uint = 0xFFCC00; public function SpriteExample() { var child:Sprite = new Sprite(); child.addEventListener(MouseEvent.MOUSE_DOWN, mouseDownHandler); child.addEventListener(MouseEvent.MOUSE_UP, mouseUpHandler); draw(child); addChild(child); } private function mouseDownHandler(event:MouseEvent):void { trace("mouseDownHandler"); var sprite:Sprite = Sprite(event.target); sprite.addEventListener(MouseEvent.MOUSE_MOVE, mouseMoveHandler); sprite.startDrag(); } private function mouseUpHandler(event:MouseEvent):void { trace("mouseUpHandler"); var sprite:Sprite = Sprite(event.target); sprite.removeEventListener(MouseEvent.MOUSE_MOVE, mouseMoveHandler); sprite.stopDrag(); } private function mouseMoveHandler(event:MouseEvent):void { trace("mouseMoveHandler"); event.updateAfterEvent(); } private function draw(sprite:Sprite):void { sprite.graphics.beginFill(bgColor); sprite.graphics.drawRect(0, 0, size, size); sprite.graphics.endFill(); } } }
Sprite Creates a new Sprite instance. Creates a new Sprite instance. After you create the Sprite instance, call the DisplayObjectContainer.addChild() or DisplayObjectContainer.addChildAt() method to add the Sprite to a parent DisplayObjectContainer. startDrag Lets the user drag the specified sprite.lockCenterBooleanfalseSpecifies whether the draggable sprite is locked to the center of the pointer position (true), or locked to the point where the user first clicked the sprite (false). boundsflash.geom:RectanglenullValue relative to the coordinates of the Sprite's parent that specify a constraint rectangle for the Sprite. Lets the user drag the specified sprite. The sprite remains draggable until explicitly stopped through a call to the Sprite.stopDrag() method, or until another sprite is made draggable. Only one sprite is draggable at a time.

Three-dimensional display objects follow the pointer and Sprite.startDrag() moves the object within the three-dimensional plane defined by the display object. Or, if the display object is a two-dimensional object and the child of a three-dimensional object, the two-dimensional object moves within the three dimensional plane defined by the three-dimensional parent object.

The following example creates a circle sprite and two target sprites. The startDrag() method is called on the circle sprite when the user positions the cursor over the sprite and presses the mouse button, and the stopDrag() method is called when the user releases the mouse button. This lets the user drag the sprite. On release of the mouse button, the mouseRelease() method is called, which in turn traces the name of the dropTarget object — the one to which the user dragged the circle sprite: import flash.display.Sprite; import flash.events.MouseEvent; var circle:Sprite = new Sprite(); circle.graphics.beginFill(0xFFCC00); circle.graphics.drawCircle(0, 0, 40); var target1:Sprite = new Sprite(); target1.graphics.beginFill(0xCCFF00); target1.graphics.drawRect(0, 0, 100, 100); target1.name = "target1"; var target2:Sprite = new Sprite(); target2.graphics.beginFill(0xCCFF00); target2.graphics.drawRect(0, 200, 100, 100); target2.name = "target2"; addChild(target1); addChild(target2); addChild(circle); circle.addEventListener(MouseEvent.MOUSE_DOWN, mouseDown) function mouseDown(event:MouseEvent):void { circle.startDrag(); } circle.addEventListener(MouseEvent.MOUSE_UP, mouseReleased); function mouseReleased(event:MouseEvent):void { circle.stopDrag(); trace(circle.dropTarget.name); }
dropTargetstopDrag()
startTouchDrag Lets the user drag the specified sprite on a touch-enabled device.touchPointIDintAn integer to assign to the touch point. lockCenterBooleanfalseSpecifies whether the draggable sprite is locked to the center of the pointer position (true), or locked to the point where the user first clicked the sprite (false). boundsflash.geom:RectanglenullValue relative to the coordinates of the Sprite's parent that specify a constraint rectangle for the Sprite. Lets the user drag the specified sprite on a touch-enabled device. The sprite remains draggable until explicitly stopped through a call to the Sprite.stopTouchDrag() method, or until another sprite is made draggable. Only one sprite is draggable at a time.

Three-dimensional display objects follow the pointer and Sprite.startTouchDrag() moves the object within the three-dimensional plane defined by the display object. Or, if the display object is a two-dimensional object and the child of a three-dimensional object, the two-dimensional object moves within the three dimensional plane defined by the three-dimensional parent object.

The following example shows functions using startTouchDrag and stopTouchDrag to handle the touchBegin and touchEnd events. The value for touchPointID is the value assigned to the event object. The bounds parameter is the rectangle defining the boundaries of the parent display object (bg is a display object containing MySprite). MySprite.addEventListener(TouchEvent.TOUCH_BEGIN, onTouchBegin); MySprite.addEventListener(TouchEvent.TOUCH_END, onTouchEnd); function onTouchBegin(e:TouchEvent) { e.target.startTouchDrag(e.touchPointID, false, bg.getRect(this)); trace("touch begin"); } function onTouchEnd(e:TouchEvent) { e.target.stopTouchDrag(e.touchPointID); trace("touch end"); }
dropTargetstopTouchDrag()flash.ui.Multitouchflash.events.TouchEvent
stopDrag Ends the startDrag() method. Ends the startDrag() method. A sprite that was made draggable with the startDrag() method remains draggable until a stopDrag() method is added, or until another sprite becomes draggable. Only one sprite is draggable at a time. The following example creates a circle sprite and two target sprites. The startDrag() method is called on the circle sprite when the user positions the cursor over the sprite and presses the mouse button, and the stopDrag() method is called when the user releases the mouse button. This lets the user drag the sprite. On release of the mouse button, the mouseRelease() method is called, which in turn traces the name of the dropTarget object — the one to which the user dragged the circle sprite: import flash.display.Sprite; import flash.events.MouseEvent; var circle:Sprite = new Sprite(); circle.graphics.beginFill(0xFFCC00); circle.graphics.drawCircle(0, 0, 40); var target1:Sprite = new Sprite(); target1.graphics.beginFill(0xCCFF00); target1.graphics.drawRect(0, 0, 100, 100); target1.name = "target1"; var target2:Sprite = new Sprite(); target2.graphics.beginFill(0xCCFF00); target2.graphics.drawRect(0, 200, 100, 100); target2.name = "target2"; addChild(target1); addChild(target2); addChild(circle); circle.addEventListener(MouseEvent.MOUSE_DOWN, mouseDown) function mouseDown(event:MouseEvent):void { circle.startDrag(); } circle.addEventListener(MouseEvent.MOUSE_UP, mouseReleased); function mouseReleased(event:MouseEvent):void { circle.stopDrag(); trace(circle.dropTarget.name); } dropTargetstartDrag()stopTouchDrag Ends the startTouchDrag() method, for use with touch-enabled devices.touchPointIDintThe integer assigned to the touch point in the startTouchDrag method. Ends the startTouchDrag() method, for use with touch-enabled devices. A sprite that was made draggable with the startTouchDrag() method remains draggable until a stopTouchDrag() method is added, or until another sprite becomes draggable. Only one sprite is draggable at a time. The following example shows functions using startTouchDrag and stopTouchDrag to handle the touchBegin and touchEnd events. The value for touchPointID is the value assigned to the event object. The bounds parameter is the rectangle defining the boundaries of the parent display object (bg is a display object containing MySprite). MySprite.addEventListener(TouchEvent.TOUCH_BEGIN, onTouchBegin); MySprite.addEventListener(TouchEvent.TOUCH_END, onTouchEnd); function onTouchBegin(e:TouchEvent) { e.target.startTouchDrag(e.touchPointID, false, bg.getRect(this)); trace("touch begin"); } function onTouchEnd(e:TouchEvent) { e.target.stopTouchDrag(e.touchPointID); trace("touch end"); } dropTargetstartTouchDrag()flash.ui.Multitouchflash.events.TouchEventbuttonMode Specifies the button mode of this sprite.BooleanSpecifies the button mode of this sprite. Specifies the button mode of this sprite. If true, this sprite behaves as a button, which means that it triggers the display of the hand cursor when the pointer passes over the sprite and can receive a click event if the enter or space keys are pressed when the sprite has focus. You can suppress the display of the hand cursor by setting the useHandCursor property to false, in which case the pointer is displayed.

Although it is better to use the SimpleButton class to create buttons, you can use the buttonMode property to give a sprite some button-like functionality. To include a sprite in the tab order, set the tabEnabled property (inherited from the InteractiveObject class and false by default) to true. Additionally, consider whether you want the children of your sprite to be user input enabled. Most buttons do not enable user input interactivity for their child objects because it confuses the event flow. To disable user input interactivity for all child objects, you must set the mouseChildren property (inherited from the DisplayObjectContainer class) to false.

If you use the buttonMode property with the MovieClip class (which is a subclass of the Sprite class), your button might have some added functionality. If you include frames labeled _up, _over, and _down, Flash Player provides automatic state changes (functionality similar to that provided in previous versions of ActionScript for movie clips used as buttons). These automatic state changes are not available for sprites, which have no timeline, and thus no frames to label.

The following example creates two sprites and sets the buttonMode property to true for one and false for the other. When you compile and run the application, both sprites respond to mouse events, but only the one in which buttonMode is set to true uses the hand cursor and is included in the tab order: import flash.display.Sprite; import flash.events.MouseEvent; var circle1:Sprite = new Sprite(); circle1.graphics.beginFill(0xFFCC00); circle1.graphics.drawCircle(40, 40, 40); circle1.buttonMode = true; circle1.addEventListener(MouseEvent.CLICK, clicked); var circle2:Sprite = new Sprite(); circle2.graphics.beginFill(0xFFCC00); circle2.graphics.drawCircle(120, 40, 40); circle2.buttonMode = false; circle2.addEventListener(MouseEvent.CLICK, clicked); function clicked(event:MouseEvent):void { trace ("Click!"); } addChild(circle1); addChild(circle2);
SimpleButtonSprite.useHandCursorInteractiveObject.tabEnabledDisplayObjectContainer.mouseChildren
dropTarget Specifies the display object over which the sprite is being dragged, or on which the sprite was dropped.flash.display:DisplayObjectSpecifies the DisplayObject over which the sprite is being dragged, or on which the sprite was dropped. Specifies the display object over which the sprite is being dragged, or on which the sprite was dropped. The following example creates a circle sprite and two target sprites. The startDrag() method is called on the circle sprite when the user positions the cursor over the sprite and presses the mouse button, and the stopDrag() method is called when the user releases the mouse button. This lets the user drag the sprite. On release of the mouse button, the mouseRelease() method is called, which in turn traces the name of the dropTarget object — the one to which the user dragged the circle sprite: import flash.display.Sprite; import flash.events.MouseEvent; var circle:Sprite = new Sprite(); circle.graphics.beginFill(0xFFCC00); circle.graphics.drawCircle(0, 0, 40); var target1:Sprite = new Sprite(); target1.graphics.beginFill(0xCCFF00); target1.graphics.drawRect(0, 0, 100, 100); target1.name = "target1"; var target2:Sprite = new Sprite(); target2.graphics.beginFill(0xCCFF00); target2.graphics.drawRect(0, 200, 100, 100); target2.name = "target2"; addChild(target1); addChild(target2); addChild(circle); circle.addEventListener(MouseEvent.MOUSE_DOWN, mouseDown) function mouseDown(event:MouseEvent):void { circle.startDrag(); } circle.addEventListener(MouseEvent.MOUSE_UP, mouseReleased); function mouseReleased(event:MouseEvent):void { circle.stopDrag(); trace(circle.dropTarget.name); } startDrag()stopDrag()graphics Specifies the Graphics object that belongs to this sprite where vector drawing commands can occur.flash.display:GraphicsSpecifies a Graphics object. Specifies the Graphics object that belongs to this sprite where vector drawing commands can occur. The following example creates a circle sprite and uses its graphics property to draw a circle with a yellow (0xFFCC00) fill: import flash.display.Sprite; var circle:Sprite = new Sprite(); circle.graphics.beginFill(0xFFCC00); circle.graphics.drawCircle(40, 40, 40); addChild(circle); hitArea Designates another sprite to serve as the hit area for a sprite.flash.display:Sprite Designates another sprite to serve as the hit area for a sprite. If the hitArea property does not exist or the value is null or undefined, the sprite itself is used as the hit area. The value of the hitArea property can be a reference to a Sprite object.

You can change the hitArea property at any time; the modified sprite immediately uses the new hit area behavior. The sprite designated as the hit area does not need to be visible; its graphical shape, although not visible, is still detected as the hit area.

Note: You must set to false the mouseEnabled property of the sprite designated as the hit area. Otherwise, your sprite button might not work because the sprite designated as the hit area receives the user input events instead of your sprite button.

The following example creates a circle sprite and a square sprite. The square sprite is the hitArea for the circle sprite. So when the user clicks the square sprite, the circle sprite dispatches a click event: import flash.display.Sprite; import flash.events.MouseEvent; var circle:Sprite = new Sprite(); circle.graphics.beginFill(0xFFCC00); circle.graphics.drawCircle(0, 0, 40); var square:Sprite = new Sprite(); square.graphics.beginFill(0xCCFF00); square.graphics.drawRect(200, 0, 100, 100); circle.hitArea = square; square.mouseEnabled = false; circle.addEventListener(MouseEvent.CLICK, clicked); function clicked(event:MouseEvent):void{ trace(event.target == circle); // true trace(event.target == square); // false } addChild(circle); addChild(square);
soundTransform Controls sound within this sprite.flash.media:SoundTransform Controls sound within this sprite.

Note: This property does not affect HTML content in an HTMLControl object (in Adobe AIR).

The following example creates a sprite named container and adds a Loader object to its child list. The Loader object loads a SWF file. When the user clicks the link in the tf text field true, the mute() method sets the volume property of the soundTransform property of the container sprite: import flash.display.Sprite; import flash.display.Loader; import flash.events.IOErrorEvent; import flash.events.MouseEvent; import flash.net.URLRequest; import flash.text.TextField; import flash.media.SoundTransform; var container:Sprite = new Sprite(); addChild(container); var ldr:Loader = new Loader; var urlReq:URLRequest = new URLRequest("SoundPlayer.swf"); ldr.load(urlReq); container.addChild(ldr); ldr.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, urlNotFound); var tf:TextField = new TextField(); tf.htmlText = "<a href = 'event:Mute'>Mute / Unmute</a>"; addChild(tf); var mySoundTransform:SoundTransform = new SoundTransform(); mySoundTransform.volume = 1; tf.addEventListener(MouseEvent.CLICK, mute); function mute(event:MouseEvent):void { if (mySoundTransform.volume == 0) { mySoundTransform.volume = 1; } else { mySoundTransform.volume = 0; } container.soundTransform = mySoundTransform; } function urlNotFound(event:IOErrorEvent):void { trace("The URL was not found."); }
flash.media.SoundTransform
useHandCursor A Boolean value that indicates whether the pointing hand (hand cursor) appears when the pointer rolls over a sprite in which the buttonMode property is set to true.BooleanA Boolean value that indicates whether the pointing hand (hand cursor) appears when the pointer rolls over a sprite in which the buttonMode property is set to true. A Boolean value that indicates whether the pointing hand (hand cursor) appears when the pointer rolls over a sprite in which the buttonMode property is set to true. The default value of the useHandCursor property is true. If useHandCursor is set to true, the pointing hand used for buttons appears when the pointer rolls over a button sprite. If useHandCursor is false, the arrow pointer is used instead.

You can change the useHandCursor property at any time; the modified sprite immediately takes on the new cursor appearance.

Note: In Flex or Flash Builder, if your sprite has child sprites, you might want to set the mouseChildren property to false. For example, if you want a hand cursor to appear over a Flex <mx:Label> control, set the useHandCursor and buttonMode properties to true, and the mouseChildren property to false.

The following example creates two sprites and sets the buttonMode property to true for both, yet it sets the useHandCursor property to true for one and false for the other. When you compile and run the application, both sprites respond as buttons (and are included in the tab order), but only the one in which useHandCursor is set to true uses the hand cursor: import flash.display.Sprite; import flash.events.MouseEvent; var circle1:Sprite = new Sprite(); circle1.graphics.beginFill(0xFFCC00); circle1.graphics.drawCircle(40, 40, 40); circle1.buttonMode = true; circle1.useHandCursor = true; circle1.addEventListener(MouseEvent.CLICK, clicked); var circle2:Sprite = new Sprite(); circle2.graphics.beginFill(0xFFCC00); circle2.graphics.drawCircle(120, 40, 40); circle2.buttonMode = true; circle2.useHandCursor = false; circle2.addEventListener(MouseEvent.CLICK, clicked); function clicked(event:MouseEvent):void { trace ("Click!"); } addChild(circle1); addChild(circle2);
buttonModeDisplayObjectContainer.mouseChildren
GraphicsBitmapFill Defines a bitmap fill.flash.display:IGraphicsFillflash.display:IGraphicsDataObject Defines a bitmap fill. The bitmap can be smoothed, repeated or tiled to fill the area; or manipulated using a transformation matrix.

Use a GraphicsBitmapFill object with the Graphics.drawGraphicsData() method. Drawing a GraphicsBitmapFill object is the equivalent of calling the Graphics.beginBitmapFill() method.

flash.display.Graphics.drawGraphicsData()flash.display.Graphics.beginBitmapFill()GraphicsBitmapFill Creates a new GraphicsBitmapFill object.bitmapDataflash.display:BitmapDatanullA transparent or opaque bitmap image that contains the bits to display. matrixflash.geom:MatrixnullA matrix object (of the flash.geom.Matrix class), which you use to define transformations on the bitmap. repeatBooleantrueIf true, the bitmap image repeats in a tiled pattern. If false, the bitmap image does not repeat, and the edges of the bitmap are used for any fill area that extends beyond the bitmap. smoothBooleanfalseIf false, upscaled bitmap images are rendered using a nearest-neighbor algorithm and appear pixelated. If true, upscaled bitmap images are rendered using a bilinear algorithm. Rendering that uses the nearest-neighbor algorithm is usually faster. Creates a new GraphicsBitmapFill object. flash.display.Graphics.beginBitmapFill()bitmapData A transparent or opaque bitmap image.flash.display:BitmapData A transparent or opaque bitmap image. flash.display.BitmapDatamatrix A matrix object (of the flash.geom.Matrix class) that defines transformations on the bitmap.flash.geom:Matrix A matrix object (of the flash.geom.Matrix class) that defines transformations on the bitmap. For example, the following matrix rotates a bitmap by 45 degrees (pi/4 radians): matrix = new flash.geom.Matrix(); matrix.rotate(Math.PI / 4); flash.geom.Matrixrepeat Specifies whether to repeat the bitmap image in a tiled pattern.Boolean Specifies whether to repeat the bitmap image in a tiled pattern.

If true, the bitmap image repeats in a tiled pattern. If false, the bitmap image does not repeat, and the outermost pixels along the edges of the bitmap are used for any fill area that extends beyond the bounds of the bitmap.

For example, consider the following bitmap (a 20 x 20-pixel checkerboard pattern):

When repeat is set to true (as in the following example), the bitmap fill repeats the bitmap:

When repeat is set to false, the bitmap fill uses the edge pixels for the fill area outside the bitmap:

smooth Specifies whether to apply a smoothing algorithm to the bitmap image.Boolean Specifies whether to apply a smoothing algorithm to the bitmap image.

If false, upscaled bitmap images are rendered by using a nearest-neighbor algorithm and look pixelated. If true, upscaled bitmap images are rendered by using a bilinear algorithm. Rendering by using the nearest neighbor algorithm is usually faster.

GraphicsStroke Defines a line style or stroke.flash.display:IGraphicsStrokeflash.display:IGraphicsDataObject Defines a line style or stroke.

Use a GraphicsStroke object with the Graphics.drawGraphicsData() method. Drawing a GraphicsStroke object is the equivalent of calling one of the methods of the Graphics class that sets the line style, such as the Graphics.lineStyle() method, the Graphics.lineBitmapStyle() method, or the Graphics.lineGradientStyle() method.

flash.display.Graphics.lineStyle()flash.display.Graphics.lineBitmapStyle()flash.display.Graphics.lineGradientStyle()flash.display.Graphics.drawGraphicsData()GraphicsStroke Creates a new GraphicsStroke object.thicknessNumberunknownAn integer that indicates the thickness of the line in points; valid values are 0-255. If a number is not specified, or if the parameter is undefined, a line is not drawn. If a value of less than 0 is passed, the default is 0. The value 0 indicates hairline thickness; the maximum thickness is 255. If a value greater than 255 is passed, the default is 255. pixelHintingBooleanfalseA Boolean value that specifies whether to hint strokes to full pixels. This affects both the position of anchors of a curve and the line stroke size itself. With pixelHinting set to true, Flash Player hints line widths to full pixel widths. With pixelHinting set to false, disjoints can appear for curves and straight lines. For example, the following illustrations show how Flash Player renders two rounded rectangles that are identical, except that the pixelHinting parameter used in the lineStyle() method is set differently (the images are scaled by 200%, to emphasize the difference):

If a value is not supplied, the line does not use pixel hinting.

scaleModeStringnormalA value from the LineScaleMode class that specifies which scale mode to use:
  • LineScaleMode.NORMAL—Always scale the line thickness when the object is scaled (the default).
  • LineScaleMode.NONE—Never scale the line thickness.
  • LineScaleMode.VERTICAL—Do not scale the line thickness if the object is scaled vertically only. For example, consider the following circles, drawn with a one-pixel line, and each with the scaleMode parameter set to LineScaleMode.VERTICAL. The circle on the left is scaled vertically only, and the circle on the right is scaled both vertically and horizontally:

  • LineScaleMode.HORIZONTAL—Do not scale the line thickness if the object is scaled horizontally only. For example, consider the following circles, drawn with a one-pixel line, and each with the scaleMode parameter set to LineScaleMode.HORIZONTAL. The circle on the left is scaled horizontally only, and the circle on the right is scaled both vertically and horizontally:

capsStringnoneA value from the CapsStyle class that specifies the type of caps at the end of lines. Valid values are: CapsStyle.NONE, CapsStyle.ROUND, and CapsStyle.SQUARE. If a value is not indicated, Flash uses round caps.

For example, the following illustrations show the different capsStyle settings. For each setting, the illustration shows a blue line with a thickness of 30 (for which the capsStyle applies), and a superimposed black line with a thickness of 1 (for which no capsStyle applies):

jointsStringroundA value from the JointStyle class that specifies the type of joint appearance used at angles. Valid values are: JointStyle.BEVEL, JointStyle.MITER, and JointStyle.ROUND. If a value is not indicated, Flash uses round joints.

For example, the following illustrations show the different joints settings. For each setting, the illustration shows an angled blue line with a thickness of 30 (for which the jointStyle applies), and a superimposed angled black line with a thickness of 1 (for which no jointStyle applies):

Note: For joints set to JointStyle.MITER, you can use the miterLimit parameter to limit the length of the miter.

miterLimitNumber3.0A number that indicates the limit at which a miter is cut off. Valid values range from 1 to 255 (and values outside that range are rounded to 1 or 255). This value is only used if the jointStyle is set to "miter". The miterLimit value represents the length that a miter can extend beyond the point at which the lines meet to form a joint. The value expresses a factor of the line thickness. For example, with a miterLimit factor of 2.5 and a thickness of 10 pixels, the miter is cut off at 25 pixels.

For example, consider the following angled lines, each drawn with a thickness of 20, but with miterLimit set to 1, 2, and 4. Superimposed are black reference lines showing the meeting points of the joints:

Notice that a given miterLimit value has a specific maximum angle for which the miter is cut off. The following table lists some examples:

miterLimit value:Angles smaller than this are cut off:1.41490 degrees260 degrees430 degrees815 degrees
fillflash.display:IGraphicsFillnullAn IGraphicsFill instance containing data for filling a stroke. An IGraphicsFill instance can represent a series of fill commands.
Creates a new GraphicsStroke object.
flash.display.LineScaleModeflash.display.CapsStyleflash.display.JointStyleflash.display.IGraphicsFill
fill Specifies the instance containing data for filling a stroke.flash.display:IGraphicsFill Specifies the instance containing data for filling a stroke. An IGraphicsFill instance can represent a series of fill commands. flash.display.IGraphicsFillmiterLimit Indicates the limit at which a miter is cut off.Number Indicates the limit at which a miter is cut off. Valid values range from 1 to 255 (and values outside that range are rounded to 1 or 255). This value is only used if the jointStyle is set to "miter". The miterLimit value represents the length that a miter can extend beyond the point at which the lines meet to form a joint. The value expresses a factor of the line thickness. For example, with a miterLimit factor of 2.5 and a thickness of 10 pixels, the miter is cut off at 25 pixels.

For example, consider the following angled lines, each drawn with a thickness of 20, but with miterLimit set to 1, 2, and 4. Superimposed are black reference lines showing the meeting points of the joints:

Notice that a given miterLimit value has a specific maximum angle for which the miter is cut off. The following table lists some examples:

miterLimit value:Angles smaller than this are cut off:1.41490 degrees260 degrees430 degrees815 degrees
pixelHinting Specifies whether to hint strokes to full pixels.Boolean Specifies whether to hint strokes to full pixels. This affects both the position of anchors of a curve and the line stroke size itself. With pixelHinting set to true, Flash Player hints line widths to full pixel widths. With pixelHinting set to false, disjoints can appear for curves and straight lines. For example, the following illustrations show how Flash Player renders two rounded rectangles that are identical, except that the pixelHinting parameter used in the lineStyle() method is set differently (the images are scaled by 200%, to emphasize the difference):

thickness Indicates the thickness of the line in points; valid values are 0-255.Number Indicates the thickness of the line in points; valid values are 0-255. If a number is not specified, or if the parameter is undefined, a line is not drawn. If a value of less than 0 is passed, the default is 0. The value 0 indicates hairline thickness; the maximum thickness is 255. If a value greater than 255 is passed, the default is 255. caps Specifies the type of caps at the end of lines.String Specifies the type of caps at the end of lines. Valid values are: CapsStyle.NONE, CapsStyle.ROUND, and CapsStyle.SQUARE. If a value is not indicated, Flash uses round caps.

For example, the following illustrations show the different capsStyle settings. For each setting, the illustration shows a blue line with a thickness of 30 (for which the capsStyle applies), and a superimposed black line with a thickness of 1 (for which no capsStyle applies):

flash.display.CapsStyle
joints Specifies the type of joint appearance used at angles.String Specifies the type of joint appearance used at angles. Valid values are: JointStyle.BEVEL, JointStyle.MITER, and JointStyle.ROUND. If a value is not indicated, Flash uses round joints.

For example, the following illustrations show the different joints settings. For each setting, the illustration shows an angled blue line with a thickness of 30 (for which the jointStyle applies), and a superimposed angled black line with a thickness of 1 (for which no jointStyle applies):

Note: For joints set to JointStyle.MITER, you can use the miterLimit parameter to limit the length of the miter.

flash.display.JointStyle
scaleMode Specifies the stroke thickness scaling.String Specifies the stroke thickness scaling. Valid values are:
  • LineScaleMode.NORMAL—Always scale the line thickness when the object is scaled (the default).
  • LineScaleMode.NONE—Never scale the line thickness.
  • LineScaleMode.VERTICAL—Do not scale the line thickness if the object is scaled vertically only. For example, consider the following circles, drawn with a one-pixel line, and each with the scaleMode parameter set to LineScaleMode.VERTICAL. The circle on the left is scaled vertically only, and the circle on the right is scaled both vertically and horizontally:

  • LineScaleMode.HORIZONTAL—Do not scale the line thickness if the object is scaled horizontally only. For example, consider the following circles, drawn with a one-pixel line, and each with the scaleMode parameter set to LineScaleMode.HORIZONTAL. The circle on the left is scaled horizontally only, and the circle on the right is scaled both vertically and horizontally:

flash.display.LineScaleMode
GraphicsEndFill Indicates the end of a graphics fill.flash.display:IGraphicsFillflash.display:IGraphicsDataObject Indicates the end of a graphics fill. Use a GraphicsEndFill object with the Graphics.drawGraphicsData() method.

Drawing a GraphicsEndFill object is the equivalent of calling the Graphics.endFill() method.

flash.display.Graphics.drawGraphicsData()flash.display.Graphics.endFill()GraphicsEndFill Creates an object to use with the Graphics.drawGraphicsData() method to end the fill, explicitly. Creates an object to use with the Graphics.drawGraphicsData() method to end the fill, explicitly. flash.display.Graphics.drawGraphicsData()flash.display.Graphics.endFill()
ShaderPrecision This class defines the constants that represent the possible values for the Shader class's precisionHint property.Object This class defines the constants that represent the possible values for the Shader class's precisionHint property. Each constant represents one of the precision modes for executing shader operations.

The precision mode selection affects the following shader operations. These operations are faster on an Intel processor with the SSE instruction set:

  • sin(x)
  • cos(x)
  • tan(x)
  • asin(x)
  • acos(x)
  • atan(x)
  • atan(x, y)
  • exp(x)
  • exp2(x)
  • log(x)
  • log2(x)
  • pow(x, y)
  • reciprocal(x)
  • sqrt(x)
flash.display.Shader.precisionHintFAST Represents fast precision mode.fastString Represents fast precision mode.

Fast precision mode is designed for maximum performance but does not work consistently on different platforms and individual CPU configurations. In many cases, this level of precision is sufficient to create graphic effects without visible artifacts.

It is usually faster to use fast precision mode than to use lookup tables.

flash.display.Shader.precisionHint
FULL Represents full precision mode.fullString Represents full precision mode.

In full precision mode, the shader computes all math operations to the full width of the IEEE 32-bit floating standard. This mode provides consistent behavior on all platforms. In this mode, some math operations such as trigonometric and exponential functions can be slow.

flash.display.Shader.precisionHint
BlendMode A class that provides constant values for visual blend mode effects.Object A class that provides constant values for visual blend mode effects. These constants are used in the following:
  • The blendMode property of the flash.display.DisplayObject class.
  • The blendMode parameter of the draw() method of the flash.display.BitmapData class
flash.display.DisplayObject.blendModeflash.display.BitmapData.draw()ADD Adds the values of the constituent colors of the display object to the colors of its background, applying a ceiling of 0xFF.addString Adds the values of the constituent colors of the display object to the colors of its background, applying a ceiling of 0xFF. This setting is commonly used for animating a lightening dissolve between two objects.

For example, if the display object has a pixel with an RGB value of 0xAAA633, and the background pixel has an RGB value of 0xDD2200, the resulting RGB value for the displayed pixel is 0xFFC833 (because 0xAA + 0xDD > 0xFF, 0xA6 + 0x22 = 0xC8, and 0x33 + 0x00 = 0x33).

ALPHA Applies the alpha value of each pixel of the display object to the background.alphaString Applies the alpha value of each pixel of the display object to the background. This requires the blendMode property of the parent display object be set to flash.display.BlendMode.LAYER.

Not supported under GPU rendering.

DARKEN Selects the darker of the constituent colors of the display object and the colors of the background (the colors with the smaller values).darkenString Selects the darker of the constituent colors of the display object and the colors of the background (the colors with the smaller values). This setting is commonly used for superimposing type.

For example, if the display object has a pixel with an RGB value of 0xFFCC33, and the background pixel has an RGB value of 0xDDF800, the resulting RGB value for the displayed pixel is 0xDDCC00 (because 0xFF > 0xDD, 0xCC < 0xF8, and 0x33 > 0x00 = 33).

Not supported under GPU rendering.

DIFFERENCE Compares the constituent colors of the display object with the colors of its background, and subtracts the darker of the values of the two constituent colors from the lighter value.differenceString Compares the constituent colors of the display object with the colors of its background, and subtracts the darker of the values of the two constituent colors from the lighter value. This setting is commonly used for more vibrant colors.

For example, if the display object has a pixel with an RGB value of 0xFFCC33, and the background pixel has an RGB value of 0xDDF800, the resulting RGB value for the displayed pixel is 0x222C33 (because 0xFF - 0xDD = 0x22, 0xF8 - 0xCC = 0x2C, and 0x33 - 0x00 = 0x33).

ERASE Erases the background based on the alpha value of the display object.eraseString Erases the background based on the alpha value of the display object. This process requires that the blendMode property of the parent display object be set to flash.display.BlendMode.LAYER.

Not supported under GPU rendering.

HARDLIGHT Adjusts the color of each pixel based on the darkness of the display object.hardlightString Adjusts the color of each pixel based on the darkness of the display object. If the display object is lighter than 50% gray, the display object and background colors are screened, which results in a lighter color. If the display object is darker than 50% gray, the colors are multiplied, which results in a darker color. This setting is commonly used for shading effects.

Not supported under GPU rendering.

INVERT Inverts the background.invertString Inverts the background. LAYER Forces the creation of a transparency group for the display object.layerString Forces the creation of a transparency group for the display object. This means that the display object is precomposed in a temporary buffer before it is processed further. The precomposition is done automatically if the display object is precached by means of bitmap caching or if the display object is a display object container that has at least one child object with a blendMode setting other than "normal".

Not supported under GPU rendering.

LIGHTEN Selects the lighter of the constituent colors of the display object and the colors of the background (the colors with the larger values).lightenString Selects the lighter of the constituent colors of the display object and the colors of the background (the colors with the larger values). This setting is commonly used for superimposing type.

For example, if the display object has a pixel with an RGB value of 0xFFCC33, and the background pixel has an RGB value of 0xDDF800, the resulting RGB value for the displayed pixel is 0xFFF833 (because 0xFF > 0xDD, 0xCC < 0xF8, and 0x33 > 0x00 = 33).

Not supported under GPU rendering.

MULTIPLY Multiplies the values of the display object constituent colors by the constituent colors of the background color, and normalizes by dividing by 0xFF, resulting in darker colors.multiplyString Multiplies the values of the display object constituent colors by the constituent colors of the background color, and normalizes by dividing by 0xFF, resulting in darker colors. This setting is commonly used for shadows and depth effects.

For example, if a constituent color (such as red) of one pixel in the display object and the corresponding color of the pixel in the background both have the value 0x88, the multiplied result is 0x4840. Dividing by 0xFF yields a value of 0x48 for that constituent color, which is a darker shade than the color of the display object or the color of the background.

NORMAL The display object appears in front of the background.normalString The display object appears in front of the background. Pixel values of the display object override the pixel values of the background. Where the display object is transparent, the background is visible. OVERLAY Adjusts the color of each pixel based on the darkness of the background.overlayString Adjusts the color of each pixel based on the darkness of the background. If the background is lighter than 50% gray, the display object and background colors are screened, which results in a lighter color. If the background is darker than 50% gray, the colors are multiplied, which results in a darker color. This setting is commonly used for shading effects.

Not supported under GPU rendering.

SCREEN Multiplies the complement (inverse) of the display object color by the complement of the background color, resulting in a bleaching effect.screenString Multiplies the complement (inverse) of the display object color by the complement of the background color, resulting in a bleaching effect. This setting is commonly used for highlights or to remove black areas of the display object. SHADER Uses a shader to define the blend between objects.shaderString Uses a shader to define the blend between objects.

Setting the blendShader property to a Shader instance automatically sets the display object's blendMode property to BlendMode.SHADER. If the blendMode property is set to BlendMode.SHADER without first setting the blendShader property, the blendMode property is set to BlendMode.NORMAL instead. If the blendShader property is set (which sets the blendMode property to BlendMode.SHADER), then later the value of the blendMode property is changed, the blend mode can be reset to use the blend shader simply by setting the blendMode property to BlendMode.SHADER. The blendShader property does not need to be set again except to change the shader that's used to define the blend mode.

Not supported under GPU rendering.

flash.display.DisplayObject.blendModeflash.display.DisplayObject.blendShaderflash.display.Shader
SUBTRACT Subtracts the values of the constituent colors in the display object from the values of the background color, applying a floor of 0.subtractString Subtracts the values of the constituent colors in the display object from the values of the background color, applying a floor of 0. This setting is commonly used for animating a darkening dissolve between two objects.

For example, if the display object has a pixel with an RGB value of 0xAA2233, and the background pixel has an RGB value of 0xDDA600, the resulting RGB value for the displayed pixel is 0x338400 (because 0xDD - 0xAA = 0x33, 0xA6 - 0x22 = 0x84, and 0x00 - 0x33 < 0x00).

Graphics The Graphics class contains a set of methods that you can use to create a vector shape.Object The Graphics class contains a set of methods that you can use to create a vector shape. Display objects that support drawing include Sprite and Shape objects. Each of these classes includes a graphics property that is a Graphics object. The following are among those helper functions provided for ease of use: drawRect(), drawRoundRect(), drawCircle(), and drawEllipse().

You cannot create a Graphics object directly from ActionScript code. If you call new Graphics(), an exception is thrown.

The Graphics class is final; it cannot be subclassed.

The following example uses the GraphicsExample class to draw a circle, a rounded rectangle, and a square. This task is accomplished by using the following steps:
  1. Declare a size property for later use in determining the size of each shape.
  2. Declare properties that set the background color to orange, the border color to dark gray, the border size to 0 pixels, the corner radius to 9 pixels, and set the space between the stage edge and the other objects to be 5 pixels.
  3. Use the properties declared in the preceding steps along with the built in methods of the Graphics class to draw the circle, rounded rectangle, and square at coordinates x = 0, y = 0.
  4. Redraw each of the shapes along the top of the stage, starting at x = 5, y = 5, with a 5-pixel spacing between shapes.
package { import flash.display.DisplayObject; import flash.display.Graphics; import flash.display.Shape; import flash.display.Sprite; public class GraphicsExample extends Sprite { private var size:uint = 80; private var bgColor:uint = 0xFFCC00; private var borderColor:uint = 0x666666; private var borderSize:uint = 0; private var cornerRadius:uint = 9; private var gutter:uint = 5; public function GraphicsExample() { doDrawCircle(); doDrawRoundRect(); doDrawRect(); refreshLayout(); } private function refreshLayout():void { var ln:uint = numChildren; var child:DisplayObject; var lastChild:DisplayObject = getChildAt(0); lastChild.x = gutter; lastChild.y = gutter; for (var i:uint = 1; i < ln; i++) { child = getChildAt(i); child.x = gutter + lastChild.x + lastChild.width; child.y = gutter; lastChild = child; } } private function doDrawCircle():void { var child:Shape = new Shape(); var halfSize:uint = Math.round(size / 2); child.graphics.beginFill(bgColor); child.graphics.lineStyle(borderSize, borderColor); child.graphics.drawCircle(halfSize, halfSize, halfSize); child.graphics.endFill(); addChild(child); } private function doDrawRoundRect():void { var child:Shape = new Shape(); child.graphics.beginFill(bgColor); child.graphics.lineStyle(borderSize, borderColor); child.graphics.drawRoundRect(0, 0, size, size, cornerRadius); child.graphics.endFill(); addChild(child); } private function doDrawRect():void { var child:Shape = new Shape(); child.graphics.beginFill(bgColor); child.graphics.lineStyle(borderSize, borderColor); child.graphics.drawRect(0, 0, size, size); child.graphics.endFill(); addChild(child); } } }
beginBitmapFill Fills a drawing area with a bitmap image.bitmapflash.display:BitmapDataA transparent or opaque bitmap image that contains the bits to be displayed. matrixflash.geom:MatrixnullA matrix object (of the flash.geom.Matrix class), which you can use to define transformations on the bitmap. For example, you can use the following matrix to rotate a bitmap by 45 degrees (pi/4 radians): matrix = new flash.geom.Matrix(); matrix.rotate(Math.PI / 4); repeatBooleantrueIf true, the bitmap image repeats in a tiled pattern. If false, the bitmap image does not repeat, and the edges of the bitmap are used for any fill area that extends beyond the bitmap.

For example, consider the following bitmap (a 20 x 20-pixel checkerboard pattern):

When repeat is set to true (as in the following example), the bitmap fill repeats the bitmap:

When repeat is set to false, the bitmap fill uses the edge pixels for the fill area outside the bitmap:

smoothBooleanfalseIf false, upscaled bitmap images are rendered by using a nearest-neighbor algorithm and look pixelated. If true, upscaled bitmap images are rendered by using a bilinear algorithm. Rendering by using the nearest neighbor algorithm is faster. Begins a bitmap filled shape.
Fills a drawing area with a bitmap image. The bitmap can be repeated or tiled to fill the area. The fill remains in effect until you call the beginFill(), beginBitmapFill(), beginGradientFill(), or beginShaderFill() method. Calling the clear() method clears the fill.

The application renders the fill whenever three or more points are drawn, or when the endFill() method is called.

The following example uses an image (image1.jpg) that is rotated and repeated to fill in a rectangle.
  1. The image file (image1.jpg) is loaded using the Loader and URLRequest objects. Here the file is in the same directory as the SWF file. The SWF file needs to be compiled with Local Playback Security set to Access Local Files Only.
  2. When the image is loaded (Event is complete), the drawImage() method is called. The ioErrorHandler() method writes a trace comment if the image was not loaded properly.
  3. In drawImage() method, a BitmapData object is instantiated and its width and height are set to the image (image1.jpg). Then the source image is drawn into the BitmapData object. Next, a rectangle is drawn in the mySprite Sprite object and the BitmapData object is used to fill it. Using a Matrix object, the beginBitmapFill() method rotates the image 45 degrees, then it begins filling the rectangle with the image until it is finished.
package { import flash.display.Sprite; import flash.display.BitmapData; import flash.display.Loader; import flash.net.URLRequest; import flash.events.Event; import flash.events.IOErrorEvent; import flash.geom.Matrix; public class Graphics_beginBitmapFillExample extends Sprite { private var url:String = "image1.jpg"; private var loader:Loader = new Loader(); public function Graphics_beginBitmapFillExample() { var request:URLRequest = new URLRequest(url); loader.load(request); loader.contentLoaderInfo.addEventListener(Event.COMPLETE, drawImage); loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler); } private function drawImage(event:Event):void { var mySprite:Sprite = new Sprite(); var myBitmap:BitmapData = new BitmapData(loader.width, loader.height, false); myBitmap.draw(loader, new Matrix()); var matrix:Matrix = new Matrix(); matrix.rotate(Math.PI/4); mySprite.graphics.beginBitmapFill(myBitmap, matrix, true); mySprite.graphics.drawRect(100, 50, 200, 90); mySprite.graphics.endFill(); addChild(mySprite); } private function ioErrorHandler(event:IOErrorEvent):void { trace("Unable to load image: " + url); } } }
endFill()beginFill()beginGradientFill()
beginFill Specifies a simple one-color fill that subsequent calls to other Graphics methods (such as lineTo() or drawCircle()) use when drawing.coloruintThe color of the fill (0xRRGGBB). alphaNumber1.0The alpha value of the fill (0.0 to 1.0). Specifies a single-color fill. Specifies a simple one-color fill that subsequent calls to other Graphics methods (such as lineTo() or drawCircle()) use when drawing. The fill remains in effect until you call the beginFill(), beginBitmapFill(), beginGradientFill(), or beginShaderFill() method. Calling the clear() method clears the fill.

The application renders the fill whenever three or more points are drawn, or when the endFill() method is called.

Please see the example at the end of this class for an illustration of how to use this method.
endFill()beginBitmapFill()beginGradientFill()
beginGradientFill Specifies a gradient fill used by subsequent calls to other Graphics methods (such as lineTo() or drawCircle()) for the object.If the type parameter is not valid. ArgumentErrorArgumentErrortypeStringA value from the GradientType class that specifies which gradient type to use: GradientType.LINEAR or GradientType.RADIAL. colorsArrayAn array of RGB hexadecimal color values used in the gradient; for example, red is 0xFF0000, blue is 0x0000FF, and so on. You can specify up to 15 colors. For each color, specify a corresponding value in the alphas and ratios parameters. alphasArrayAn array of alpha values for the corresponding colors in the colors array; valid values are 0 to 1. If the value is less than 0, the default is 0. If the value is greater than 1, the default is 1. ratiosArrayAn array of color distribution ratios; valid values are 0-255. This value defines the percentage of the width where the color is sampled at 100%. The value 0 represents the left position in the gradient box, and 255 represents the right position in the gradient box.

Note: This value represents positions in the gradient box, not the coordinate space of the final gradient, which can be wider or thinner than the gradient box. Specify a value for each value in the colors parameter.

For example, for a linear gradient that includes two colors, blue and green, the following example illustrates the placement of the colors in the gradient based on different values in the ratios array:

ratiosGradient[0, 127][0, 255][127, 255]

The values in the array must increase sequentially; for example, [0, 63, 127, 190, 255].

matrixflash.geom:MatrixnullA transformation matrix as defined by the flash.geom.Matrix class. The flash.geom.Matrix class includes a createGradientBox() method, which lets you conveniently set up the matrix for use with the beginGradientFill() method. spreadMethodStringpadA value from the SpreadMethod class that specifies which spread method to use, either: SpreadMethod.PAD, SpreadMethod.REFLECT, or SpreadMethod.REPEAT.

For example, consider a simple linear gradient between two colors:

import flash.geom.* import flash.display.* var fillType:String = GradientType.LINEAR; var colors:Array = [0xFF0000, 0x0000FF]; var alphas:Array = [1, 1]; var ratios:Array = [0x00, 0xFF]; var matr:Matrix = new Matrix(); matr.createGradientBox(20, 20, 0, 0, 0); var spreadMethod:String = SpreadMethod.PAD; this.graphics.beginGradientFill(fillType, colors, alphas, ratios, matr, spreadMethod); this.graphics.drawRect(0,0,100,100);

This example uses SpreadMethod.PAD for the spread method, and the gradient fill looks like the following:

If you use SpreadMethod.REFLECT for the spread method, the gradient fill looks like the following:

If you use SpreadMethod.REPEAT for the spread method, the gradient fill looks like the following:

interpolationMethodStringrgbA value from the InterpolationMethod class that specifies which value to use: InterpolationMethod.LINEAR_RGB or InterpolationMethod.RGB

For example, consider a simple linear gradient between two colors (with the spreadMethod parameter set to SpreadMethod.REFLECT). The different interpolation methods affect the appearance as follows:

InterpolationMethod.LINEAR_RGBInterpolationMethod.RGB
focalPointRatioNumber0A number that controls the location of the focal point of the gradient. 0 means that the focal point is in the center. 1 means that the focal point is at one border of the gradient circle. -1 means that the focal point is at the other border of the gradient circle. A value less than -1 or greater than 1 is rounded to -1 or 1. For example, the following example shows a focalPointRatio set to 0.75:

Specifies a gradient fill.
Specifies a gradient fill used by subsequent calls to other Graphics methods (such as lineTo() or drawCircle()) for the object. The fill remains in effect until you call the beginFill(), beginBitmapFill(), beginGradientFill(), or beginShaderFill() method. Calling the clear() method clears the fill.

The application renders the fill whenever three or more points are drawn, or when the endFill() method is called.

endFill()beginFill()beginBitmapFill()flash.geom.Matrix.createGradientBox()flash.display.GradientTypeflash.display.SpreadMethod
beginShaderFill Specifies a shader fill used by subsequent calls to other Graphics methods (such as lineTo() or drawCircle()) for the object.When the shader output type is not compatible with this operation (the shader must specify a pixel3 or pixel4 output). ArgumentErrorArgumentErrorWhen the shader specifies an image input that isn't provided. ArgumentErrorArgumentErrorWhen a ByteArray or Vector.<Number> instance is used as an input and the width and height properties aren't specified for the ShaderInput, or the specified values don't match the amount of data in the input object. See the ShaderInput.input property for more information. ArgumentErrorArgumentErrorshaderflash.display:ShaderThe shader to use for the fill. This Shader instance is not required to specify an image input. However, if an image input is specified in the shader, the input must be provided manually. To specify the input, set the input property of the corresponding ShaderInput property of the Shader.data property.

When you pass a Shader instance as an argument the shader is copied internally. The drawing fill operation uses that internal copy, not a reference to the original shader. Any changes made to the shader, such as changing a parameter value, input, or bytecode, are not applied to the copied shader that's used for the fill.

matrixflash.geom:MatrixnullA matrix object (of the flash.geom.Matrix class), which you can use to define transformations on the shader. For example, you can use the following matrix to rotate a shader by 45 degrees (pi/4 radians): matrix = new flash.geom.Matrix(); matrix.rotate(Math.PI / 4);

The coordinates received in the shader are based on the matrix that is specified for the matrix parameter. For a default (null) matrix, the coordinates in the shader are local pixel coordinates which can be used to sample an input.

Specifies a shader fill.
Specifies a shader fill used by subsequent calls to other Graphics methods (such as lineTo() or drawCircle()) for the object. The fill remains in effect until you call the beginFill(), beginBitmapFill(), beginGradientFill(), or beginShaderFill() method. Calling the clear() method clears the fill.

The application renders the fill whenever three or more points are drawn, or when the endFill() method is called.

Shader fills are not supported under GPU rendering; filled areas will be colored cyan.

endFill()beginFill()beginBitmapFill()beginGradientFill()flash.display.ShaderInput
clear Clears the graphics that were drawn to this Graphics object, and resets fill and line style settings. Clears the graphics that were drawn to this Graphics object, and resets fill and line style settings. copyFrom Copies all of drawing commands from the source Graphics object into the calling Graphics object.sourceGraphicsflash.display:GraphicsThe Graphics object from which to copy the drawing commands. Copies all of drawing commands from the source Graphics object into the calling Graphics object. curveTo Draws a curve using the current line style from the current drawing position to (anchorX, anchorY) and using the control point that (controlX, controlY) specifies.controlXNumberA number that specifies the horizontal position of the control point relative to the registration point of the parent display object. controlYNumberA number that specifies the vertical position of the control point relative to the registration point of the parent display object. anchorXNumberA number that specifies the horizontal position of the next anchor point relative to the registration point of the parent display object. anchorYNumberA number that specifies the vertical position of the next anchor point relative to the registration point of the parent display object. Draws a curve from the current drawing position to (anchorX, anchorY) using the control point specified by (controlX, controlY). Draws a curve using the current line style from the current drawing position to (anchorX, anchorY) and using the control point that (controlX, controlY) specifies. The current drawing position is then set to (anchorX, anchorY). If the movie clip in which you are drawing contains content created with the Flash drawing tools, calls to the curveTo() method are drawn underneath this content. If you call the curveTo() method before any calls to the moveTo() method, the default of the current drawing position is (0, 0). If any of the parameters are missing, this method fails and the current drawing position is not changed.

The curve drawn is a quadratic Bezier curve. Quadratic Bezier curves consist of two anchor points and one control point. The curve interpolates the two anchor points and curves toward the control point.

The following example draws a green circular object with a width and height of 100 pixels, 250 pixels to the right from the registration point (0, 0) of Sprite display object.

Draw four curves to produce a circle and fill it green.

Note that due to the nature of the quadratic Bezier equation, this is not a perfect circle. The best way to draw a circle is to use the Graphics class's drawCircle() method.

package { import flash.display.Sprite; import flash.display.Shape; public class Graphics_curveToExample1 extends Sprite { public function Graphics_curveToExample1():void { var roundObject:Shape = new Shape(); roundObject.graphics.beginFill(0x00FF00); roundObject.graphics.moveTo(250, 0); roundObject.graphics.curveTo(300, 0, 300, 50); roundObject.graphics.curveTo(300, 100, 250, 100); roundObject.graphics.curveTo(200, 100, 200, 50); roundObject.graphics.curveTo(200, 0, 250, 0); roundObject.graphics.endFill(); this.addChild(roundObject); } } }
The following example draws a new moon using curveTo() method.

Two curve lines of 1 pixel are drawn and the space in between is filled white. The moveTo() method is used to position the current drawing position to coordinates (100, 100). The first curve moves the drawing position to (100, 200), its destination point. The second curve returns the position back to the starting position (100, 100), its destination point. The horizontal control points determine the different curve sizes.

package { import flash.display.Sprite; import flash.display.Shape; public class Graphics_curveToExample2 extends Sprite { public function Graphics_curveToExample2() { var newMoon:Shape = new Shape(); newMoon.graphics.lineStyle(1, 0); newMoon.graphics.beginFill(0xFFFFFF); newMoon.graphics.moveTo(100, 100); newMoon.graphics.curveTo(30, 150, 100, 200); newMoon.graphics.curveTo(50, 150, 100, 100); graphics.endFill(); this.addChild(newMoon); } } }
drawCircle Draws a circle.xNumberThe x location of the center of the circle relative to the registration point of the parent display object (in pixels). yNumberThe y location of the center of the circle relative to the registration point of the parent display object (in pixels). radiusNumberThe radius of the circle (in pixels). Draws a circle. Draws a circle. Set the line style, fill, or both before you call the drawCircle() method, by calling the linestyle(), lineGradientStyle(), beginFill(), beginGradientFill(), or beginBitmapFill() method. Please see the example at the end of this class for an illustration of how to use this method. drawEllipse()lineStyle()lineGradientStyle()beginFill()beginGradientFill()beginBitmapFill()drawEllipse Draws an ellipse.xNumberThe x location of the top-left of the bounding-box of the ellipse relative to the registration point of the parent display object (in pixels). yNumberThe y location of the top left of the bounding-box of the ellipse relative to the registration point of the parent display object (in pixels). widthNumberThe width of the ellipse (in pixels). heightNumberThe height of the ellipse (in pixels). Draws an ellipse. Draws an ellipse. Set the line style, fill, or both before you call the drawEllipse() method, by calling the linestyle(), lineGradientStyle(), beginFill(), beginGradientFill(), or beginBitmapFill() method. The following example uses the function drawEgg() to draw three different sized eggs (three sizes of ellipses), depending on the eggSize parameter.
  1. The constructor calls the function drawEgg() and passes the horizontal and vertical parameters for where the egg should be drawn, plus the type of egg (eggSize). (The height and width of the eggs (the ellipses) can be used to decide where to display them.)
  2. Function drawEgg() draws the different size ellipses and fills them white using beginFill() method. There is no advance error handling written for his function.
package { import flash.display.Sprite; import flash.display.Shape; public class Graphics_drawEllipseExample extends Sprite { public static const SMALL:uint = 0; public static const MEDIUM:uint = 1; public static const LARGE:uint = 2; public function Graphics_drawEllipseExample() { drawEgg(SMALL, 0, 100); drawEgg(MEDIUM, 100, 60); drawEgg(LARGE, 250, 35); } public function drawEgg(eggSize:uint, x:Number, y:Number):void { var myEgg:Shape = new Shape(); myEgg.graphics.beginFill(0xFFFFFF); myEgg.graphics.lineStyle(1); switch(eggSize) { case SMALL: myEgg.graphics.drawEllipse(x, y, 60, 70); break; case MEDIUM: myEgg.graphics.drawEllipse(x, y, 120, 150); break; case LARGE: myEgg.graphics.drawEllipse(x, y, 150, 200); break; default: trace ("Wrong size! There is no egg."); break; } myEgg.graphics.endFill(); this.addChild(myEgg); } } }
drawCircle()lineStyle()lineGradientStyle()beginFill()beginGradientFill()beginBitmapFill()
drawGraphicsData Submits a series of IGraphicsData instances for drawing.graphicsDataA Vector containing graphics objects, each of which much implement the IGraphicsData interface. Submits a series of IGraphicsData instances for drawing. This method accepts a Vector containing objects including paths, fills, and strokes that implement the IGraphicsData interface. A Vector of IGraphicsData instances can refer to a part of a shape, or a complex fully defined set of data for rendering a complete shape.

Graphics paths can contain other graphics paths. If the graphicsData Vector includes a path, that path and all its sub-paths are rendered during this operation.

The following example creates a GraphicsGradientFill object to establish the fill properties for a square. Then, the example creates a GraphicsStroke object (for the line thickness) class and a GraphicsSolidFill object (for the line color) to set the properties for the border line of the square. The example then creates a GraphicsPath object to contain the values for drawing the shape. All of these objects are stored in an IGraphicsData object, and passed to the drawGraphicsData() command to render the shape. package{ import flash.display.*; import flash.geom.*; public class DrawGraphicsDataExample extends Sprite { public function DrawGraphicsDataExample(){ // establish the fill properties var myFill:GraphicsGradientFill = new GraphicsGradientFill(); myFill.colors = [0xEEFFEE, 0x0000FF]; myFill.matrix = new Matrix(); myFill.matrix.createGradientBox(100, 100, 0); // establish the stroke properties var myStroke:GraphicsStroke = new GraphicsStroke(2); myStroke.fill = new GraphicsSolidFill(0x000000); // establish the path properties var myPath:GraphicsPath = new GraphicsPath(new Vector.<int>(), new Vector.<Number>()); myPath.commands.push(1,2,2,2,2); myPath.data.push(10,10, 10,100, 100,100, 100,10, 10,10); // populate the IGraphicsData Vector array var myDrawing:Vector.<IGraphicsData> = new Vector.<IGraphicsData>(); myDrawing.push(myFill, myStroke, myPath); // render the drawing graphics.drawGraphicsData(myDrawing); } } }
flash.display.IGraphicsDataflash.display.GraphicsBitmapFillflash.display.GraphicsEndFillflash.display.GraphicsGradientFillflash.display.GraphicsPathflash.display.GraphicsShaderFillflash.display.GraphicsSolidFillflash.display.GraphicsStrokeflash.display.GraphicsTrianglePath
drawPath Submits a series of commands for drawing.commandsA Vector of integers representing commands defined by the GraphicsPathCommand class. The GraphicsPathCommand class maps commands to numeric identifiers for this vector array. dataA Vector of Numbers where each pair of numbers is treated as a coordinate location (an x, y pair). The x- and y-coordinate value pairs are not Point objects; the data vector is a series of numbers where each group of two numbers represents a coordinate location. windingStringevenOddSpecifies the winding rule using a value defined in the GraphicsPathWinding class. Submits a series of commands for drawing. The drawPath() method uses vector arrays to consolidate individual moveTo(), lineTo(), and curveTo() drawing commands into a single call. The drawPath() method parameters combine drawing commands with x- and y-coordinate value pairs and a drawing direction. The drawing commands are values from the GraphicsPathCommand class. The x- and y-coordinate value pairs are Numbers in an array where each pair defines a coordinate location. The drawing direction is a value from the GraphicsPathWinding class.

Generally, drawings render faster with drawPath() than with a series of individual lineTo() and curveTo() methods.

The drawPath() method uses a uses a floating computation so rotation and scaling of shapes is more accurate and gives better results. However, curves submitted using the drawPath() method can have small sub-pixel alignment errors when used in conjunction with the lineTo() and curveTo() methods.

The drawPath() method also uses slightly different rules for filling and drawing lines. They are:

  • When a fill is applied to rendering a path:
    • A sub-path of less than 3 points is not rendered. (But note that the stroke rendering will still occur, consistent with the rules for strokes below.)
    • A sub-path that isn't closed (the end point is not equal to the begin point) is implicitly closed.
  • When a stroke is applied to rendering a path:
    • The sub-paths can be composed of any number of points.
    • The sub-path is never implicitly closed.
The following example populates two Vector objects, then passes them to the drawPath() method to render a blue star. The first Vector, star_commands, contains a series of integers representing drawing commands from the flash.display.GraphicsPathCommand class, where the value 1 is a MoveTo() command and the value 2 is a LineTo() command. The second Vector, star_coord, contains 5 sets of x- and y-coordinate pairs. The drawPath() method matches the commands with the positions to draw a star. package{ import flash.display.*; public class DrawPathExample extends Sprite { public function DrawPathExample(){ var star_commands:Vector.<int> = new Vector.<int>(5, true); star_commands[0] = 1; star_commands[1] = 2; star_commands[2] = 2; star_commands[3] = 2; star_commands[4] = 2; var star_coord:Vector.<Number> = new Vector.<Number>(10, true); star_coord[0] = 66; //x star_coord[1] = 10; //y star_coord[2] = 23; star_coord[3] = 127; star_coord[4] = 122; star_coord[5] = 50; star_coord[6] = 10; star_coord[7] = 49; star_coord[8] = 109; star_coord[9] = 127; graphics.beginFill(0x003366); graphics.drawPath(star_commands, star_coord); } } } In the above example, each command and coordinate pair is assigned individually to show their position in the array, but they can be assigned in a single statement. The following example draws the same star by assigning the values for each array in a single push() statement: package{ import flash.display.*; public class DrawPathExample extends Sprite { public function DrawPathExample(){ var star_commands:Vector.<int> = new Vector.<int>(); star_commands.push(1, 2, 2, 2, 2); var star_coord:Vector.<Number> = new Vector.<Number>(); star_coord.push(66,10, 23,127, 122,50, 10,49, 109,127); graphics.beginFill(0x003366); graphics.drawPath(star_commands, star_coord); } } } Note: By default, the drawPath() method uses the even-odd winding type. So, the center of the star is not filled. Specify the non-zero winding type for the third parameter and it fills the center of the star: graphics.drawPath(star_commands, star_coord, GraphicsPathWinding.NON_ZERO);
flash.display.GraphicsPathCommandflash.display.GraphicsPathWinding
drawRect Draws a rectangle.If the width or height parameters are not a number (Number.NaN). ArgumentErrorArgumentErrorxNumberA number indicating the horizontal position relative to the registration point of the parent display object (in pixels). yNumberA number indicating the vertical position relative to the registration point of the parent display object (in pixels). widthNumberThe width of the rectangle (in pixels). heightNumberThe height of the rectangle (in pixels). Draws a round rectangle. Draws a rectangle. Set the line style, fill, or both before you call the drawRect() method, by calling the linestyle(), lineGradientStyle(), beginFill(), beginGradientFill(), or beginBitmapFill() method. The following example shows how you can draw shapes in ActionScript 3.0. Example provided by ActionScriptExamples.com. var movieClip:MovieClip = new MovieClip(); movieClip.graphics.beginFill(0xFF0000); movieClip.graphics.drawRect(0, 0, 100, 80); movieClip.graphics.endFill(); movieClip.x = 10; movieClip.y = 10; addChild(movieClip); lineStyle()lineGradientStyle()beginFill()beginGradientFill()beginBitmapFill()drawRoundRect()drawRoundRect Draws a rounded rectangle.If the width, height, ellipseWidth or ellipseHeight parameters are not a number (Number.NaN). ArgumentErrorArgumentErrorxNumberA number indicating the horizontal position relative to the registration point of the parent display object (in pixels). yNumberA number indicating the vertical position relative to the registration point of the parent display object (in pixels). widthNumberThe width of the round rectangle (in pixels). heightNumberThe height of the round rectangle (in pixels). ellipseWidthNumberThe width of the ellipse used to draw the rounded corners (in pixels). ellipseHeightNumberunknownThe height of the ellipse used to draw the rounded corners (in pixels). Optional; if no value is specified, the default value matches that provided for the ellipseWidth parameter. Draws a round rectangle. Draws a rounded rectangle. Set the line style, fill, or both before you call the drawRoundRect() method, by calling the linestyle(), lineGradientStyle(), beginFill(), beginGradientFill(), or beginBitmapFill() method. Please see the example at the end of this class for an illustration of how to use this method. lineStyle()lineGradientStyle()beginFill()beginGradientFill()beginBitmapFill()drawRect()drawTriangles Renders a set of triangles, typically to distort bitmaps and give them a three-dimensional appearance.verticesA Vector of Numbers where each pair of numbers is treated as a coordinate location (an x, y pair). The vertices parameter is required. indicesnullA Vector of integers or indexes, where every three indexes define a triangle. If the indexes parameter is null then every three vertices (six x,y pairs in the vertices Vector) defines a triangle. Otherwise each index refers to a vertex, which is a pair of numbers in the vertices Vector. For example indexes[1] refers to (vertices[2], vertices[3]). The indexes parameter is optional, but indexes generally reduce the amount of data submitted and the amount of data computed. uvtDatanullA Vector of normalized coordinates used to apply texture mapping. Each coordinate refers to a point on the bitmap used for the fill. You must have one UV or one UVT coordinate per vertex. In UV coordinates, (0,0) is the upper left of the bitmap, and (1,1) is the lower right of the bitmap.

If the length of this vector is twice the length of the vertices vector then normalized coordinates are used without perspective correction.

If the length of this vector is three times the length of the vertices vector then the third coordinate is interpreted as 't' (the distance from the eye to the texture in eye space). This helps the rendering engine correctly apply perspective when mapping textures in three dimensions.

If the uvtData parameter is null, then normal fill rules (and any fill type) apply.

cullingStringnoneSpecifies whether to render triangles that face in a specified direction. This parameter prevents the rendering of triangles that cannot be seen in the current view. This parameter can be set to any value defined by the TriangleCulling class.
Renders a set of triangles, typically to distort bitmaps and give them a three-dimensional appearance. The drawTriangles() method maps either the current fill, or a bitmap fill, to the triangle faces using a set of (u,v) coordinates.

Any type of fill can be used, but if the fill has a transform matrix that transform matrix is ignored.

A uvtData parameter improves texture mapping when a bitmap fill is used.

flash.display.TriangleCullingflash.display.GraphicsTrianglePath
endFill Applies a fill to the lines and curves that were added since the last call to the beginFill(), beginGradientFill(), or beginBitmapFill() method.Applies a fill to the lines and curves. Applies a fill to the lines and curves that were added since the last call to the beginFill(), beginGradientFill(), or beginBitmapFill() method. Flash uses the fill that was specified in the previous call to the beginFill(), beginGradientFill(), or beginBitmapFill() method. If the current drawing position does not equal the previous position specified in a moveTo() method and a fill is defined, the path is closed with a line and then filled. beginFill()beginBitmapFill()beginGradientFill()lineBitmapStyle Specifies a bitmap to use for the line stroke when drawing lines.bitmapflash.display:BitmapDataThe bitmap to use for the line stroke. matrixflash.geom:MatrixnullAn optional transformation matrix as defined by the flash.geom.Matrix class. The matrix can be used to scale or otherwise manipulate the bitmap before applying it to the line style. repeatBooleantrueWhether to repeat the bitmap in a tiled fashion. smoothBooleanfalseWhether smoothing should be applied to the bitmap. Specifies a bitmap to use for the line stroke when drawing lines.

The bitmap line style is used for subsequent calls to Graphics methods such as the lineTo() method or the drawCircle() method. The line style remains in effect until you call the lineStyle() or lineGradientStyle() methods, or the lineBitmapStyle() method again with different parameters.

You can call the lineBitmapStyle() method in the middle of drawing a path to specify different styles for different line segments within a path.

Call the lineStyle() method before you call the lineBitmapStyle() method to enable a stroke, or else the value of the line style is undefined.

Calls to the clear() method set the line style back to undefined.

lineStyle()lineGradientStyle()flash.geom.Matrix
lineGradientStyle Specifies a gradient to use for the stroke when drawing lines.typeStringA value from the GradientType class that specifies which gradient type to use, either GradientType.LINEAR or GradientType.RADIAL. colorsArrayAn array of RGB hex color values to be used in the gradient (for example, red is 0xFF0000, blue is 0x0000FF, and so on). alphasArrayAn array of alpha values for the corresponding colors in the colors array; valid values are 0 to 1. If the value is less than 0, the default is 0. If the value is greater than 1, the default is 1. ratiosArrayAn array of color distribution ratios; valid values are from 0 to 255. This value defines the percentage of the width where the color is sampled at 100%. The value 0 represents the left position in the gradient box, and 255 represents the right position in the gradient box. This value represents positions in the gradient box, not the coordinate space of the final gradient, which can be wider or thinner than the gradient box. Specify a value for each value in the colors parameter.

For example, for a linear gradient that includes two colors, blue and green, the following figure illustrates the placement of the colors in the gradient based on different values in the ratios array:

ratiosGradient[0, 127][0, 255][127, 255]

The values in the array must increase, sequentially; for example, [0, 63, 127, 190, 255].

matrixflash.geom:MatrixnullA transformation matrix as defined by the flash.geom.Matrix class. The flash.geom.Matrix class includes a createGradientBox() method, which lets you conveniently set up the matrix for use with the lineGradientStyle() method. spreadMethodStringpadA value from the SpreadMethod class that specifies which spread method to use:

SpreadMethod.PADSpreadMethod.REFLECTSpreadMethod.REPEAT

interpolationMethodStringrgbA value from the InterpolationMethod class that specifies which value to use. For example, consider a simple linear gradient between two colors (with the spreadMethod parameter set to SpreadMethod.REFLECT). The different interpolation methods affect the appearance as follows:

InterpolationMethod.LINEAR_RGBInterpolationMethod.RGB

focalPointRatioNumber0A number that controls the location of the focal point of the gradient. The value 0 means the focal point is in the center. The value 1 means the focal point is at one border of the gradient circle. The value -1 means that the focal point is at the other border of the gradient circle. Values less than -1 or greater than 1 are rounded to -1 or 1. The following image shows a gradient with a focalPointRatio of -0.75:

Specifies a gradient to use for the stroke when drawing lines.

The gradient line style is used for subsequent calls to Graphics methods such as the lineTo() methods or the drawCircle() method. The line style remains in effect until you call the lineStyle() or lineBitmapStyle() methods, or the lineGradientStyle() method again with different parameters.

You can call the lineGradientStyle() method in the middle of drawing a path to specify different styles for different line segments within a path.

Call the lineStyle() method before you call the lineGradientStyle() method to enable a stroke, or else the value of the line style is undefined.

Calls to the clear() method set the line style back to undefined.

The following example draws a rectangle and a circle that use a gradient stroke from red to green to blue.

The method createGradientBox() from the Matrix class is used to define the gradient box to 200 width and 40 height. The thickness of line is set to 5 pixels. Thickness of the stroke must be defined for lineGradientStyle() method. The gradient is set to linear. Colors for the gradient are set to red, green, and blue. Transparency (alpha value) for the colors is set to 1 (opaque). The distribution of gradient is even, where the colors are sampled at 100% at 0 (left-hand position in the gradient box), 128 (middle in the box) and 255 (right-hand position in the box). The width of the rectangle encompasses all the spectrum of the gradient, while the circle encompasses 50% from the middle of the spectrum.

package { import flash.display.Sprite; import flash.display.Shape; import flash.geom.Matrix; import flash.display.GradientType; public class Graphics_lineGradientStyleExample extends Sprite { public function Graphics_lineGradientStyleExample() { var myShape:Shape = new Shape(); var gradientBoxMatrix:Matrix = new Matrix(); gradientBoxMatrix.createGradientBox(200, 40, 0, 0, 0); myShape.graphics.lineStyle(5); myShape.graphics.lineGradientStyle(GradientType.LINEAR, [0xFF0000, 0x00FF00, 0x0000FF], [1, 1, 1], [0, 128, 255], gradientBoxMatrix); myShape.graphics.drawRect(0, 0, 200, 40); myShape.graphics.drawCircle(100, 120, 50); this.addChild(myShape); } } }
lineStyle()lineBitmapStyle()flash.geom.Matrix.createGradientBox()flash.display.GradientTypeflash.display.SpreadMethod
lineShaderStyle Specifies a shader to use for the line stroke when drawing lines.shaderflash.display:ShaderThe shader to use for the line stroke. matrixflash.geom:MatrixnullAn optional transformation matrix as defined by the flash.geom.Matrix class. The matrix can be used to scale or otherwise manipulate the bitmap before applying it to the line style. Specifies a shader to use for the line stroke when drawing lines.

The shader line style is used for subsequent calls to Graphics methods such as the lineTo() method or the drawCircle() method. The line style remains in effect until you call the lineStyle() or lineGradientStyle() methods, or the lineBitmapStyle() method again with different parameters.

You can call the lineShaderStyle() method in the middle of drawing a path to specify different styles for different line segments within a path.

Call the lineStyle() method before you call the lineShaderStyle() method to enable a stroke, or else the value of the line style is undefined.

Calls to the clear() method set the line style back to undefined.

lineStyle()lineBitmapStyle()flash.geom.Matrix
lineStyle Specifies a line style used for subsequent calls to Graphics methods such as the lineTo() method or the drawCircle() method.thicknessNumberunknownAn integer that indicates the thickness of the line in points; valid values are 0-255. If a number is not specified, or if the parameter is undefined, a line is not drawn. If a value of less than 0 is passed, the default is 0. The value 0 indicates hairline thickness; the maximum thickness is 255. If a value greater than 255 is passed, the default is 255. coloruint0A hexadecimal color value of the line; for example, red is 0xFF0000, blue is 0x0000FF, and so on. If a value is not indicated, the default is 0x000000 (black). Optional. alphaNumber1.0A number that indicates the alpha value of the color of the line; valid values are 0 to 1. If a value is not indicated, the default is 1 (solid). If the value is less than 0, the default is 0. If the value is greater than 1, the default is 1. pixelHintingBooleanfalse(Not supported in Flash Lite 4) A Boolean value that specifies whether to hint strokes to full pixels. This affects both the position of anchors of a curve and the line stroke size itself. With pixelHinting set to true, line widths are adjusted to full pixel widths. With pixelHinting set to false, disjoints can appear for curves and straight lines. For example, the following illustrations show how Flash Player or Adobe AIR renders two rounded rectangles that are identical, except that the pixelHinting parameter used in the lineStyle() method is set differently (the images are scaled by 200%, to emphasize the difference):

If a value is not supplied, the line does not use pixel hinting.

scaleModeStringnormal(Not supported in Flash Lite 4) A value from the LineScaleMode class that specifies which scale mode to use:
  • LineScaleMode.NORMAL—Always scale the line thickness when the object is scaled (the default).
  • LineScaleMode.NONE—Never scale the line thickness.
  • LineScaleMode.VERTICAL—Do not scale the line thickness if the object is scaled vertically only. For example, consider the following circles, drawn with a one-pixel line, and each with the scaleMode parameter set to LineScaleMode.VERTICAL. The circle on the left is scaled vertically only, and the circle on the right is scaled both vertically and horizontally:

  • LineScaleMode.HORIZONTAL—Do not scale the line thickness if the object is scaled horizontally only. For example, consider the following circles, drawn with a one-pixel line, and each with the scaleMode parameter set to LineScaleMode.HORIZONTAL. The circle on the left is scaled horizontally only, and the circle on the right is scaled both vertically and horizontally:

capsStringnull(Not supported in Flash Lite 4) A value from the CapsStyle class that specifies the type of caps at the end of lines. Valid values are: CapsStyle.NONE, CapsStyle.ROUND, and CapsStyle.SQUARE. If a value is not indicated, Flash uses round caps.

For example, the following illustrations show the different capsStyle settings. For each setting, the illustration shows a blue line with a thickness of 30 (for which the capsStyle applies), and a superimposed black line with a thickness of 1 (for which no capsStyle applies):

jointsStringnull(Not supported in Flash Lite 4) A value from the JointStyle class that specifies the type of joint appearance used at angles. Valid values are: JointStyle.BEVEL, JointStyle.MITER, and JointStyle.ROUND. If a value is not indicated, Flash uses round joints.

For example, the following illustrations show the different joints settings. For each setting, the illustration shows an angled blue line with a thickness of 30 (for which the jointStyle applies), and a superimposed angled black line with a thickness of 1 (for which no jointStyle applies):

Note: For joints set to JointStyle.MITER, you can use the miterLimit parameter to limit the length of the miter.

miterLimitNumber3(Not supported in Flash Lite 4) A number that indicates the limit at which a miter is cut off. Valid values range from 1 to 255 (and values outside that range are rounded to 1 or 255). This value is only used if the jointStyle is set to "miter". The miterLimit value represents the length that a miter can extend beyond the point at which the lines meet to form a joint. The value expresses a factor of the line thickness. For example, with a miterLimit factor of 2.5 and a thickness of 10 pixels, the miter is cut off at 25 pixels.

For example, consider the following angled lines, each drawn with a thickness of 20, but with miterLimit set to 1, 2, and 4. Superimposed are black reference lines showing the meeting points of the joints:

Notice that a given miterLimit value has a specific maximum angle for which the miter is cut off. The following table lists some examples:

miterLimit value:Angles smaller than this are cut off:1.41490 degrees260 degrees430 degrees815 degrees
Specifies a line style that Flash uses for drawing lines.
Specifies a line style used for subsequent calls to Graphics methods such as the lineTo() method or the drawCircle() method. The line style remains in effect until you call the lineGradientStyle() method, the lineBitmapStyle() method, or the lineStyle() method with different parameters.

You can call the lineStyle() method in the middle of drawing a path to specify different styles for different line segments within the path.

Note: Calls to the clear() method set the line style back to undefined.

Note: Flash Lite 4 supports only the first three parameters (thickness, color, and alpha).

Please see the lineTo() or moveTo() method's example for illustrations of how to use the getStyle() method.
lineBitmapStyle()lineGradientStyle()LineScaleModeCapsStyleJointStyle
lineTo Draws a line using the current line style from the current drawing position to (x, y); the current drawing position is then set to (x, y).xNumberA number that indicates the horizontal position relative to the registration point of the parent display object (in pixels). yNumberA number that indicates the vertical position relative to the registration point of the parent display object (in pixels). Draws a line from the current drawing position to (x, y). Draws a line using the current line style from the current drawing position to (x, y); the current drawing position is then set to (x, y). If the display object in which you are drawing contains content that was created with the Flash drawing tools, calls to the lineTo() method are drawn underneath the content. If you call lineTo() before any calls to the moveTo() method, the default position for the current drawing is (0, 0). If any of the parameters are missing, this method fails and the current drawing position is not changed. The following example draws a trapezoid using lineTo() method, starting at pixels (100, 100).

The line thickness is set to 10 pixels, color is gold and opaque, caps at the end of lines is set to none (since all lines are jointed), and the joint between the lines is set to MITER with miter limit set to 10, to have sharp, pointed corners.

package { import flash.display.Sprite; import flash.display.LineScaleMode; import flash.display.CapsStyle; import flash.display.JointStyle; import flash.display.Shape; public class Graphics_lineToExample extends Sprite { public function Graphics_lineToExample() { var trapezoid:Shape = new Shape(); trapezoid.graphics.lineStyle(10, 0xFFD700, 1, false, LineScaleMode.VERTICAL, CapsStyle.NONE, JointStyle.MITER, 10); trapezoid.graphics.moveTo(100, 100); trapezoid.graphics.lineTo(120, 50); trapezoid.graphics.lineTo(200, 50); trapezoid.graphics.lineTo(220, 100); trapezoid.graphics.lineTo(100, 100); this.addChild(trapezoid); } } }
moveTo Moves the current drawing position to (x, y).xNumberA number that indicates the horizontal position relative to the registration point of the parent display object (in pixels). yNumberA number that indicates the vertical position relative to the registration point of the parent display object (in pixels). Moves the current drawing position to (x, y). Moves the current drawing position to (x, y). If any of the parameters are missing, this method fails and the current drawing position is not changed. The following example draws a dashed line of three pixels thickness using moveTo() and lineTo() methods.

Using the lineStyle() method, the line thickness is set to 3 pixels. It is also set not to scale. Color is set to red with 25 percent opacity. The CapsStyle property is set to square (the default is round).

Since Graphics_moveToExample is an instance of the Sprite class, it has access to all the Graphics class methods. The Graphics class methods can be used to directly draw on the Graphic_moveToExample Sprite object. However, not putting the vector drawing object in a Shape limits the way they can be managed, moved, or changed.

package { import flash.display.Sprite; import flash.display.CapsStyle; import flash.display.LineScaleMode; public class Graphics_moveToExample extends Sprite { public function Graphics_moveToExample() { graphics.lineStyle(3, 0x990000, 0.25, false, LineScaleMode.NONE, CapsStyle.SQUARE); graphics.moveTo(10, 20); graphics.lineTo(20, 20); graphics.moveTo(30, 20); graphics.lineTo(50, 20); graphics.moveTo(60, 20); graphics.lineTo(80, 20); graphics.moveTo(90, 20); graphics.lineTo(110, 20); graphics.moveTo(120, 20); graphics.lineTo(130, 20); } } }
NativeWindowType The NativeWindowType class defines constants for the type property of the NativeWindowInitOptions object used to create a native window.Defines constants for the supported window types. Object The NativeWindowType class defines constants for the type property of the NativeWindowInitOptions object used to create a native window.

Note: The type value is specified when a window is created and cannot be changed.

flash.display.NativeWindowflash.display.NativeWindowInitOptionsLIGHTWEIGHT A minimal window.lightweightString A minimal window. NORMAL A typical window.normalString A typical window. UTILITY A utility window.utilityString A utility window.
StageAspectRatio The StageAspectRatio class provides values for the Stage.setAspectRatio() method.Object The StageAspectRatio class provides values for the Stage.setAspectRatio() method. flash.display.Stage.setAspectRatio()LANDSCAPE Specifies a device orientation that presents a landscape UI landscapeString Specifies a device orientation that presents a landscape UI PORTRAIT Specifies a device orientation that presents a portrait UI portraitString Specifies a device orientation that presents a portrait UI Screen The Screen class provides information about the display screens available to this application.flash.events:EventDispatcher The Screen class provides information about the display screens available to this application.

Screens are independent desktop areas within a possibly larger "virtual desktop." The origin of the virtual desktop is the top-left corner of the operating-system-designated main screen. Thus, the coordinates for the bounds of an individual display screen may be negative. There may also be areas of the virtual desktop that are not within any of the display screens.

The Screen class includes static class members for accessing the available screen objects and instance members for accessing the properties of an individual screen. Screen information should not be cached since it can be changed by a user at any time.

Note that there is not necessarily a one-to-one correspondance between screens and the physical monitors attached to a computer. For example, two monitors may display the same screen.

You cannot instantiate the Screen class directly. Calls to the new Screen() constructor throw an ArgumentError exception.

The following example defines a DockingWindow class to create a window that docks to the sides of the screen. This task is accomplished by performing the following steps:
  1. Responding to keyboard events to determine the side of the screen on which to dock.
  2. Accessing the static Screen class method getScreensForRectangle() to get the Screen object for the screen upon which the window is currently displayed.
  3. Resetting the window bounds based on the screen dimensions.
  4. Redrawing the window content based on the new window dimensions.

Note, this class is intended to be used as the root class of an AIR application with the settings SystemChrome="none" and transparent="true". To use this class in a window with system chrome, you must take the chrome thickness and the minimum width of the window into account when calculating window location and size.

package { import flash.display.Screen; import flash.display.Sprite; import flash.display.StageAlign; import flash.display.StageScaleMode; import flash.events.KeyboardEvent; import flash.geom.Rectangle; import flash.ui.Keyboard; public class DockingWindow extends Sprite { private const dockedWidth:uint = 80; private const dockedHeight:uint = 80; public function DockingWindow():void{ stage.align = StageAlign.TOP_LEFT; stage.scaleMode = StageScaleMode.NO_SCALE; stage.addEventListener(KeyboardEvent.KEY_DOWN,onKey); dockLeft(); } private function onKey(event:KeyboardEvent):void{ switch(event.keyCode){ case Keyboard.LEFT : dockLeft(); break; case Keyboard.RIGHT : dockRight(); break; case Keyboard.UP : dockTop(); break; case Keyboard.DOWN : dockBottom(); break; case Keyboard.SPACE : stage.nativeWindow.close(); } } public function dockLeft():void{ var screen:Screen = getCurrentScreen(); stage.nativeWindow.x = screen.visibleBounds.left; stage.nativeWindow.y = screen.visibleBounds.top; stage.nativeWindow.height = screen.visibleBounds.height; stage.stageWidth = dockedWidth; drawContent(); } public function dockRight():void{ var screen:Screen = getCurrentScreen(); stage.nativeWindow.x = screen.visibleBounds.width - dockedWidth; stage.nativeWindow.y = screen.visibleBounds.top; stage.stageWidth = dockedWidth; stage.nativeWindow.height = screen.visibleBounds.height; drawContent(); } public function dockTop():void{ var screen:Screen = getCurrentScreen(); stage.nativeWindow.x = screen.visibleBounds.left; stage.nativeWindow.y = screen.visibleBounds.top; stage.nativeWindow.width = screen.visibleBounds.width; stage.stageHeight = dockedHeight; drawContent(); } public function dockBottom():void{ var screen:Screen = getCurrentScreen(); stage.nativeWindow.x = screen.visibleBounds.left; stage.nativeWindow.y = screen.visibleBounds.height - dockedHeight; stage.nativeWindow.width = screen.visibleBounds.width; stage.stageHeight = dockedHeight; drawContent(); } private function getCurrentScreen():Screen{ return Screen.getScreensForRectangle(stage.nativeWindow.bounds)[0]; } private function drawContent():void{ const size:int = 60; const pad:int = 10; var numHSquares:int = Math.floor(stage.stageWidth/(size + pad)); var numVSquares:int = Math.floor(stage.stageHeight/(size + pad)); with (graphics){ clear(); lineStyle(1); beginFill(0x3462d5,.7); for(var i:int = 0; i < numHSquares; i++){ for(var j:int = 0; j < numVSquares; j++){ drawRect((i * (size + pad)) + pad, (j * (size + pad)) + pad, size, size); } } endFill(); } } } }
getScreensForRectangle Returns the (possibly empty) set of screens that intersect the provided rectangle.An array of Screen objects containing the screens that contain any part of the area defined by the rect parameter. Arrayrectflash.geom:RectangleA rectangle with coordinates relative to the origin of the virtual desktop, which is the top-left corner of the primary screen. Returns the (possibly empty) set of screens that intersect the provided rectangle. The following example shows how to get the array of screens containing at least part of a given rectangle: import flash.display.Screen; import flash.geom.Rectangle; var rect:Rectangle = new Rectangle(-200, 100, 1000, 600); var intersectedScreens:Array = Screen.getScreensForRectangle(rect); bounds The bounds of this screen.flash.geom:Rectangle The bounds of this screen.

The screen location is relative to the virtual desktop.

On Linux systems that use certain window managers, this property returns the desktop bounds, not the screen's visible bounds.

The following example shows how to get the bounds of a screen (in this case, the primary display screen): import flash.display.Screen; import flash.geom.Rectangle; var mainScreen:Screen = Screen.mainScreen; var screenBounds:Rectangle = mainScreen.bounds;
colorDepth The color depth of this screen (expressed in number of bits).int The color depth of this screen (expressed in number of bits). The following example shows how to get the color depth of a screen (in this case, the primary display screen): var mainScreen:Screen = Screen.mainScreen; var colors:uint = mainScreen.colorDepth; mainScreen The primary display.flash.display:Screen The primary display. The following example shows how to get the Screen object representing the "main" screen of this computer: var primaryScreen:Screen = Screen.mainScreen; screens The array of the currently available screens.Array The array of the currently available screens.

Modifying the returned array has no effect on the available screens.

The following example shows how to get the array containing the available screens: var screenArray:Array = Screen.screens;
visibleBounds The bounds of the area on this screen in which windows can be visible.flash.geom:Rectangle The bounds of the area on this screen in which windows can be visible.

The visibleBounds of a screen excludes the task bar (and other docked desk bars) on Windows, and excludes the menu bar and, depending on system settings, the dock on Mac OS X. On some Linux configurations, it is not possible to determine the visible bounds. In these cases, the visibleBounds property returns the same value as the screenBounds property.

The following example shows how to get the usable bounds of a screen (in this case, the primary display screen): import flash.display.Screen; import flash.geom.Rectangle; var mainScreen:Screen = Screen.mainScreen; var screenBounds:Rectangle = mainScreen.visibleBounds;
NativeWindowDisplayState The NativeWindowDisplayState class defines constants for the names of the window display states.Object The NativeWindowDisplayState class defines constants for the names of the window display states.

Note: The fullscreen modes are set using the Stage object displayState property, not the window displaySate.

flash.display.Stage.displayStateflash.display.StageDisplayStateMAXIMIZED The maximized display state.maximizedString The maximized display state. MINIMIZED The minimized display state.minimizedString The minimized display state. NORMAL The normal display state.normalString The normal display state.
Bitmap The Bitmap class represents display objects that represent bitmap images.Represents display objects that derive from images. flash.display:DisplayObject The Bitmap class represents display objects that represent bitmap images. These can be images that you load with the flash.display.Loader class, or they can be images that you create with the Bitmap() constructor.

The Bitmap() constructor allows you to create a Bitmap object that contains a reference to a BitmapData object. After you create a Bitmap object, use the addChild() or addChildAt() method of the parent DisplayObjectContainer instance to place the bitmap on the display list.

A Bitmap object can share its BitmapData reference among several Bitmap objects, independent of translation or rotation properties. Because you can create multiple Bitmap objects that reference the same BitmapData object, multiple display objects can use the same complex BitmapData object without incurring the memory overhead of a BitmapData object for each display object instance.

A BitmapData object can be drawn to the screen by a Bitmap object in one of two ways: by using the vector renderer as a fill-bitmap shape, or by using a faster pixel-copying routine. The pixel-copying routine is substantially faster than the vector renderer, but the Bitmap object must meet certain conditions to use it:

  • No stretching, rotation, or skewing can be applied to the Bitmap object.
  • No color transform can be applied to the Bitmap object.
  • No blend mode can be applied to the Bitmap object.
  • No clipping can be done through mask layers or setMask() methods.
  • The image itself cannot be a mask.
  • The destination coordinates must be on a whole pixel boundary.

If you load a Bitmap object from a domain other than that of the Loader object used to load the image, and there is no URL policy file that permits access to the domain of the Loader object, then a script in that domain cannot access the Bitmap object or its properties and methods. For more information, see the Flash Player Developer Center Topic: Security.

Note: The Bitmap class is not a subclass of the InteractiveObject class, so it cannot dispatch mouse events. However, you can use the addEventListener() method of the display object container that contains the Bitmap object.

The following example uses the BitmapExample class to load the "Image.gif" image into a DisplayObject in the default location (x = 0, y = 0). A copy of Image.gif is then placed to the right of the original, which has new colors applied to pixels that pass a test using the threshold() method. This task is accomplished using the following steps:
  1. A property url is created, which is the location and name of the image file
  2. The class constructor calls the configureAssets() method, which, in turn, calls the completeHandler() method.
  3. configureAssets() creates a Loader object, which then instantiates an event listener, which is dispatched when completeHandler() completes the image manipulation.
  4. Next, the buildChild() method creates a new instance of a URLRequest object, request, with url passed so the file name and location are known.
  5. The request object is passed to the loader.load() method, which loads the image into memory via a display object.
  6. The image is then placed on the display list, which promptly displays the image on screen at coordinates x = 0, y = 0.
  7. The completeHandler() method then performs the following tasks:
    1. Creates a second Loader object, along with a Bitmap object, which is initialized with the Loader object.
    2. Creates a second Bitmap object, duplicate, which in turn calls the duplicateImage() method, which creates a duplicate of the original image.
    3. Creates a BitmapData object, which is assigned to the duplicate object's BitmapData object.
    4. Creates a new Rectangle object initialized with the same coordinates, width, and height as the original image.
    5. Creates a new Point object, which defaults to x = 0, y = 0.
    6. Creates the following variables:
      • operation: applies the new color when the threshold value is >= the original.
      • threshold: the value against which each pixel is compared is set to light gray with an alpha of 0xCC.
      • color: the color that the pixels will be set to that pass the threshold test, which is solid yellow in this case.
      • mask: set to the exact opposite of color, (transparent blue).
      • copySource: set to false, indicating that the pixel values are not copied in the event the threshold value does not pass. This value has no meaning because the image is duplicated and only pixels that pass the threshold test are changed.
    7. Calls the threshold() method by using the preceding variables. The resulting threshold equation is as follows: if (current pixel Value & 0x000000FF) >= (0xCCCCCCCC & 0x000000FF) then set pixel to 0xFFFFFF00.

Notes:

  • You will need to compile the SWF file with "Local playback security" set to "Access local files only".
  • This example requires that a file named Image.gif be placed in the same directory as your SWF file.
  • It is recommended that you use an image up to 80 pixels wide.

package { import flash.display.Bitmap; import flash.display.BitmapData; import flash.display.Loader; import flash.display.Sprite; import flash.events.*; import flash.geom.Point; import flash.geom.Rectangle; import flash.net.URLRequest; public class BitmapExample extends Sprite { private var url:String = "Image.gif"; private var size:uint = 80; public function BitmapExample() { configureAssets(); } private function configureAssets():void { var loader:Loader = new Loader(); loader.contentLoaderInfo.addEventListener(Event.COMPLETE, completeHandler); loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler); var request:URLRequest = new URLRequest(url); loader.x = size * numChildren; loader.load(request); addChild(loader); } private function duplicateImage(original:Bitmap):Bitmap { var image:Bitmap = new Bitmap(original.bitmapData.clone()); image.x = size * numChildren; addChild(image); return image; } private function completeHandler(event:Event):void { var loader:Loader = Loader(event.target.loader); var image:Bitmap = Bitmap(loader.content); var duplicate:Bitmap = duplicateImage(image); var bitmapData:BitmapData = duplicate.bitmapData; var sourceRect:Rectangle = new Rectangle(0, 0, bitmapData.width, bitmapData.height); var destPoint:Point = new Point(); var operation:String = ">="; var threshold:uint = 0xCCCCCCCC; var color:uint = 0xFFFFFF00; var mask:uint = 0x000000FF; var copySource:Boolean = true; bitmapData.threshold(bitmapData, sourceRect, destPoint, operation, threshold, color, mask, copySource); } private function ioErrorHandler(event:IOErrorEvent):void { trace("Unable to load image: " + url); } } }
flash.display.Loaderflash.display.BitmapDataBitmap Initializes a Bitmap object to refer to the specified BitmapData object.bitmapDataflash.display:BitmapDatanullThe BitmapData object being referenced. pixelSnappingStringautoWhether or not the Bitmap object is snapped to the nearest pixel. smoothingBooleanfalseWhether or not the bitmap is smoothed when scaled. For example, the following examples show the same bitmap scaled by a factor of 3, with smoothing set to false (left) and true (right):

Initializes a Bitmap object to refer to the specified BitmapData object. The following example shows how you can dynamically load an image at runtime using the ActionScript 3.0 Loader class and then copy the image's pixels into four separate Bitmap object instances on the display list by using the Loader instance's content property and bitmapData properties. Example provided by ActionScriptExamples.com. const IMAGE_URL:String = "http://www.helpexamples.com/flash/images/logo.png"; var ldr:Loader = new Loader(); ldr.contentLoaderInfo.addEventListener(Event.COMPLETE, ldr_complete); ldr.load(new URLRequest(IMAGE_URL)); var bitmap1:Bitmap; var bitmap2:Bitmap; var bitmap3:Bitmap; var bitmap4:Bitmap; function ldr_complete(evt:Event):void { var bmp:Bitmap = ldr.content as Bitmap; bitmap1 = new Bitmap(bmp.bitmapData); bitmap1.x = 100; bitmap1.y = 100; bitmap1.rotation = 0; addChild(bitmap1); bitmap2 = new Bitmap(bmp.bitmapData); bitmap2.x = 200; bitmap2.y = 100; bitmap2.rotation = 90; addChild(bitmap2); bitmap3 = new Bitmap(bmp.bitmapData); bitmap3.x = 300; bitmap3.y = 100; bitmap3.rotation = 180; addChild(bitmap3); bitmap4 = new Bitmap(bmp.bitmapData); bitmap4.x = 400; bitmap4.y = 100; bitmap4.rotation = 270; addChild(bitmap4); }
bitmapData The BitmapData object being referenced.flash.display:BitmapData The BitmapData object being referenced. pixelSnapping Controls whether or not the Bitmap object is snapped to the nearest pixel.String Controls whether or not the Bitmap object is snapped to the nearest pixel. The PixelSnapping class includes possible values:
  • PixelSnapping.NEVER—No pixel snapping occurs.
  • PixelSnapping.ALWAYS—The image is always snapped to the nearest pixel, independent of transformation.
  • PixelSnapping.AUTO—The image is snapped to the nearest pixel if it is drawn with no rotation or skew and it is drawn at a scale factor of 99.9% to 100.1%. If these conditions are satisfied, the bitmap image is drawn at 100% scale, snapped to the nearest pixel. Internally, this value allows the image to be drawn as fast as possible using the vector renderer.
smoothing Controls whether or not the bitmap is smoothed when scaled.Boolean Controls whether or not the bitmap is smoothed when scaled. If true, the bitmap is smoothed when scaled. If false, the bitmap is not smoothed when scaled.
Scene The Scene class includes properties for identifying the name, labels, and number of frames in a scene.Object The Scene class includes properties for identifying the name, labels, and number of frames in a scene. A Scene object instance is created in Flash Professional, not by writing ActionScript code. The MovieClip class includes a currentScene property, which is a Scene object that identifies the scene in which the playhead is located in the timeline of the MovieClip instance. The scenes property of the MovieClip class is an array of Scene objects. Also, the gotoAndPlay() and gotoAndStop() methods of the MovieClip class use Scene objects as parameters. MovieClip.currentSceneMovieClip.scenesMovieClip.gotoAndPlay()MovieClip.gotoAndStop()labels An array of FrameLabel objects for the scene.Array An array of FrameLabel objects for the scene. Each FrameLabel object contains a frame property, which specifies the frame number corresponding to the label, and a name property. FrameLabelname The name of the scene.String The name of the scene. numFrames The number of frames in the scene.int The number of frames in the scene. StageDisplayState The StageDisplayState class provides values for the Stage.displayState property.Object The StageDisplayState class provides values for the Stage.displayState property. flash.display.Stage.displayStateFULL_SCREEN_INTERACTIVE Specifies that the Stage is in full-screen mode with keyboard interactivity enabled.fullScreenInteractiveString Specifies that the Stage is in full-screen mode with keyboard interactivity enabled. Only AIR applications support this capability. FULL_SCREEN Specifies that the Stage is in full-screen mode.fullScreenString Specifies that the Stage is in full-screen mode. Keyboard interactivity is disabled in this mode. NORMAL Specifies that the Stage is in normal mode.normalString Specifies that the Stage is in normal mode. ShaderData A ShaderData object contains properties representing any parameters and inputs for a shader kernel, as well as properties containing any metadata specified for the shader.Object A ShaderData object contains properties representing any parameters and inputs for a shader kernel, as well as properties containing any metadata specified for the shader.

These properties are added to the ShaderData object when it is created. The properties' names match the names specified in the shader's source code. The data type of each property varies according to what aspect of the shader the property represents. The properties that represent shader parameters are ShaderParameter instances, the properties that represent input images are ShaderInput instances, and the properties that represent shader metadata are instances of the ActionScript class corresponding to their data type (for example, a String instance for textual metadata and a uint for uint metadata).

For example, consider this shader, which is defined with one input image (src), two parameters (size and radius), and three metadata values (nameSpace, version, and description):

<languageVersion : 1.0;> kernel DoNothing < namespace: "Adobe::Example"; vendor: "Adobe examples"; version: 1; description: "A shader that does nothing, but does it well."; > { input image4 src; output pixel4 dst; parameter float2 size < description: "The size of the image to which the kernel is applied"; minValue: float2(0.0, 0.0); maxValue: float2(100.0, 100.0); defaultValue: float2(50.0, 50.0); >; parameter float radius < description: "The radius of the effect"; minValue: 0.0; maxValue: 50.0; defaultValue: 25.0; >; void evaluatePixel() { float2 one = (radius / radius) ∗ (size / size); dst = sampleNearest(src, outCoord()); } }

If you create a Shader instance by loading the byte code for this shader, the ShaderData instance in its data property contains these properties:

PropertyData typeValuenameString"DoNothing"nameSpaceString"Adobe::Example"versionString"1"descriptionString"A shader that does nothing, but does it well."srcShaderInput[A ShaderInput instance]sizeShaderParameter[A ShaderParameter instance, with properties for the parameter metadata]radiusShaderParameter[A ShaderParameter instance, with properties for the parameter metadata]

Note that any input image or parameter that is defined in the shader source code but not used in the shader's evaluatePixel() function is removed when the shader is compiled to byte code. In that case, there is no corresponding ShaderInput or ShaderParameter instance added as a property of the ShaderData instance.

Generally, developer code does not create a ShaderData instance. A ShaderData instance containing data, parameters, and inputs for a shader is available as the Shader instance's data property.

The following example loads a shader and enumerates the ShaderData instance in its data property to display the input, parameters, and metadata properties of the shader.

Note that this example assumes there's a shader bytecode file named "donothing.pbj" in the same directory as the output directory for the application.

// // Source code for the shader: // <languageVersion : 1.0;> kernel DoNothing < namespace: "Adobe::Example"; vendor: "Adobe examples"; version: 1; description: "A shader that does nothing, but does it well."; > { input image4 src; output pixel4 dst; parameter float2 size < description: "The size of the image to which the shader is applied"; minValue: float2(0.0, 0.0); maxValue: float2(100.0, 100.0); defaultValue: float2(50.0, 50.0); >; parameter float radius < description: "The radius of the effect"; minValue: float(0.0); maxValue: float(50.0); defaultValue: float(25.0); >; void evaluatePixel() { float2 one = (radius / radius) * (size / size); dst = sampleNearest(src, outCoord()); } } // // ActionScript source code: // package { import flash.display.Shader; import flash.display.Sprite; import flash.events.Event; import flash.net.URLLoader; import flash.net.URLLoaderDataFormat; import flash.net.URLRequest; public class ShaderDataExample extends Sprite { private var loader:URLLoader; public function ShaderDataExample() { loader = new URLLoader(); loader.dataFormat = URLLoaderDataFormat.BINARY; loader.addEventListener(Event.COMPLETE, loadCompleteHandler); loader.load(new URLRequest("donothing.pbj")); } private function loadCompleteHandler(event:Event):void { var shader:Shader = new Shader(); shader.byteCode = loader.data; for (var p:String in shader.data) { trace(p, ":", shader.data[p]); for (var d:String in shader.data[p]) { trace("\t", d, ":", shader.data[p][d]); } } } } }
flash.display.Shader.dataflash.display.ShaderInputflash.display.ShaderParameterShaderData Creates a ShaderData instance.byteCodeflash.utils:ByteArrayThe shader's byte code. Creates a ShaderData instance. Generally, developer code does not call the ShaderData constructor directly. A ShaderData instance containing data, parameters, and inputs for a Shader instance is accessed using its data property. flash.display.Shader.data
ShaderJob A ShaderJob instance is used to execute a shader operation in stand-alone mode.flash.events:EventDispatcher A ShaderJob instance is used to execute a shader operation in stand-alone mode. The shader operation executes and returns its result data. It is up to the developer to determine how to use the result.

There are two primary reasons for using a shader in stand-alone mode:

  • Processing non-image data: Using a ShaderJob instance you have control over input values and over how the shader result is used. The shader can return the result as binary data or number data instead of image data.
  • Background processing: Some shaders are complex and require a notable amount of time to execute. Executing a complex shader in the main execution of an application could slow down other parts of the application such as user interaction or updating the screen. Using a ShaderJob instance, you can execute the shader in the background. When the shader is executed in this way, the shader operation runs separate from the main execution of the application.

The shader property (or constructor parameter) specifies the Shader instance representing the shader that is used for the operation. You provide any parameter or input that the shader expects using the associated ShaderParameter or ShaderInput instance.

Before execution a ShaderJob operation, you provide an object into which the result is written, by setting it as the value of the target property. When the shader operation completes the result is written into the target object.

To begin a background shader operation, call the start() method. When the operation finishes the result is written into the target object. At that point the ShaderJob instance dispatches a complete event, notifying listeners that the result is available.

To execute a shader synchronously (that is, not running in the background), call the start() method and pass true as an argument. The shader runs in the main execution thread and your code pauses until the operation completes. When it finishes the result is written into the target object. At that point the application continues running at the next line of code.

ShaderShaderInputShaderParameterShaderEventcomplete Dispatched when a ShaderJob that executes asynchronously finishes processing the data using the shader.flash.events.ShaderEvent.COMPLETEflash.events.ShaderEvent Dispatched when a ShaderJob that executes asynchronously finishes processing the data using the shader. A ShaderJob instance executes asynchronously when the start() method is called with a false value for the waitForCompletion parameter. ShaderJob shaderflash.display:ShadernullThe shader to use for the operation. targetObjectnullThe object into which the result of the shader operation is written. This argument must be a BitmapData, ByteArray, or Vector.<Number> instance. widthint0The width of the result data in the target if it is a ByteArray or Vector.<Number> instance. The size of the ByteArray or Vector.<Number> instance is enlarged if necessary and existing data is overwritten. heightint0The height of the result data in the target if it is a ByteArray or Vector.<Number> instance. The size of the ByteArray or Vector.<Number> instance is enlarged if necessary and existing data is overwritten. cancel Cancels the currently running shader operation. Cancels the currently running shader operation. Any result data that is already computed is discarded. The complete event is not dispatched.

Calling cancel() multiple times has no additional effect.

start Starts a shader operation in synchronous or asynchronous mode, according to the value of the waitForCompletion parameter.When the target property is null or is not a BitmapData, ByteArray, or Vector.<Number> instance. ArgumentErrorArgumentErrorWhen the shader specifies an image input that isn't provided. ArgumentErrorArgumentErrorWhen a ByteArray or Vector.<Number> instance is used as an input and the width and height properties aren't specified for the ShaderInput, or the specified values don't match the amount of data in the input object. See the ShaderInput.input property for more information. ArgumentErrorArgumentErrorwaitForCompletionBooleanfalseSpecifies whether to execute the shader in the background (false, the default) or in the main program execution (true). Starts a shader operation in synchronous or asynchronous mode, according to the value of the waitForCompletion parameter.

In asynchronous mode (when waitForCompletion is false), which is the default, the ShaderJob execution runs in the background. The shader operation does not affect the responsiveness of the display or other operations. In asynchronous mode the start() call returns immediately and the program continues with the next line of code. When the asynchronous shader operation finishes, the result is available and the complete event is dispatched.

Only one background ShaderJob operation executes at a time. Shader operations are held in a queue until they execute. If you call the start() method while a shader operation is executing, the additional operation is added to the end of the queue. Later, when its turn comes, it executes.

To execute a shader operation in synchronous mode, call start() with a true value for the waitForCompletion parameter (the only parameter). Your code pauses at the point where start() is called until the shader operation completes. At that point the result is available and execution continues with the next line of code.

When you call the start() method the Shader instance in the shader property is copied internally. The shader operation uses that internal copy, not a reference to the original shader. Any changes made to the shader, such as changing a parameter value, input, or bytecode, are not applied to the copied shader that's used for the shader processing. To incorporate shader changes into the shader processing, call the cancel() method (if necessary) and call the start() method again to restart the shader processing.

While a shader operation is executing, the target object's value is not changed. When the operation finishes (and the complete event is dispatched in asynchronous mode) the entire result is written to the target object at one time. If the target object is a BitmapData instance and its dispose() method is called before the operation finishes, the complete event is still dispatched in asynchronous mode. However, the result data is not written to the BitmapData object because it is in a disposed state.

completeflash.events:ShaderEventDispatched when the operation finishes, if the start() method is called with a waitForCompletion argument of true. Dispatched when the operation finishes, if the start() method is called with a waitForCompletion argument of true.
height The height of the result data in the target if it is a ByteArray or Vector.&lt;Number&gt; instance.int The height of the result data in the target if it is a ByteArray or Vector.<Number> instance. The size of the ByteArray or Vector.<Number> instance is enlarged if necessary and existing data is overwritten. progress The progress of a running shader.Number The progress of a running shader. This property is a value from 0 through 1. Zero is the initial value (0% complete). One indicates that the shader has completed its operation.

If the cancel() method is called this property becomes undefined, and its value cannot be used reliably until the shader operation starts again.

shader The shader that's used for the operation.flash.display:Shader The shader that's used for the operation. Any input or parameter that the shader expects must be provided using the ShaderInput or ShaderParameter property of the Shader instance's data property. An input must be provided using its corresponding ShaderInput even if it is the same as the target object.

To process a ByteArray containing a linear array of data (as opposed to image data) set the corresponding ShaderInput instance's height to 1 and width to the number of 32-bit floating-point values in the ByteArray. In that case, the input in the shader must be defined with the image1 data type.

flash.display.ShaderDataflash.display.ShaderInputflash.display.ShaderParameter
target The object into which the result of the shader operation is written.Object The object into which the result of the shader operation is written. This object must be a BitmapData, ByteArray, or Vector.<Number> instance. width The width of the result data in the target if it is a ByteArray or Vector.&lt;Number&gt; instance.int The width of the result data in the target if it is a ByteArray or Vector.<Number> instance. The size of the ByteArray or Vector.<Number> instance is enlarged if necessary and existing data is overwritten.
NativeWindowSystemChrome The NativeWindowSystemChrome class defines constants for the systemChrome property of the NativeWindowInitOptions object used to create a native window.Defines constants representing the supported types of window chrome. Object The NativeWindowSystemChrome class defines constants for the systemChrome property of the NativeWindowInitOptions object used to create a native window.

System chrome refers to the operating system-specific elements of a window such as a title bar, minimize, maximize, and close buttons.

Note: The type of system chrome used is specified when a window is created and cannot be changed.

flash.display.NativeWindowflash.display.NativeWindowInitOptionsALTERNATE Reserved for future use.alternateString Reserved for future use.

Do not use.

NONE No system chrome.noneString No system chrome. STANDARD The standard chrome for the host operating system.standardString The standard chrome for the host operating system.

Use this setting to emulate the look and feel of the native operating system.

IGraphicsStroke This interface is used to define objects that can be used as stroke parameters in the flash.display.Graphics methods and drawing classes. This interface is used to define objects that can be used as stroke parameters in the flash.display.Graphics methods and drawing classes. Use the implementor classes of this interface to create and manage stroke property data, and to reuse the same data for different instances. flash.display.Graphics.drawGraphicsData()SimpleButton The SimpleButton class lets you control all instances of button symbols in a SWF file.The SimpleButton class lets you control all instances of button symbols in a SWF file. flash.display:InteractiveObject The SimpleButton class lets you control all instances of button symbols in a SWF file.

In Flash Professional, you can give a button an instance name in the Property inspector. SimpleButton instance names are displayed in the Movie Explorer and in the Insert Target Path dialog box in the Actions panel. After you create an instance of a button in Flash Professional, you can use the methods and properties of the SimpleButton class to manipulate buttons with ActionScript.

In ActionScript 3.0, you use the new SimpleButton() constructor to create a SimpleButton instance.

The SimpleButton class inherits from the InteractiveObject class.

The following example uses the SimpleButtonExample class, which in turn uses the CustomSimpleButton class, and this class then instantiates four ButtonDisplayState objects. The result is a button that is created in the shape of a square, whose background color changes based on the mouse state by overriding instance properties of the SimpleButton class. This is accomplished by performing the following steps:
  1. In the SimpleButtonExample() constructor, a new CustomSimpleButton object of type SimpleButton, called button, is created, which calls the CustomSimpleButton constructor method. The button object is the added to the display list. The button's color and size are determined in the steps that follow.
  2. In the CustomSimpleButton class, instance properties are declared that are later used to control the size and background color of button, based on the state it is in (orange in the normal state, dark yellow in the mouse over state, an light blue in the mouse down state). In all of the button's states, the size of the square is set to 80 pixels by using the size property.
  3. The constructor function for the CustomSimpleButton class sets the downState, overState, upState, hitTestState, and useHandCursor properties with four instances of the ButtonDisplayState class.
  4. In the ButtonDisplayState class, the constructor sets the value of the square's size and background color and calls the draw() method.
  5. The draw() method redraws the square with the size and background color set in the constructor based on the button's state.
package { import flash.display.Sprite; public class SimpleButtonExample extends Sprite { public function SimpleButtonExample() { var button:CustomSimpleButton = new CustomSimpleButton(); addChild(button); } } } import flash.display.DisplayObject; import flash.display.Shape; import flash.display.SimpleButton; class CustomSimpleButton extends SimpleButton { private var upColor:uint = 0xFFCC00; private var overColor:uint = 0xCCFF00; private var downColor:uint = 0x00CCFF; private var size:uint = 80; public function CustomSimpleButton() { downState = new ButtonDisplayState(downColor, size); overState = new ButtonDisplayState(overColor, size); upState = new ButtonDisplayState(upColor, size); hitTestState = new ButtonDisplayState(upColor, size * 2); hitTestState.x = -(size / 4); hitTestState.y = hitTestState.x; useHandCursor = true; } } class ButtonDisplayState extends Shape { private var bgColor:uint; private var size:uint; public function ButtonDisplayState(bgColor:uint, size:uint) { this.bgColor = bgColor; this.size = size; draw(); } private function draw():void { graphics.beginFill(bgColor); graphics.drawRect(0, 0, size, size); graphics.endFill(); } }
InteractiveObject classSimpleButton Creates a new SimpleButton instance.upStateflash.display:DisplayObjectnullThe initial value for the SimpleButton up state. overStateflash.display:DisplayObjectnullThe initial value for the SimpleButton over state. downStateflash.display:DisplayObjectnullThe initial value for the SimpleButton down state. hitTestStateflash.display:DisplayObjectnullThe initial value for the SimpleButton hitTest state. Creates a new SimpleButton instance. Creates a new SimpleButton instance. Any or all of the display objects that represent the various button states can be set as parameters in the constructor. downState Specifies a display object that is used as the visual object for the button "Down" state &#8212;the state that the button is in when the user selects the hitTestState object.flash.display:DisplayObjectSpecifies a DisplayObject value used for the button "Down" state. Specifies a display object that is used as the visual object for the button "Down" state —the state that the button is in when the user selects the hitTestState object. hitTestStateoverStateupStateenabled A Boolean value that specifies whether a button is enabled.BooleanSpecifies whether a button is enabled (true) or disabled (false). A Boolean value that specifies whether a button is enabled. When a button is disabled (the enabled property is set to false), the button is visible but cannot be clicked. The default value is true. This property is useful if you want to disable part of your navigation; for example, you might want to disable a button in the currently displayed page so that it can't be clicked and the page cannot be reloaded.

Note: To prevent mouseClicks on a button, set both the enabled and mouseEnabled properties to false.

hitTestState Specifies a display object that is used as the hit testing object for the button.flash.display:DisplayObject Specifies a display object that is used as the hit testing object for the button. For a basic button, set the hitTestState property to the same display object as the overState property. If you do not set the hitTestState property, the SimpleButton is inactive — it does not respond to user input events. downStateoverStateupStateoverState Specifies a display object that is used as the visual object for the button over state &#8212; the state that the button is in when the pointer is positioned over the button.flash.display:DisplayObjectSpecifies a DisplayObject value used for the button "Over" state. Specifies a display object that is used as the visual object for the button over state — the state that the button is in when the pointer is positioned over the button. downStatehitTestStateupStatesoundTransform The SoundTransform object assigned to this button.flash.media:SoundTransform The SoundTransform object assigned to this button. A SoundTransform object includes properties for setting volume, panning, left speaker assignment, and right speaker assignment. This SoundTransform object applies to all states of the button. This SoundTransform object affects only embedded sounds. flash.media.SoundTransformtrackAsMenu Indicates whether other display objects that are SimpleButton or MovieClip objects can receive user input release events.Boolean Indicates whether other display objects that are SimpleButton or MovieClip objects can receive user input release events. The trackAsMenu property lets you create menus. You can set the trackAsMenu property on any SimpleButton or MovieClip object. If the trackAsMenu property does not exist, the default behavior is false.

You can change the trackAsMenu property at any time; the modified button immediately takes on the new behavior.

upState Specifies a display object that is used as the visual object for the button up state &#8212; the state that the button is in when the pointer is not positioned over the button.flash.display:DisplayObjectSpecifies a DisplayObject value used for the button "Up" state. Specifies a display object that is used as the visual object for the button up state — the state that the button is in when the pointer is not positioned over the button. downStatehitTestStateoverStateuseHandCursor A Boolean value that, when set to true, indicates whether the hand cursor is shown when the pointer rolls over a button.BooleanDisplays a pointing hand cursor when set to true. A Boolean value that, when set to true, indicates whether the hand cursor is shown when the pointer rolls over a button. If this property is set to false, the arrow pointer cursor is displayed instead. The default is true.

You can change the useHandCursor property at any time; the modified button immediately uses the new cursor behavior.

TriangleCulling Defines codes for culling algorithms that determine which triangles not to render when drawing triangle paths.Object Defines codes for culling algorithms that determine which triangles not to render when drawing triangle paths.

The terms POSITIVE and NEGATIVE refer to the sign of a triangle's normal along the z-axis. The normal is a 3D vector that is perpendicular to the surface of the triangle.

A triangle whose vertices 0, 1, and 2 are arranged in a clockwise order has a positive normal value. That is, its normal points in a positive z-axis direction, away from the current view point. When the TriangleCulling.POSITIVE algorithm is used, triangles with positive normals are not rendered. Another term for this is backface culling.

A triangle whose vertices are arranged in a counter-clockwise order has a negative normal value. That is, its normal points in a negative z-axis direction, toward the current view point. When the TriangleCulling.NEGATIVE algorithm is used, triangles with negative normals will not be rendered.

flash.display.Graphics.drawTriangles()flash.display.GraphicsTrianglePathIntroduction to 3D Vectors3D Backface CullingNEGATIVE Specifies culling of all triangles facing toward the current view point.negativeString Specifies culling of all triangles facing toward the current view point. NONE Specifies no culling.noneString Specifies no culling. All triangles in the path are rendered. POSITIVE Specifies culling of all triangles facing away from the current view point.positiveString Specifies culling of all triangles facing away from the current view point. This is also known as backface culling.
NativeWindow The NativeWindow class provides an interface for creating and controlling native desktop windows.flash.events:EventDispatcher The NativeWindow class provides an interface for creating and controlling native desktop windows.

AIR profile support: This feature is supported on all desktop operating systems, but is not supported on mobile devices or AIR for TV devices. You can test for support at run time on desktop devices using the NativeWindow.isSupported property. See AIR Profile Support for more information regarding API support across multiple profiles.

A reference to the NativeWindow instance is returned by the window constructor. A reference to a NativeWindow instance can also be accessed using the stage.nativeWindow property of any display object on that window's stage:

var window:NativeWindow = displayObject.stage.nativeWindow;

The properties of a NativeWindow instance can only be accessed by application content. If non-application content attempts to access the NativeWindow object, a security error will be thrown.

Content can be added to a window using the DisplayObjectContainer methods of the Stage object such as addChild().

You cannot not add Flex components directly to the display list of a NativeWindow instance. Instead, use the Flex mx:WindowedApplication and mx:Window components to create your windows and add the other Flex components as children of those objects. You can add Flex-based SWF content directly to a NativeWindow window as long as the SWF file is loaded into its own application domain and is application content.

To create a root HTML window for displaying HTML content it is typically easier to create the window with HTMLLoader.createRootWindow(). Windows created in this way will have an HTMLLoader object added automatically. (From JavaScript code, you can also use the JavaScript window.open() function. However, this method gives you less control over the window appearance and behavior.)

The following operations on NativeWindow objects are asynchronous: close(), maximize(), minimize(), restore(), and bounds changes. An application can detect when these operations have completed by listening for the appropriate events.

If the NativeApplication.autoExit property is true, which is the default, the application will close when its last window is closed (and all close event handlers have returned). If autoExit is false, then NativeApplication.nativeApplication.exit() must be called to terminate the application.

NativeWindow objects will not be garbage collected after the window constructor has been called and before close() has been called. It is the responsibility of the application to close its own windows.

flash.display.Stage.nativeWindowflash.display.NativeWindowInitOptionsflash.desktop.NativeApplicationflash.system.ApplicationDomainflash.html.HTMLLoader.createRootWindow()deactivate Dispatched by this NativeWindow object after the window has been deactivated.flash.events.Event.DEACTIVATEflash.events.Event Dispatched by this NativeWindow object after the window has been deactivated. activate Dispatched by this NativeWindow object after the window has been activated.flash.events.Event.ACTIVATEflash.events.Event Dispatched by this NativeWindow object after the window has been activated. close Dispatched by this NativeWindow object after the window has been closed.flash.events.Event.CLOSEflash.events.Event Dispatched by this NativeWindow object after the window has been closed. closing Dispatched by this NativeWindow object immediately before the window is to be closed.flash.events.Event.CLOSINGflash.events.Event Dispatched by this NativeWindow object immediately before the window is to be closed. This event can be canceled to prevent the window from being closed. displayStateChange Dispatched by this NativeWindow object after the window's displayState property has changed.flash.events.NativeWindowDisplayStateEvent.DISPLAY_STATE_CHANGEflash.events.NativeWindowDisplayStateEvent Dispatched by this NativeWindow object after the window's displayState property has changed.

Do not resize the window or change its display state in the displayStateChange event handler.

displayStateChanging Dispatched by this NativeWindow object immediately before the window changes its display state.flash.events.NativeWindowDisplayStateEvent.DISPLAY_STATE_CHANGINGflash.events.NativeWindowDisplayStateEvent Dispatched by this NativeWindow object immediately before the window changes its display state. This event can be canceled to prevent the change. The following example demonstrates how to cancel a displayStateChanging event. function displayStateChanging_handler(displayStateEvent:NativeWindowDisplayStateEvent):void { //shouldStopStateChange is an application-defined Boolean indicating //that display state changes should be canceled if (displayStateEvent.type == NativeWindowDisplayStateEvent.DISPLAY_STATE_CHANGING && shouldStopStateChange) { displayStateEvent.preventDefault(); } } resize Dispatched by this NativeWindow object after the window has been resized.flash.events.NativeWindowBoundsEvent.RESIZEflash.events.NativeWindowBoundsEvent Dispatched by this NativeWindow object after the window has been resized. A resize event is dispatched whenever the size (width or height properties) of the window changes, which can occur because of a system-controlled window resize; minimizing, maximizing, or restoring the window; or changing the window size by setting the width, height, or bounds properties. NativeWindow resize events are dispatched during system-controled resize loops. In contrast, Stage object resize events are dispatched when the Stage is ready for drawing. Stage resize eventresizing Dispatched by this NativeWindow object immediately before the window is to be resized on the desktop.flash.events.NativeWindowBoundsEvent.RESIZINGflash.events.NativeWindowBoundsEvent Dispatched by this NativeWindow object immediately before the window is to be resized on the desktop. This event can be canceled to prevent or modify the resize. The following example demonstrates how to cancel a resizing event. function boundsChanging_handler(boundsEvent:NativeWindowBoundsEvent):void { //shouldStopResize is an application-defined Boolean indicating //that resize operations should be canceled if (boundsEvent.type == NativeWindowBoundsEvent.RESIZING && shouldStopResize) { boundsEvent.preventDefault(); } } move Dispatched by this NativeWindow object after the window has been moved on the desktop.flash.events.NativeWindowBoundsEvent.MOVEflash.events.NativeWindowBoundsEvent Dispatched by this NativeWindow object after the window has been moved on the desktop.

A move event is dispatched whenever the origin (x or y properties) of the window changes, which can occur because of a system-controlled window move; minimizing, maximizing, or restoring the window; or changing the window location by setting the x, y, or bounds properties.

Note: Avoid actions that may open simultaneous operating system dialogs boxes in the handler functions for both the moving and move events of a NativeWindow object. This may occur, for example, if both handler functions throw an error. If it does occur, the second dialog box opened will not register mouse clicks and must be closed using the keyboard.

moving Dispatched by the NativeWindow object immediately before the window is to be moved on the desktop.flash.events.NativeWindowBoundsEvent.MOVINGflash.events.NativeWindowBoundsEvent Dispatched by the NativeWindow object immediately before the window is to be moved on the desktop. This event can be canceled to prevent or modify the move.

Note: Avoid actions that may open simultaneous operating system dialogs boxes in the handler functions for both the moving and move events of a NativeWindow object. This may occur, for example, if both handler functions throw an error. If it does occur, the second dialog box opened will not register mouse clicks and must be closed using the keyboard.

NativeWindow Creates a new NativeWindow instance and a corresponding operating system window.If the initOptions parameter is invalid. IllegalOperationErrorflash.errors:IllegalOperationErrorinitOptionsflash.display:NativeWindowInitOptionsAn object containing the initialization properties for this window. Creates a new NativeWindow instance and a corresponding operating system window.

The settings defined in the initOptions parameter cannot be changed after the window is created. Invalid initOptions settings will cause an illegal operation error to be thrown. Settings that are valid but not available on the current system will not throw an exception. The window capabilities specific to the current operating system can be detected, if desired, using the static NativeWindow members such as systemMaxSize.

The default window size is determined by the operating system, and windows are created in an invisible state. To prevent changes to the window from being visible, do not change the window visible property to true or call activate() until the window changes are finished.

The following example creates and activates a new NativeWindow instance: import flash.display.NativeWindowInitOptions; import flash.display.NativeWindowSystemChrome; import flash.display.NativeWindowType; import flash.display.NativeWindow; import flash.display.StageAlign; import flash.display.StageScaleMode; import flash.geom.Rectangle; var windowOptions:NativeWindowInitOptions = new NativeWindowInitOptions(); windowOptions.systemChrome = NativeWindowSystemChrome.STANDARD; windowOptions.type = NativeWindowType.NORMAL; var newWindow:NativeWindow = new NativeWindow(windowOptions); newWindow.stage.scaleMode = StageScaleMode.NO_SCALE; newWindow.stage.align = StageAlign.TOP_LEFT; newWindow.bounds = new Rectangle(100, 100, 800, 800); newWindow.activate();
flash.display.NativeWindowInitOptionsflash.html.HTMLLoader.createRootWindow()
activate Activates this window. Activates this window.

Activating a window will:

  • Make the window visible
  • Bring the window to the front
  • Give the window keyboard and mouse focus

On Linux, activate() is an asynchronous operation.

The NativeWindow object dispatches an activate event on all platforms.

The following examples show how to activate a window.

With a reference to a display object on the window stage:

displayObject.stage.nativeWindow.activate();
With a reference to an instance of the NativeWindow class: windowObj.activate(); From JavaScript in an HTML page rendered in the window (where window is the global JavaScript window object): window.nativeWindow.activate();
visibleorderToFront()
close Closes this window. Closes this window.

A close event is dispatched as soon as the close operation is complete. A closing event will not be dispatched. If cancellation of the close operation should be allowed, dispatch a closing event and check whether any registered listeners cancel the default behavior before calling the close() method.

When a window is closed, any windows that it owns are also closed. The owned windows do not dispatch closing events.

If display object instances that are currently in the window are not referenced elsewhere they will be garbage collected and destroyed, except on the initial application window created by AIR. To allow display objects on the initial window to be garbage collected, remove them from the window stage.

After being closed, the NativeWindow object is still a valid reference, but accessing most properties and methods will throw an illegal operation error.

Closed windows cannot be reopened. If the window is already closed, no action is taken and no events are dispatched.

Note: to hide a window without closing it, set the window's visible property to false.

The following examples show how to close a window:

With a reference to the NativeWindow instance (windowObj):

windowObj.close();
With a reference to a display object on the window stage: displayObj.stage.nativeWindow.close(); From a JavaScript routine running in an HTMLLoader object (or HTML root window): window.close(); //overriddable in HTMLHost Or: window.nativeWindow.close(); //not overriddable The following example illustrates how to allow cancellation of a close operation (where windowObj is the NativeWindow instance to be closed): public function closeCommand():Boolean{ var closeEvent:Event = new Event(Event.CLOSING,true,true); windowObj.dispatchEvent(closeEvent); if(!closeEvent.isDefaultPrevented()){ windowObj.close(); return true; } else { return false; } } The following example illustrates how to close a window from a JavaScript routine running in an HTMLLoader object (or HTML root window), while allowing the operation to be canceled: <script src="AIRAliases.js" type="text/javascript"></script> <script type="text/javascript"> var dirtyData = false; function closeWindow(){ var closingEvent = new air.Event(air.Event.CLOSING,true,true); window.nativeWindow.dispatchEvent(closingEvent); if(!closingEvent.isDefaultPrevented()){ window.nativeWindow.close(); //or use: window.close(); return true; } else { return false; } } function onClosing(event){ if(dirtyData){ event.preventDefault(); //Save data... } } window.nativeWindow.addEventListener(air.Event.CLOSING,onClosing); </script>
flash.display.NativeWindow.closedflash.html.HTMLLoaderflash.html.HTMLHost
globalToScreen Converts a point in pixel coordinates relative to the origin of the window stage (a global point in terms of the display list), to a point on the virtual desktop.The specified global point relative to the desktop. flash.geom:PointglobalPointflash.geom:PointThe point on the stage to convert to a point on the screen. Converts a point in pixel coordinates relative to the origin of the window stage (a global point in terms of the display list), to a point on the virtual desktop.

Virtual desktop coordinates are relative to the upper, lefthand corner of the primary monitor.

flash.display.Screen
listOwnedWindows Returns a list of the NativeWindow objects that are owned by this window.an Vector.<NativeWindow> object containing zero or more NativeWindow objects that are owned by this instance. Returns a list of the NativeWindow objects that are owned by this window.

You cannot change ownership of NativeWindows by adding or removing objects from the returned vector. Window ownership cannot be changed after a window is created.

flash.display.NativeWindowInitOptions.owner
maximize Maximizes this window.If this method is called after this window has been closed. IllegalOperationErrorflash.errors:IllegalOperationError Maximizes this window.

Calling maximize() method dispatches a displayStateChange event, and, if applicable, a move and a resize event. Whereas system chrome will dispatch a displayStateChanging event that can be canceled when a maximize command is initiated by a user, your maximize logic must implement this behavior, if desired.

The maximize() method executes asynchronously. To detect the completion of the state change, listen for the displayStateChange event. If the window is already maximized, no action is taken and no events are dispatched.

OS behavior notes:

  • On operating systems, such as Mac OS X, in which maximizing a window does not also prevent resizing, calling maximize() will zoom the window to fill the screen, but will not prevent subsequent resizing of the window. Resizing a zoomed window will also restore the display state.
  • On some operating systems, such as Mac OS X, as well as on some Linux window managers, maximizing a window will not expand the window beyond the width and height specified in the maxSize property. On others, the window will expand to fill the screen even if the screen is larger than the maxSize.
  • Some Linux window managers do not allow utility windows to be maximized.
The following example illustrates how to allow cancelation of a maximize operation: public function maximizeWindow(nativeWin:NativeWindow):Boolean{ if(nativeWin.displayState != NativeWindowDisplayState.MAXIMIZED){ var beforeState:String = nativeWin.displayState; var afterState:String = NativeWindowDisplayState.MAXIMIZED; var displayStateEvent:NativeWindowDisplayStateEvent = new NativeWindowDisplayStateEvent(NativeWindowDisplayStateEvent.DISPLAY_STATE_CHANGING, true,true,beforeState,afterState); nativeWin.dispatchEvent(displayStateEvent); if(!displayStateEvent.isDefaultPrevented()){ nativeWin.maximize(); return true; } else { return false; } } return false; } The following example illustrates how to allow cancelation of a maximize operation from a JavaScript routine running in an HTMLLoader object on the window (or an HTML window): function maximizeWindow(nativeWin){ if(nativeWin.displayState != air.NativeWindowDisplayState.MAXIMIZED){ var beforeState = nativeWin.displayState; var afterState = air.NativeWindowDisplayState.MAXIMIZED; var displayStateEvent = new air.NativeWindowDisplayStateEvent(air.NativeWindowDisplayStateEvent.DISPLAY_STATE_CHANGING, true,true,beforeState,afterState); nativeWin.dispatchEvent(displayStateEvent); if(!displayStateEvent.isDefaultPrevented()){ nativeWin.maximize(); return true; } else { return false; } } return false; }
flash.display.NativeWindowDisplayStateflash.events.NativeWindowDisplayStateEvent
minimize Minimizes this window.If this method is called after this window has been closed. IllegalOperationErrorflash.errors:IllegalOperationError Minimizes this window.

Calling minimize() dispatches a displayStateChange event, and, if applicable, a move and a resize event. Whereas system chrome will dispatch a displayStateChanging event that can be canceled when a minimize command is initiated by a user, calling minimize() directly does not. Your minimize logic may implement this behavior, if desired.

The minimize() method executes asynchronously. To detect the completion of the state change, listen for the displayStateChange event, which is dispatched on all platforms. If the window is already minimized, no action is taken and no events are dispatched.

Any windows owned by this window are hidden when it is minimized. The owned windows do not dispatch displayStateChanging or displayStateChange events.

Notes:

  • On Windows, minimizing an invisible window (visible == false), will make the window visible.
  • Some Linux window managers do not allow utility windows to be minimized.
The following example illustrates how to allow cancelation of a call to minimize() by dispatching a displayStateChanging event: public function minimizeWindow(nativeWin:NativeWindow):Boolean{ if(nativeWin.displayState != NativeWindowDisplayState.MINIMIZED){ var beforeState:String = nativeWin.displayState; var afterState:String = NativeWindowDisplayState.MINIMIZED; var displayStateEvent:NativeWindowDisplayStateEvent = new NativeWindowDisplayStateEvent(NativeWindowDisplayStateEvent.DISPLAY_STATE_CHANGING, true,true,beforeState,afterState); nativeWin.dispatchEvent(displayStateEvent); if(!displayStateEvent.isDefaultPrevented()){ nativeWin.minimize(); return true; } else { return false; } } return false; } The following example illustrates how to allow cancelation of a call to minimize() in JavaScript running in an HTMLLoader object (or HTML window): function minimizeWindow(){ if(window.nativeWindow.displayState != air.NativeWindowDisplayState.MINIMIZED){ var beforeState = window.nativeWindow.displayState; var afterState = air.NativeWindowDisplayState.MINIMIZED; var displayStateEvent = new air.NativeWindowDisplayStateEvent(air.NativeWindowDisplayStateEvent.DISPLAY_STATE_CHANGING, true,true,beforeState,afterState); window.nativeWindow.dispatchEvent(displayStateEvent); if(!displayStateEvent.isDefaultPrevented()){ window.nativeWindow.minimize(); return true; } else { return false; } } return false; }
flash.display.NativeWindowDisplayStateflash.events.NativeWindowDisplayStateEvent
notifyUser Triggers a visual cue through the operating system that an event of interest has occurred.typeStringA string representing the urgency of the notification. Triggers a visual cue through the operating system that an event of interest has occurred.

When NativeWindow.supportsNotification is true, the visual cue will conform to the operating system convention of the native system. For example, on Windows, the task bar icon will flash.

The type parameter determines the intensity of the cue. Constants for the permitted values are defined in the NotificationType class, and may be:

  • NotificationType.INFORMATIONAL
  • NotificationType.CRITICAL

The cues provided for informational notifications are of short duration; those provided for critical notifications will last until the user activates this window. Not all Linux window managers support two levels of notification. For such window managers, notifyUser() will have the same affect no matter which option is specified.

Note: Calling notifyUser() when NativeWindow.supportsNotification is false is allowed, but does nothing.

orderInBackOf Sends this window directly behind the specified window.true if this window was successfully sent to the back; false if this window is invisible or minimized. Booleanwindowflash.display:NativeWindowAn application window. Sends this window directly behind the specified window.

Does not activate or acquire the focus for the window or the application. Minimized or hidden (visible is false) windows cannot be reordered.

An owned window can never be moved behind its owner. If this window has an owner, then the owner and its other owned windows are also ordered behind the target. If the target window has an owner, then this window is ordered behind the owner of the target instead.

Some Linux window managers do not allow utility windows to be ordered behind normal windows.

The following examples show how to move a window just below another window with references to the NativeWindow instances: windowBehind.orderInBackOf(windowFront); With references to display objects on the window stages: displayObjBehind.stage.nativeWindow.orderInBackOf(displayObjectFront.stage.nativeWindow); From a JavaScript routine running in an HTMLLoader object (or HTML root window) using references to two JavaScript Window objects: jsWindowObjBehind.nativeWindow.orderInBackOf(jsWindowObjFront.nativeWindow);
orderInFrontOf Brings this window directly in front of the specified window.true if this window was successfully brought to the front; false if this window is invisible or minimized. Booleanwindowflash.display:NativeWindowAn application window. Brings this window directly in front of the specified window.

Does not activate or acquire the focus for the window or the application. Minimized or hidden (visible is false) windows cannot be reordered.

A window can never be moved in front of a window that it owns. If this window has an owner, then the owner and its other owned windows are also ordered in front of the target. If the target window has an owner, then this window is also ordered in front of any other windows that have the same owner as the target.

Some Linux window managers do not allow normal windows to be ordered in front of utility windows.

The following examples show how to move a window just above another window with references to the NativeWindow instances: windowFront.orderInFrontOf(windowBehind); With references to display objects on the window stages: displayObjFront.stage.nativeWindow.orderInFrontOf(displayObjectBehind.stage.nativeWindow); From a JavaScript routine running in an HTMLLoader object (or HTML root window) using references to two JavaScript window objects: jsWindowObjFront.nativeWindow.orderInFrontOf(jsWindowObjBehind.nativeWindow);
orderToBack Sends this window behind any other visible windows.true if this window was successfully sent to the back; false if this window is invisible or minimized. Boolean Sends this window behind any other visible windows.

Does not activate or acquire the focus for this window or the application. Minimized or hidden (visible is false) windows cannot be reordered.

If alwaysInFront is true, then calling this method will not send this window behind any windows which have alwaysInFront set to false.

An owned window can never be moved behind its owner. If this window has an owner, then the owner and its other owned windows are also ordered to the bottom of window display list. This window will move behind any other windows owned by the same window. If this window owns other windows, then those windows are also moved to the back, maintaining their current order relative to each other.

Some Linux window managers do not allow utility windows to be ordered behind normal windows.

The following examples show how to move a window behind all other windows in the application (with the same alwaysInFront setting): windowObj.orderToBack(); With a reference to a display object on the window stage: displayObj.stage.nativeWindow.orderToBack(); From a JavaScript routine running in an HTMLLoader object in the window (or a root HTML window): window.nativeWindow.orderToBack();
orderToFront Brings this window in front of any other visible windows.true if this window was successfully brought to the front; false if this window is invisible or minimized. Boolean Brings this window in front of any other visible windows.

Does not activate or acquire the focus for this window or the application. Minimized or hidden (visible is false) windows cannot be reordered.

If alwaysInFront is false, then calling this method will not send this window in front of any windows which have alwaysInFront set to true.

A window can never be moved in front of a window that it owns. If this window owns other windows, then those windows are also moved to the front, maintaining their current order relative to each other. If this window has an owner, then the owner and its other owned windows are also ordered to the front of the window display order. This window is moved in front of other windows that have the same owner.

Some Linux window managers do not allow normal windows to be ordered in front of utility windows.

The following examples show how to move a window in front of all other windows in the application (with the same alwaysInFront setting): windowObj.orderToFront(); With a reference to a display object on the window stage: displayObj.stage.nativeWindow.orderToFront(); From a JavaScript routine running in an HTMLLoader object in the window (or a root HTML window): window.nativeWindow.orderToFront();
restore Restores this window from either a minimized or a maximized state.If the method is called after this window has been closed. IllegalOperationErrorflash.errors:IllegalOperationError Restores this window from either a minimized or a maximized state.

Calling restore() dispatches a displayStateChange event, and, if applicable, a move and a resize event. Whereas system chrome will dispatch a displayStateChanging event that can be canceled when a restore command is initiated by a user, your restore logic must implement this behavior, if desired.

If the window is already in the NativeWindowDisplayState.NORMAL state, no action is taken and no events are dispatched.

To detect the completion of the state change, listen for the displayStateChange event, which is dispatched on all platforms.

The following example illustrates how to allow cancelation of a restore operation: public function restoreWindow(nativeWin:NativeWindow):Boolean{ if(nativeWin.displayState != NativeWindowDisplayState.NORMAL){ var beforeState:String = nativeWin.displayState; var afterState:String = NativeWindowDisplayState.NORMAL; var displayStateChangingEvent:NativeWindowDisplayStateEvent = new NativeWindowDisplayStateEvent(NativeWindowDisplayStateEvent.DISPLAY_STATE_CHANGING, true,true,beforeState,afterState); nativeWin.dispatchEvent(displayStateChangingEvent); if(!displayStateChangingEvent.isDefaultPrevented()){ nativeWin.restore(); return true; } else { return false; } } return false; } The following example illustrates how to allow cancelation of a restore operation from a JavaScript routine running in an HTMLLoader object on the window (or an HTML window): function restoreWindow(nativeWin){ if(window.nativeWindow.displayState != air.NativeWindowDisplayState.NORMAL){ var beforeState = window.nativeWindow.displayState; var afterState = air.NativeWindowDisplayState.NORMAL; var displayStateEvent = new air.NativeWindowDisplayStateEvent(air.NativeWindowDisplayStateEvent.DISPLAY_STATE_CHANGING, true,true,beforeState,afterState); window.nativeWindow.dispatchEvent(displayStateEvent); if(!displayStateEvent.isDefaultPrevented()){ window.nativeWindow.restore(); return true; } else { return false; } } return false; }
flash.display.NativeWindowDisplayStateflash.events.NativeWindowDisplayStateEvent
startMove Starts a system-controlled move of this window.If the method is called after this window has been closed. IllegalOperationErrorflash.errors:IllegalOperationErrortrue if the move was successfully initiated and false if the window is maximized. Boolean Starts a system-controlled move of this window.

When called from a mouseDown event, this method begins a mouse-driven move sequence that continues until a mouseUp event occurs.

When called from other code this method begins a keyboard- or mouse-driven move sequence consistent with the operating system's default sequence.

During a move sequence, a series of events will be dispatched as the window origin moves. For each incremental move, first a moving event is dispatched and then, if the moving event is not canceled, the window location is updated and a move event is dispatched. If a moving event is canceled, the move sequence is immediately terminated.

The following example shows how to move a window in response to a mouseDown event: var initOpts:NativeWindowInitOptions = new NativeWindowInitOptions(); var win:NativeWindow = new NativeWindow(initOpts); win.activate(); win.stage.addEventListener(MouseEvent.MOUSE_DOWN, mouseDownHandler); function mouseDownHandler(event:MouseEvent):void { win.startMove(); }
startResize Starts a system-controlled resize operation of this window.If the method is called after this window has been closed. IllegalOperationErrorflash.errors:IllegalOperationErrortrue if the resize was successfully initiated and false if the window is maximized. BooleanedgeOrCornerStringBRA constant from the NativeWindowResize class that specifies which edge or corner of this window to resize. The following are valid values:

ValueVertical alignmentHorizontal alignmentNativeWindowResize.TOPTopCenterNativeWindowResize.BOTTOMBottomCenterNativeWindowResize.LEFTCenterLeftNativeWindowResize.RIGHTCenterRightNativeWindowResize.TOP_LEFTTopLeftNativeWindowResize.TOP_RIGHTTopRightNativeWindowResize.BOTTOM_LEFTBottomLeftNativeWindowResize.BOTTOM_RIGHTBottomRightNativeWindowResize.NONE----

Starts a system-controlled resize operation of this window.

When called from a mouseDown event handler this method begins a mouse-driven resizing sequence that continues until a mouseUp event occurs.

When called from other code this method begins a keyboard- or mouse-driven resizing sequence consistent with the operating system's default sequence.

During the resize sequence, a series of events will be dispatched as the window dimensions change. For each incremental change, first a resizing event is dispatched and then, if the resizing event is not canceled, the window dimensions are updated and a resize event is dispatched. If a resizing event is canceled, the the sequence is immediately terminated.

The following example shows how to resize a window in response to a mouseDown event: stage.addEventListener(MouseEvent.MOUSE_DOWN, onResizeCommand); function onResizeCommand(event:MouseEvent):void { var win:NativeWindow = event.target.nativeWindow; var resizeFrom:String = ""; if (event.stageY < win.height * .33) { resizeFrom = NativeWindowResize.TOP; } else if (event.stageY > win.height * .66) { resizeFrom = NativeWindowResize.BOTTOM; } if (event.stageX < win.width * .33) { resizeFrom += NativeWindowResize.LEFT; } else if (event.stageX > win.width * .66) { resizeFrom += NativeWindowResize.RIGHT; } win.startResize(resizeFrom); }
flash.display.NativeWindowResize
active Indicates whether this window is the active application window.Boolean Indicates whether this window is the active application window.

Use the activate() method to make a window active.

flash.display.NativeWindow.activate()flash.desktop.NativeApplication.activate()
alwaysInFront Specifies whether this window will always be in front of other windows (including those of other applications).Boolean Specifies whether this window will always be in front of other windows (including those of other applications).

There are two groups of windows in the system depth order. Windows in the alwaysInFront group are always displayed in front of all other windows. Depth ordering between windows within the same group is determined normally. In other words, activating a window will bring it in front of other windows in its group.

Changing alwaysInFront from false to true will bring the window to the top of all other windows. Changing the property from true to false will send the window to the back of "alwaysInFront" windows, but still in front of other windows. Setting the property to its current value will not change the window depth order. Setting the alwaysInFront property of a window that has an owner has no effect.

The alwaysInFront property should rarely be set to true since windows with this setting will appear in front of the windows of other applications even when the other application is active.

OS behavior notes:

  • Some Linux window managers do not display windows that have the alwaysInFront property set to in front of fullscreen windows.
  • On Mac® OS X, setting alwaysInFront to true will have no effect when the displayState property of the window stage is fullScreen or fullScreenInteractive.
The following examples force a window to be displayed in front of all other windows (that are not similarly forced to the front): windowObj.alwaysInFront = true; With a reference to a display object on the window stage: displayObject.stage.nativeWindow.alwaysInFront=true; From a JavaScript routine running in an HTMLLoader object in the window (or a root HTML window): window.nativeWindow.alwaysInFront = true;
bounds The size and location of this window.flash.geom:RectangleIf the rectangle is null or contains invalid values. ArgumentErrorArgumentErrorIf the bounds property is accessed after this window has been closed. IllegalOperationErrorflash.errors:IllegalOperationError The size and location of this window.

The dimensions of a window include any system chrome. The dimensions of a window's stage are equal to the dimensions of the window, minus the size of any system chrome. Changing the width and height of the window will change the stage's stageWidth and stageHeight. The reverse also applies; changing the stage dimensions will change the window size.

In a root HTML window, the outerWidth and outerHeight properties are equivalent to the window height and width properties. The innerWidth and innerHeight properties equal the stage.stageWidth and stage.stageHeight properties minus the thickness of any automatic scrollbars displayed by the window.

A resize event is dispatched whenever the width or height of this window changes. Likewise, a move event is dispatched whenever the origin (x,y) of this window changes. On Mac OS and Windows, setting the bounds property directly will not dispatch a moving or resizing event. However, on Linux the NativeWindow does dispatch a moving and resizing events when you set the bounds property.

Setting the bounds property of a window is equivalent to setting its x, y, width, and height properties. Likewise, setting any of the individual dimensions is equivalent to setting the bounds property. When you set all the dimensions at the same time by using the bounds property, fewer events are dispatched.

The order in which the individual dimensions are set is not guaranteed. On Linux window managers that do not allow windows to extend off the desktop area, a change to an individual property may be blocked even though the net affect of applying all the property changes would have resulted in a legal window.

If the width or height specified is less than the minimum or greater than the maximum allowed width or height, then the window width or height is set to the closest legal size. The factors that determine the minimum and maximum width and height are the following:

  • The minSize and maxSize properties of the NativeWindow object
  • The minimum and maximum operating system limits, which are the values of NativeWindow.systemMinSize and NativeWindow.systemMaxSize.
  • The maximum width and height of a window in Adobe AIR, which are each 4095 pixels. (In AIR 1.5 and earlier, the maximum width and height of a window is 2880 pixels each.)
  • The minimum width and height required by any displayed system chrome.

Pixel values are rounded to the nearest integer when the position or dimensions of a window are changed.

The following examples set the bounds of a window with a reference to a NativeWindow object: windowObj.bounds = new Rectangle(200, 200, 1000, 800); With a reference to a display object on the window stage: displayObject.stage.nativeWindow.bounds = new Rectangle(20, 20, 800, 600); From a JavaScript routine running in an HTMLLoader object in the window (or a root HTML window): window.nativeWindow.bounds = new air.Rectangle(20, 20, 800, 600);
flash.display.NativeWindowInitOptions.resizable
closed Indicates whether this window has been closed.Boolean Indicates whether this window has been closed.

Accessing the following properties on a closed window will throw an illegal operation error:

  • title
  • bounds
  • x, y, width, height
  • displayState
  • visible

Likewise, calling the following methods on a closed window will also throw an illegal operation error:

  • minimize()
  • maximize()
  • restore()
  • startResize()
  • startMove()
The following examples show how to access the closed property of a window: var isWindowClosed:Boolean = windowObj.closed; With a reference to a display object on the window stage: var isWindowClosed:Boolean = displayObject.stage.nativeWindow.closed; From a JavaScript routine running in an HTMLLoader object in the window (or root HTML window): var isWindowClosed = window.nativeWindow.closed;
displayState The display state of this window.StringIf the displayState property is accessed after this window has been closed. IllegalOperationErrorflash.errors:IllegalOperationError The display state of this window.

Constants for the possible values are defined in the NativeWindowDisplayState class:

  • NativeWindowDisplayState.NORMAL
  • NativeWindowDisplayState.MINIMIZED
  • NativeWindowDisplayState.MAXIMIZED
The following example shows how to get the current window display state given a reference to the window object: var state:String = windowObj.displayState;
flash.display.NativeWindowDisplayState
height The height of this window in pixels.NumberIf the value set is null or invalid. ArgumentErrorArgumentErrorIf the property is accessed after this window has been closed. IllegalOperationErrorflash.errors:IllegalOperationError The height of this window in pixels.

The dimensions of a window include any system window chrome that is displayed. The height of the usable display area inside a window is available from the Stage.stageHeight property.

Changing the height property of a window is equivalent to changing the height through the bounds property.

If the height specified is less than the minimum or greater than the maximum allowed height, then the window height is set to the closest legal size. The factors that determine the minimum and maximum height are the following:

  • The minSize.x and maxSize.x properties of the NativeWindow object
  • The minimum and maximum operating system limits, which are the values of NativeWindow.systemMinSize.x and NativeWindow.systemMaxSize.x.
  • The maximum height of a window in Adobe AIR, which is 4095 pixels (2880 pixels in AIR 1.5 and earlier).

On Linux, setting the height property is an asynchronous operation.

To detect the completion of the height change, listen for the resize event, which is dispatched on all platforms.

Pixel values are rounded to the nearest integer when the height of a window is changed.

flash.display.NativeWindow.boundsflash.display.Stage.stageHeight
isSupported Indicates whether native windows are supported on the client system.Boolean Indicates whether native windows are supported on the client system. maxSize The maximum size for this window.flash.geom:PointIf assigned size is not within the operating system minimum and maximum window sizes. IllegalOperationErrorflash.errors:IllegalOperationErrorIf size is forbidden for the content's current privilege. SecurityErrorSecurityErrorIf the size is null or contains invalid values. ArgumentErrorArgumentErrorIf the maxSize property is accessed after this window has been closed. IllegalOperationErrorflash.errors:IllegalOperationError The maximum size for this window.

The size limit is specified as the coordinates of a Point object. The point x property corresponds to the window width, the y property to the window height.

The maxSize restriction is enforced for window resizing operations invoked both through ActionScript code and through the operating system.

Setting maxSize will change the window bounds if the current bounds are larger than the new maximum size.

If the width or height specified is greater than the maximum allowed width or height, then the window width is set to the closest legal size. The factors that determine the minimum and maximum width and height are the following:

  • The maximum operating system limit, which is the value NativeWindow.systemMaxSize.
  • The maximum width and height of a window in Adobe AIR, which is 4095 pixels for each. (In AIR 1.5 and earlier, the maximum width and height of a window is 2880 pixels each.)

Note: On some operating systems, such as Mac OS X, maximizing a window will only enlarge the window to the maxSize value even if the maximized window will be smaller than the operating system screen. The window will still be in the maximized display state.

The following examples show how to set the maximum allowed size for a window. windowObj.maxSize = new Point(1040,920); With a reference to a display object on the window stage: displayObject.stage.nativeWindow.maxSize = new Point(800,600); From a JavaScript routine running in an HTMLLoader object in a window (or in a root HTML window): window.nativeWindow.maxSize = new air.Point(960,960);
flash.display.NativeWindow.systemMinSizeflash.display.NativeWindow.systemMaxSize
maximizable Reports the maximizable setting used to create this window.BooleanWhen trying to set to false without sufficient privilege. SecurityErrorSecurityErrorIf the property is accessed after this window has been closed. IllegalOperationErrorflash.errors:IllegalOperationError Reports the maximizable setting used to create this window.

The maximizable setting cannot be changed after a window is created.

Note: Some Linux window managers allow windows to be maximized by the user even when the maximizable property is set to false.

flash.display.NativeWindowInitOptions.maximizable
menu The native menu for this window.flash.display:NativeMenu The native menu for this window.

When a NativeMenu object is assigned to the window menu property, a native menu will be displayed for a window if NativeWindow.supportsMenu is true, unless the window systemChrome property is NativeWindowSystemChrome.NONE.

Note: Assigning a menu to a window when NativeWindow.supportsMenu is false or when the window systemChrome property is NativeWindowSystemChrome.NONE is allowed, but does nothing. Be sure to use the NativeWindow.supportsMenu property to determine whether the operating system supports window menus. Using other means (such as Capabilities.os) to determine support can lead to programming errors (if some possible target operating systems are not considered).

flash.display.NativeWindow.supportsMenu
minSize The minimum size for this window.flash.geom:PointIf the assigned size is not within the operating system minimum and maximum window sizes. IllegalOperationErrorflash.errors:IllegalOperationErrorIf size is forbidden for the content's current privilege. SecurityErrorSecurityErrorIf the size is null or contains invalid values. ArgumentErrorArgumentErrorif the minSize property is accessed after this window has been closed. IllegalOperationErrorflash.errors:IllegalOperationError The minimum size for this window.

The size limit is specified as the coordinates of a Point object. The point x property corresponds to the window width, the y property to the window height.

Setting minSize, will change the window bounds if the current bounds are smaller than the new minimum size.

The minSize restriction is enforced for window resizing operations invoked both through ActionScript code and through the operating system.

Note: The width and height of any displayed system chrome may make it impossible to set a window as small as the specified minimum size.

The following examples show how to set the minimum allowed size for a window: windowObj.minSize = new Point(200,80); With a reference to a display object on the window stage: displayObject.stage.nativeWindow.minSize = new Point(120,60); From a JavaScript routine running in an HTMLLoader object in a window (or in a root HTML window): window.nativeWindow.minSize = new air.Point(80,60);
flash.display.NativeWindow.systemMinSizeflash.display.NativeWindow.systemMaxSize
minimizable Reports the minimizable setting used to create this window.BooleanWhen trying to set to false without sufficient privilege. SecurityErrorSecurityErrorIf the property is accessed after this window has been closed. IllegalOperationErrorflash.errors:IllegalOperationError Reports the minimizable setting used to create this window.

The minimizable setting cannot be changed after a window is created.

Note: Some Linux window managers allow windows to be minimizable by the user even when the minimizable property is set to false.

flash.display.NativeWindowInitOptions.minimizable
owner The NativeWindow object that owns this window.flash.display:NativeWindow The NativeWindow object that owns this window.

Window ownership is established when a window is created and cannot be changed. To create a window that has an owner, set the owning NativeWindow object as the owner property of the NativeWindowInitOptions object used to create the owned window.

Note: On Linux, some window managers do not display owned windows in front of the owning window when the owner is in fullscreen mode.

flash.display.NativeWindowInitOptions.owner
resizable Reports the resizable setting used to create this window.BooleanWhen trying to set to false without sufficient privilege. SecurityErrorSecurityErrorIf the property is accessed after this window has been closed. IllegalOperationErrorflash.errors:IllegalOperationError Reports the resizable setting used to create this window.

The resizable setting cannot be changed after a window is created.

flash.display.NativeWindowInitOptions.resizable
stage The Stage object for this window.flash.display:Stage The Stage object for this window. The Stage object is the root object in the display list architecture used in ActionScript 3.0-based SWF content.

The stage is the root of the display list for the window. Add visual display objects to a window by adding them to the stage or to another object already in the display list of this stage. The stage dimensions are those of the window client area when the window uses system chrome. The stage dimensions are equal to the dimensions of the window if system chrome is not used.

The following example shows how to set stage properties for a NativeWindow instance: import flash.display.StageAlign; windowObj.stage.align = StageAlign.TOP_LEFT;
flash.display.Stage
supportsMenu Indicates whether AIR supports native window menus on the current computer system.Boolean Indicates whether AIR supports native window menus on the current computer system.

When NativeWindow.supportsMenu is true, a native menu will be displayed for a window when a NativeMenu object is assigned to the window menu property (unless the window systemChrome property is NativeWindowSystemChrome.NONE). Be sure to use the NativeWindow.supportsMenu property to determine whether the operating system native window menus. Using other means (such as Capabilities.os) to determine support can lead to programming errors (if some possible target operating systems are not considered).

Note: Assigning a menu to a window when NativeWindow.supportsMenu is false or when the window systemChrome property is NativeWindowSystemChrome.NONE is allowed, but does nothing.

flash.display.NativeMenuflash.desktop.NativeApplication.supportsMenu
supportsNotification Indicates whether AIR supports window notification cueing on the current computer system.Boolean Indicates whether AIR supports window notification cueing on the current computer system.

When NativeWindow.supportsNotification is true, calling the window's notifyUser() method will result in a visual cue to the user that an event of interest has occurred. This visual cue will conform to the operating system convention of the native system. For example, on Windows®, the task bar icon will flash.

Note: Calling notifyUser() when NativeWindow.supportsNotification is false is allowed, but does nothing.

flash.display.NativeWindow.notifyUser()
supportsTransparency Indicates whether AIR supports native windows with transparent pixels.Boolean Indicates whether AIR supports native windows with transparent pixels.

When NativeWindow.supportsTransparency is true, transparency in pixels of a native window will be honored, if the window transparent property is set to true. Opacity of all pixels will be set to 1 if NativeWindow.supportsTransparency is false, regardless of the value of the window transparent property. Fully transparent pixels will render as black when NativeWindow.supportsTransparency is false. Be sure to use the NativeWindow.supportsTransparency property to determine whether the operating system supports transparency. Using other means (such as Capabilities.os) to determine support can lead to programming errors (if some possible target operating systems are not considered).

Note: The value of this property might change while an application is running, based on user preferences set for the operating system.

flash.display.NativeWindow.transparent
systemChrome Reports the system chrome setting used to create this window.StringWhen trying to set to false without sufficient privilege. SecurityErrorSecurityErrorIf the property is accessed after this window has been closed. IllegalOperationErrorflash.errors:IllegalOperationError Reports the system chrome setting used to create this window.

The values returned by NativeWindow.systemChrome will be one of the constants defined in the NativeWindowSystemChrome class.

The system chrome setting cannot be changed after a window is created.

The following example shows how to get the system chrome type for a window: var sysChromeType:String = windowObj.systemChrome; With a reference to a display object on the window stage: var sysChromeType:String = displayObject.stage.nativeWindow.systemChrome; From a JavaScript routine running in an HTMLLoader object in the window (or root HTML window): var sysChromeType = window.nativeWindow.systemChrome; The following example shows how to change the apparent system chrome and transparency settings by creating a new window and moving all child display objects to the new window: import flash.display.NativeWindow; import flash.display.NativeWindowSystemChrome; import flash.display.NativeWindowInitOptions; public function deChromeWindow(oldWindow:NativeWindow):NativeWindow{ if(oldWindow.systemChrome != NativeWindowSystemChrome.NONE){ var newOptions:NativeWindowInitOptions = new NativeWindowInitOptions(); newOptions.systemChrome = NativeWindowSystemChrome.NONE; newOptions.transparent = true; var newWindow:NativeWindow = new NativeWindow(newOptions); newWindow.stage.stageWidth = oldWindow.stage.stageWidth; newWindow.stage.stageHeight = oldWindow.stage.stageHeight; newWindow.stage.align = oldWindow.stage.align; newWindow.stage.scaleMode = oldWindow.stage.scaleMode; for(var i:int = 0; i < oldWindow.stage.numChildren; i++){ newWindow.stage.addChild(oldWindow.stage.getChildAt(i)); } newWindow.activate(); oldWindow.close(); return newWindow; } return oldWindow; }
flash.display.NativeWindowSystemChromeflash.display.NativeWindowInitOptions.systemChrome
systemMaxSize The largest window size allowed by the operating system.flash.geom:Point The largest window size allowed by the operating system.

The size limit is specified as the coordinates of a Point object. The point x property corresponds to the window width, the y property to the window height.

In addition to the operating system size limit, AIR has a maximum window size limit of 4095 by 4095 pixels (2880 pixels by 2880 pixels in AIR 1.5 and earlier). And an application can set a limit using the maxSize property of the NativeWindow object.

systemMinSize The smallest window size allowed by the operating system.flash.geom:Point The smallest window size allowed by the operating system.

The size limit is specified as the coordinates of a Point object. The point x property corresponds to the window width, the y property to the window height.

title The window title.StringIf the property is accessed after this window has been closed. IllegalOperationErrorflash.errors:IllegalOperationError The window title.

The title will appear in the system chrome for the window, if displayed, as well as in other system-dependent locations (such as the task bar).

The following example sets the title of a window object: windowObj.title = "Window Title";
transparent Reports the transparency setting used to create this window.BooleanWhen trying to set to false without sufficient privilege. SecurityErrorSecurityErrorIf the property is accessed after this window has been closed. IllegalOperationErrorflash.errors:IllegalOperationError Reports the transparency setting used to create this window.

The transparent property cannot be changed after a window is created. Transparency affects both the visual appearance and the mouse behavior of the window. On Windows and Mac OS X, the window will not capture mouse events when the alpha value of the pixel is below a certain threshold, which varies between about .06 and .01 depending on the operating system. On Linux, the the window will capture mouse events above completely transparent areas and therefore will prevent users from accessing other windows and items on the desktop.

Note: Window transparency cannot always be supported. If the user's operating system configuration is such that transparency is not available, the window will be created without transparency. Areas that would have been transparent are composited against black. Use the NativeWindow.supportsTransparency property to determine whether window transparency is supported.

flash.display.NativeWindowInitOptions.transparent
type Reports the window type setting used to create this window.StringWhen trying to set to false without sufficient privilege. SecurityErrorSecurityErrorIf the property is accessed after this window has been closed. IllegalOperationErrorflash.errors:IllegalOperationError Reports the window type setting used to create this window.

The values returned by NativeWindow.type will be one of the constants defined in the NativeWindowType class.

The type setting cannot be changed after a window is created.

flash.display.NativeWindowTypeflash.display.NativeWindowInitOptions.type
visible Specifies whether this window is visible.BooleanWhen trying to set to false without sufficient privilege. SecurityErrorSecurityErrorIf the property is accessed after this window has been closed. IllegalOperationErrorflash.errors:IllegalOperationError Specifies whether this window is visible.

An invisible window is not displayed on the desktop, but all window properties and methods are valid.

By default, visible is set to false. To display a window, set visible to true or call NativeWindow.activate().

If this window has an owner, the visible state of that owning window determines whether this window is displayed. If the owning window is not displayed, then any owned windows are not displayed, even if their visible properties are true.

Note: On Mac OS X, setting visible=false on a minimized window will not remove the window icon from the dock. If a user subsequently clicks the dock icon, the window will return to the visible state and be displayed on the desktop.

The following examples show how to access the visible property of a window: windowObj.visible = true; With a reference to a display object on the window stage: displayObj.stage.nativeWindow.visible = true; From a JavaScript routine running in an HTMLLoader object in the window (or root HTML window): window.nativeWindow.visible = true;
activate()
width The width of this window in pixels.NumberIf the value set is null or invalid. ArgumentErrorArgumentErrorIf the property is accessed after this window has been closed. IllegalOperationErrorflash.errors:IllegalOperationError The width of this window in pixels.

The dimensions reported for a native window include any system window chrome that is displayed. The width of the usable display area inside a window is available from the Stage.stageWidth property.

Changing the width property of a window is equivalent to changing the width through the bounds property.

If the width specified is less than the minimum or greater than the maximum allowed width, then the window width is set to the closest legal size. The factors that determine the minimum and maximum width are the following:

  • The minSize.y and maxSize.y properties of the NativeWindow object
  • The minimum and maximum operating system limits, which are the values of NativeWindow.systemMinSize.y and NativeWindow.systemMaxSize.y.
  • The maximum width of a window in Adobe AIR, which is 4095 pixels (2880 pixels in AIR 1.5 and earlier).

On Linux, setting the width property is an asynchronous operation.

To detect the completion of the width change, listen for the resize event, which is dispatched on all platforms.

Pixel values are rounded to the nearest integer when the width of a window is changed.

flash.display.NativeWindow.boundsflash.display.Stage.stageWidth
x The horizontal axis coordinate of this window's top left corner relative to the origin of the operating system desktop.NumberIf the value set is null or invalid. ArgumentErrorArgumentErrorIf the property is accessed after this window has been closed. IllegalOperationErrorflash.errors:IllegalOperationError The horizontal axis coordinate of this window's top left corner relative to the origin of the operating system desktop.

On systems with more than one monitor, x can be negative. If you save the value, perhaps to reposition a window at its previous location, you should always verify that the window is placed in a usable location when the position is restored. Changes in screen resolution or monitor arrangement can can result in a window being placed off screen. Use the Screen class to obtain information about the desktop geometry.

Changing the x property of a window is equivalent to changing the location through the bounds property.

On Linux, setting the x property is an asynchronous operation.

To detect the completion of the position change, listen for the move event, which is dispatched on all platforms.

Pixel values are rounded to the nearest integer when the x-coordinate of a window is changed.

flash.display.NativeWindow.boundsflash.display.Screen
y The vertical axis coordinate of this window's top left corner relative to the upper left corner of the operating system's desktop.NumberIf the value set is null or invalid. ArgumentErrorArgumentErrorIf the property is accessed after this window has been closed. IllegalOperationErrorflash.errors:IllegalOperationError The vertical axis coordinate of this window's top left corner relative to the upper left corner of the operating system's desktop.

On systems with more than one monitor, y can be negative. If you save the value, perhaps to reposition a window at its previous location, you should always verify that the window is placed in a usable location when the position is restored. Changes in screen resolution or monitor arrangement can can result in a window being placed off screen. Use the Screen class to obtain information about the desktop geometry.

Changing the y property of a window is equivalent to changing the location through the bounds property.

On Linux, setting the y property is an asynchronous operation.

To detect the completion of the position change, listen for the move event, which is dispatched on all platforms.

Pixel values are rounded to the nearest integer when the y-coordinate of a window is changed.

flash.display.NativeWindow.boundsflash.display.Screen
Stage The Stage class represents the main drawing area.flash.display:DisplayObjectContainer The Stage class represents the main drawing area.

For SWF content running in the browser (in Flash® Player), the Stage represents the entire area where Flash content is shown. For content running in AIR on desktop operating systems, each NativeWindow object has a corresponding Stage object.

The Stage object is not globally accessible. You need to access it through the stage property of a DisplayObject instance.

The Stage class has several ancestor classes — DisplayObjectContainer, InteractiveObject, DisplayObject, and EventDispatcher — from which it inherits properties and methods. Many of these properties and methods are either inapplicable to Stage objects, or require security checks when called on a Stage object. The properties and methods that require security checks are documented as part of the Stage class.

In addition, the following inherited properties are inapplicable to Stage objects. If you try to set them, an IllegalOperationError is thrown. These properties may always be read, but since they cannot be set, they will always contain default values.

  • accessibilityProperties
  • alpha
  • blendMode
  • cacheAsBitmap
  • contextMenu
  • filters
  • focusRect
  • loaderInfo
  • mask
  • mouseEnabled
  • name
  • opaqueBackground
  • rotation
  • scale9Grid
  • scaleX
  • scaleY
  • scrollRect
  • tabEnabled
  • tabIndex
  • transform
  • visible
  • x
  • y

Some events that you might expect to be a part of the Stage class, such as enterFrame, exitFrame, frameConstructed, and render, cannot be Stage events because a reference to the Stage object cannot be guaranteed to exist in every situation where these events are used. Because these events cannot be dispatched by the Stage object, they are instead dispatched by every DisplayObject instance, which means that you can add an event listener to any DisplayObject instance to listen for these events. These events, which are part of the DisplayObject class, are called broadcast events to differentiate them from events that target a specific DisplayObject instance. Two other broadcast events, activate and deactivate, belong to DisplayObject's superclass, EventDispatcher. The activate and deactivate events behave similarly to the DisplayObject broadcast events, except that these two events are dispatched not only by all DisplayObject instances, but also by all EventDispatcher instances and instances of other EventDispatcher subclasses. For more information on broadcast events, see the DisplayObject class.

The following example uses the StageExample class to dispatch events whenever the stage is activated or resized. This is accomplished by performing the following steps:
  1. The class constructor first sets the Flash application to be fixed, regardless of the size of the Flash Player window and then adds two event listeners with the activateHandler() and resizeHandler() methods.
  2. The activateHandler() method runs when the left mouse button is clicked.
  3. The resizeHandler() method runs when the stage is resized.
package { import flash.display.Sprite; import flash.display.StageAlign; import flash.display.StageScaleMode; import flash.events.Event; public class StageExample extends Sprite { public function StageExample() { stage.scaleMode = StageScaleMode.NO_SCALE; stage.align = StageAlign.TOP_LEFT; stage.addEventListener(Event.ACTIVATE, activateHandler); stage.addEventListener(Event.RESIZE, resizeHandler); } private function activateHandler(event:Event):void { trace("activateHandler: " + event); } private function resizeHandler(event:Event):void { trace("resizeHandler: " + event); trace("stageWidth: " + stage.stageWidth + " stageHeight: " + stage.stageHeight); } } }
flash.display.DisplayObjectstageVideoAvailability Dispatched by the Stage object when the state of the stageVideos property changes.flash.events.StageVideoAvailabilityEvent.STAGE_VIDEO_AVAILABILITYflash.events.StageVideoAvailabilityEvent Dispatched by the Stage object when the state of the stageVideos property changes. orientationChange Dispatched by the Stage object when the stage orientation changes.flash.events.StageOrientationEvent.ORIENTATION_CHANGEflash.events.StageOrientationEvent Dispatched by the Stage object when the stage orientation changes.

Orientation changes can occur when the user rotates the device, opens a slide-out keyboard, or when the setAspectRatio() is called.

Note: If the autoOrients property is false, then the stage orientation does not change when a device is rotated. Thus, StageOrientationEvents are only dispatched for device rotation when autoOrients is true.

orientationChanging Dispatched by the Stage object when the stage orientation begins changing.flash.events.StageOrientationEvent.ORIENTATION_CHANGINGflash.events.StageOrientationEvent Dispatched by the Stage object when the stage orientation begins changing.

Important: orientationChanging events are not dispatched on Android devices.

Note: If the autoOrients property is false, then the stage orientation does not change when a device is rotated. Thus, StageOrientationEvents are only dispatched for device rotation when autoOrients is true.

fullScreen Dispatched when the Stage object enters, or leaves, full-screen mode.flash.events.FullScreenEvent.FULL_SCREENflash.events.FullScreenEvent Dispatched when the Stage object enters, or leaves, full-screen mode. A change in full-screen mode can be initiated through ActionScript, or the user invoking a keyboard shortcut, or if the current focus leaves the full-screen window. resize Dispatched when the scaleMode property of the Stage object is set to StageScaleMode.NO_SCALE and the SWF file is resized.flash.events.Event.RESIZEflash.events.Event Dispatched when the scaleMode property of the Stage object is set to StageScaleMode.NO_SCALE and the SWF file is resized. mouseLeave Dispatched by the Stage object when the pointer moves out of the stage area.flash.events.Event.MOUSE_LEAVEflash.events.Event Dispatched by the Stage object when the pointer moves out of the stage area. If the mouse button is pressed, the event is not dispatched. addChildAt Adds a child DisplayObject instance to this DisplayObjectContainer instance.Calling the addChildAt() method of a Stage object throws an exception for any caller that is not in the same security sandbox as the Stage owner (the main SWF file). To avoid this, the Stage owner can grant permission to the domain of the caller by calling the Security.allowDomain() method or the Security.allowInsecureDomain() method. For more information, see the "Security" chapter in the ActionScript 3.0 Developer's Guide. SecurityErrorSecurityErrorThe DisplayObject instance that you pass in the child parameter. flash.display:DisplayObjectchildflash.display:DisplayObjectThe DisplayObject instance to add as a child of this DisplayObjectContainer instance. indexintThe index position to which the child is added. If you specify a currently occupied index position, the child object that exists at that position and all higher positions are moved up one position in the child list. Adds a child DisplayObject instance to this DisplayObjectContainer instance. The child is added at the index position specified. An index of 0 represents the back (bottom) of the display list for this DisplayObjectContainer object.

For example, the following example shows three display objects, labeled a, b, and c, at index positions 0, 2, and 1, respectively:

If you add a child object that already has a different display object container as a parent, the object is removed from the child list of the other display object container.

addChild Adds a child DisplayObject instance to this DisplayObjectContainer instance.Calling the addChild() method of a Stage object throws an exception for any caller that is not in the same security sandbox as the Stage owner (the main SWF file). To avoid this, the Stage owner can grant permission to the domain of the caller by calling the Security.allowDomain() method or the Security.allowInsecureDomain() method. For more information, see the "Security" chapter in the ActionScript 3.0 Developer's Guide. SecurityErrorSecurityErrorThe DisplayObject instance that you pass in the child parameter. flash.display:DisplayObjectchildflash.display:DisplayObjectThe DisplayObject instance to add as a child of this DisplayObjectContainer instance. Adds a child DisplayObject instance to this DisplayObjectContainer instance. The child is added to the front (top) of all other children in this DisplayObjectContainer instance. (To add a child to a specific index position, use the addChildAt() method.)

If you add a child object that already has a different display object container as a parent, the object is removed from the child list of the other display object container.

Note: The command stage.addChild() can cause problems with a published SWF file, including security problems and conflicts with other loaded SWF files. There is only one Stage within a Flash runtime instance, no matter how many SWF files you load into the runtime. So, generally, objects should not be added to the Stage, directly, at all. The only object the Stage should contain is the root object. Create a DisplayObjectContainer to contain all of the items on the display list. Then, if necessary, add that DisplayObjectContainer instance to the Stage.

addEventListener Registers an event listener object with an EventDispatcher object so that the listener receives notification of an event.Calling the addEventListener method of a Stage object throws an exception for any caller that is not in the same security sandbox as the Stage owner (the main SWF file). To avoid this situation, the Stage owner can grant permission to the domain of the caller by calling the Security.allowDomain() method or the Security.allowInsecureDomain() method. For more information, see the "Security" chapter in the ActionScript 3.0 Developer's Guide. SecurityErrorSecurityErrortypeStringThe type of event. listenerFunctionThe listener function that processes the event. This function must accept an Event object as its only parameter and must return nothing, as this example shows: function(evt:Event):void

The function can have any name.

useCaptureBooleanfalse Determines whether the listener works in the capture phase or the target and bubbling phases. If useCapture is set to true, the listener processes the event only during the capture phase and not in the target or bubbling phase. If useCapture is false, the listener processes the event only during the target or bubbling phase. To listen for the event in all three phases, call addEventListener twice, once with useCapture set to true, then again with useCapture set to false. priorityint0The priority level of the event listener. The priority is designated by a signed 32-bit integer. The higher the number, the higher the priority. All listeners with priority n are processed before listeners of priority n-1. If two or more listeners share the same priority, they are processed in the order in which they were added. The default priority is 0. useWeakReferenceBooleanfalseDetermines whether the reference to the listener is strong or weak. A strong reference (the default) prevents your listener from being garbage-collected. A weak reference does not.

Class-level member functions are not subject to garbage collection, so you can set useWeakReference to true for class-level member functions without subjecting them to garbage collection. If you set useWeakReference to true for a listener that is a nested inner function, the function will be garbage-collected and no longer persistent. If you create references to the inner function (save it in another variable) then it is not garbage-collected and stays persistent.

Registers an event listener object with an EventDispatcher object so that the listener receives notification of an event. You can register event listeners on all nodes in the display list for a specific type of event, phase, and priority.

After you successfully register an event listener, you cannot change its priority through additional calls to addEventListener(). To change a listener's priority, you must first call removeListener(). Then you can register the listener again with the new priority level.

Keep in mind that after the listener is registered, subsequent calls to addEventListener() with a different type or useCapture value result in the creation of a separate listener registration. For example, if you first register a listener with useCapture set to true, it listens only during the capture phase. If you call addEventListener() again using the same listener object, but with useCapture set to false, you have two separate listeners: one that listens during the capture phase and another that listens during the target and bubbling phases.

You cannot register an event listener for only the target phase or the bubbling phase. Those phases are coupled during registration because bubbling applies only to the ancestors of the target node.

If you no longer need an event listener, remove it by calling removeEventListener(), or memory problems could result. Event listeners are not automatically removed from memory because the garbage collector does not remove the listener as long as the dispatching object exists (unless the useWeakReference parameter is set to true).

Copying an EventDispatcher instance does not copy the event listeners attached to it. (If your newly created node needs an event listener, you must attach the listener after creating the node.) However, if you move an EventDispatcher instance, the event listeners attached to it move along with it.

If the event listener is being registered on a node while an event is being processed on this node, the event listener is not triggered during the current phase but can be triggered during a later phase in the event flow, such as the bubbling phase.

If an event listener is removed from a node while an event is being processed on the node, it is still triggered by the current actions. After it is removed, the event listener is never invoked again (unless registered again for future processing).

assignFocus Sets keyboard focus to the interactive object specified by objectToFocus, with the focus direction specified by the direction parameter.If focus cannot be set to the target or direction is not a valid type. ErrorErrorobjectToFocusflash.display:InteractiveObjectThe object to focus, or null to clear the focus from any element on the Stage. directionStringThe direction from which objectToFocus is being focused. Valid values are enumerated as constants in the FocusDirection class. Assigns keyboard focus to an interactive object and specifies the direction focus is coming from. Sets keyboard focus to the interactive object specified by objectToFocus, with the focus direction specified by the direction parameter.

The concept of focus direction must be defined by the application (or application framework). No intrinsic focus sorting of interactive objects exists, although you could use other available properties to establish an ordering principle. For example, you could sort interactive objects according to their positions on the Stage or in the display list. Calling assignFocus() is equivalent to setting the Stage.focus property, with the additional ability to indicate the direction from which the focus is being set.

The objectToFocus will dispatch a focusIn event on receiving focus. The direction property of the FocusEvent object will report the setting of the direction parameter.

If you assign an HTMLLoader object to the objectToFocus parameter, the HTMLLoader object selects the appropriate focusable object in the HTML DOM, based on the direction parameter value. If it is FocusDirection.BOTTOM, the focusable object in the HTML DOM at the end of the reading order is given focus. If it is FocusDirection.TOP, the focusable object in the HTML DOM at the beginning of the reading order is given focus. If it is NONE, the HTMLLoader object receives focus without changing its current focused element.

flash.display.Stage.focusflash.display.FocusDirectionflash.events.FocusEvent
dispatchEvent Dispatches an event into the event flow.Calling the dispatchEvent() method of a Stage object throws an exception for any caller that is not in the same security sandbox as the Stage owner (the main SWF file). To avoid this, the Stage owner can grant permission to the domain of the caller by calling the Security.allowDomain() method or the Security.allowInsecureDomain() method. For more information, see the "Security" chapter in the ActionScript 3.0 Developer's Guide. SecurityErrorSecurityErrorA value of true if the event was successfully dispatched. A value of false indicates failure or that preventDefault() was called on the event. Booleaneventflash.events:EventThe Event object that is dispatched into the event flow. If the event is being redispatched, a clone of the event is created automatically. After an event is dispatched, its target property cannot be changed, so you must create a new copy of the event for redispatching to work. Dispatches an event into the event flow. The event target is the EventDispatcher object upon which the dispatchEvent() method is called. getChildAtflash.display:DisplayObjectindexintgetChildIndexintchildflash.display:DisplayObjecthasEventListener Checks whether the EventDispatcher object has any listeners registered for a specific type of event.Calling the hasEventListener() method of a Stage object throws an exception for any caller that is not in the same security sandbox as the Stage owner (the main SWF file). To avoid this, the Stage owner can grant permission to the domain of the caller by calling the Security.allowDomain() method or the Security.allowInsecureDomain() method. For more information, see the "Security" chapter in the ActionScript 3.0 Developer's Guide. SecurityErrorSecurityErrorA value of true if a listener of the specified type is registered; false otherwise. BooleantypeStringThe type of event. Checks whether the EventDispatcher object has any listeners registered for a specific type of event. This allows you to determine where an EventDispatcher object has altered handling of an event type in the event flow hierarchy. To determine whether a specific event type actually triggers an event listener, use willTrigger().

The difference between hasEventListener() and willTrigger() is that hasEventListener() examines only the object to which it belongs, whereas willTrigger() examines the entire event flow for the event specified by the type parameter.

When hasEventListener() is called from a LoaderInfo object, only the listeners that the caller can access are considered.

invalidate Calling the invalidate() method signals Flash runtimes to alert display objects on the next opportunity it has to render the display list (for example, when the playhead advances to a new frame).Signals Flash runtimes to update properties of display objects on the next opportunity it has to refresh the Stage. Calling the invalidate() method signals Flash runtimes to alert display objects on the next opportunity it has to render the display list (for example, when the playhead advances to a new frame). After you call the invalidate() method, when the display list is next rendered, the Flash runtime sends a render event to each display object that has registered to listen for the render event. You must call the invalidate() method each time you want the Flash runtime to send render events.

The render event gives you an opportunity to make changes to the display list immediately before it is actually rendered. This lets you defer updates to the display list until the latest opportunity. This can increase performance by eliminating unnecessary screen updates.

The render event is dispatched only to display objects that are in the same security domain as the code that calls the stage.invalidate() method, or to display objects from a security domain that has been granted permission via the Security.allowDomain() method.

flash.events.Event.RENDER
isFocusInaccessible Determines whether the Stage.focus property returns null for security reasons.true if the object that has focus belongs to a security sandbox to which the SWF file does not have access. BooleanDetermines whether the Stage.focus property would return null for security reasons. Determines whether the Stage.focus property returns null for security reasons. In other words, isFocusInaccessible returns true if the object that has focus belongs to a security sandbox to which the SWF file does not have access. removeChildAt Removes a child DisplayObject from the specified index position in the child list of the DisplayObjectContainer.Calling the removeChildAt() method of a Stage object throws an exception for any caller that is not in the same security sandbox as the object to be removed. To avoid this, the owner of that object can grant permission to the domain of the caller by calling the Security.allowDomain() method or the Security.allowInsecureDomain() method. For more information, see the "Security" chapter in the ActionScript 3.0 Developer's Guide. SecurityErrorSecurityErrorThe DisplayObject instance that was removed. flash.display:DisplayObjectindexintThe child index of the DisplayObject to remove. Removes a child DisplayObject from the specified index position in the child list of the DisplayObjectContainer. The parent property of the removed child is set to null, and the object is garbage collected if no other references to the child exist. The index positions of any display objects above the child in the DisplayObjectContainer are decreased by 1.

The garbage collector reallocates unused memory space. When a variable or object is no longer actively referenced or stored somewhere, the garbage collector sweeps through and wipes out the memory space it used to occupy if no other references to it exist.

removeChildflash.display:DisplayObjectchildflash.display:DisplayObjectsetAspectRatio Sets the stage to an orientation with the specified aspect ratio.The value passed as the newAspectRatio parameter is not valid. The value must match one of the constants defined in the StageAspectRatio class. ArgumentErrorArgumentErrornewAspectRatioStringThe type code for the desired aspect ratio (StageAspectRatio.PORTRAIT or StageAspectRatio.LANDSCAPE). Sets the stage to an orientation with the specified aspect ratio.

If the stage orientation changes as a result of the method call, the Stage object dispatches an orientationChange event.

To check whether device orientation is supported, check the value of the Stage.supportsOrientantionChange property.

AIR profile support: This feature is supported on mobile devices, but it is not supported on desktop operating systems or AIR for TV devices. You can test for support at run time using the Stage.supportsOrientantionChange property. See AIR Profile Support for more information regarding API support across multiple profiles.

StageAspectRatiosupportsOrientationChange
setChildIndex Changes the position of an existing child in the display object container.Calling the setChildIndex() method of a Stage object throws an exception for any caller that is not in the same security sandbox as the Stage owner (the main SWF file). To avoid this, the Stage owner can grant permission to the domain of the caller by calling the Security.allowDomain() method or the Security.allowInsecureDomain() method. For more information, see the "Security" chapter in the ActionScript 3.0 Developer's Guide. SecurityErrorSecurityErrorchildflash.display:DisplayObjectThe child DisplayObject instance for which you want to change the index number. indexintThe resulting index number for the child display object. Changes the position of an existing child in the display object container. This affects the layering of child objects. For example, the following example shows three display objects, labeled a, b, and c, at index positions 0, 1, and 2, respectively:

When you use the setChildIndex() method and specify an index position that is already occupied, the only positions that change are those in between the display object's former and new position. All others will stay the same. If a child is moved to an index LOWER than its current index, all children in between will INCREASE by 1 for their index reference. If a child is moved to an index HIGHER than its current index, all children in between will DECREASE by 1 for their index reference. For example, if the display object container in the previous example is named container, you can swap the position of the display objects labeled a and b by calling the following code:

container.setChildIndex(container.getChildAt(1), 0);

This code results in the following arrangement of objects:

setOrientation Sets the stage to the specified orientation.The value passed as the newOrientation parameter is not valid. The value must match one of the constants defined in the StageOriention class, except for the StageOrientation.UNKNOWN constant. ArgumentErrorArgumentErrornewOrientationStringThe new orientation of the stage. Sets the stage to the specified orientation.

Set the newOrientation parameter to one of the following four values defined as constants in the StageOrientation class:

StageOrientation constantStage orientationStageOrientation.DEFAULTSet the stage orientation to the default orientation (right-side up).StageOrientation.ROTATED_RIGHTSet the stage orientation to be rotated right.StageOrientation.ROTATED_LEFTSet the stage orientation to be rotated left.StageOrientation.UPSIDE_DOWNSet the stage orientation to be rotated upside down.

Do not set the parameter to StageOrientation.UNKNOWN or any string value other than those listed in the table.

To check whether changing device orientation is supported, check the value of the Stage.supportsOrientantionChange property. Check the list provided by the supportedOrientations property to determine which orientations are supported by the current device.

Setting the orientation is an asynchronous operation. It is not guaranteed to be complete immediately after you call the setOrientation() method. Add an event listener for the orientationChange event to determine when the orientation change is complete.

Important: The setOrientation() method was not supported on Android devices before AIR 2.6.

autoOrientssupportsOrientationChangeStageOrientationEventStageOrientationorientationChangeflash.events:StageOrientationEventThe stage has resized as a result of the call to the setOrientation() method. The stage has resized as a result of the call to the setOrientation() method.
swapChildrenAtindex1intindex2intswapChildren Swaps the z-order (front-to-back order) of the two specified child objects.Calling the swapChildrenAt() method of a Stage object throws an exception for any caller that is not in the same security sandbox as the owner of either of the objects to be swapped. To avoid this, the object owners can grant permission to the domain of the caller by calling the Security.allowDomain() method or the Security.allowInsecureDomain() method. For more information, see the "Security" chapter in the ActionScript 3.0 Developer's Guide. SecurityErrorSecurityErrorchild1flash.display:DisplayObjectThe first child object. child2flash.display:DisplayObjectThe second child object. Swaps the z-order (front-to-back order) of the two specified child objects. All other child objects in the display object container remain in the same index positions. willTrigger Checks whether an event listener is registered with this EventDispatcher object or any of its ancestors for the specified event type.Calling the willTrigger() method of a Stage object throws an exception for any caller that is not in the same security sandbox as the Stage owner (the main SWF file). To avoid this, the Stage owner can grant permission to the domain of the caller by calling the Security.allowDomain() method or the Security.allowInsecureDomain() method. For more information, see the "Security" chapter in the ActionScript 3.0 Developer's Guide. SecurityErrorSecurityErrorA value of true if a listener of the specified type will be triggered; false otherwise. BooleantypeStringThe type of event. Checks whether an event listener is registered with this EventDispatcher object or any of its ancestors for the specified event type. This method returns true if an event listener is triggered during any phase of the event flow when an event of the specified type is dispatched to this EventDispatcher object or any of its descendants.

The difference between the hasEventListener() and the willTrigger() methods is that hasEventListener() examines only the object to which it belongs, whereas the willTrigger() method examines the entire event flow for the event specified by the type parameter.

When willTrigger() is called from a LoaderInfo object, only the listeners that the caller can access are considered.

align A value from the StageAlign class that specifies the alignment of the stage in Flash Player or the browser.String A value from the StageAlign class that specifies the alignment of the stage in Flash Player or the browser. The following are valid values:

ValueVertical AlignmentHorizontalStageAlign.TOPTopCenterStageAlign.BOTTOMBottomCenterStageAlign.LEFTCenterLeftStageAlign.RIGHTCenterRightStageAlign.TOP_LEFTTopLeftStageAlign.TOP_RIGHTTopRightStageAlign.BOTTOM_LEFTBottomLeftStageAlign.BOTTOM_RIGHTBottomRight

The align property is only available to an object that is in the same security sandbox as the Stage owner (the main SWF file). To avoid this, the Stage owner can grant permission to the domain of the calling object by calling the Security.allowDomain() method or the Security.alowInsecureDomain() method. For more information, see the "Security" chapter in the ActionScript 3.0 Developer's Guide.

flash.display.StageAlign
allowsFullScreen Specifies whether this stage allows the use of the full screen mode Boolean Specifies whether this stage allows the use of the full screen mode autoOrients Specifies whether the stage automatically changes orientation when the device orientation changes.Boolean Specifies whether the stage automatically changes orientation when the device orientation changes.

The initial value of this property is derived from the autoOrients element of the application descriptor and defaults to false. When changing the property to false, the behavior is not guaranteed. On some devices, the stage remains in the current orientation. On others, the stage orientation changes to a device-defined "standard" orientation, after which, no further stage orientation changes occur.

AIR profile support: This feature is supported on mobile devices, but it is not supported on desktop operating systems or AIR for TV devices. You can test for support at run time using the Stage.supportsOrientantionChange property. See AIR Profile Support for more information regarding API support across multiple profiles.

deviceOrientationsupportsOrientationChange
colorCorrectionSupport Specifies whether the Flash runtime is running on an operating system that supports color correction and whether the color profile of the main (primary) monitor can be read and understood by the Flash runtime.String Specifies whether the Flash runtime is running on an operating system that supports color correction and whether the color profile of the main (primary) monitor can be read and understood by the Flash runtime. This property also returns the default state of color correction on the host system (usually the browser). Currently the return values can be:

The three possible values are strings with corresponding constants in the flash.display.ColorCorrectionSupport class:

  • "unsupported": Color correction is not available.
  • "defaultOn": Always performs color correction.
  • "defaultOff": Never performs color correction.
The following example shows an event handler that populates a text field with the current environment's ability to support color correction or not. First, it checks the value of stage.colorCorrectionSupport to see if it is DEFAULT_ON or DEFAULT_OFF, values from the ColorCorrectionSupport class. If the property is either value, then the text field displays the current value. Otherwise, if the value is neither DEFAULT_ON nor DEFAULT_OFF, the text field displays "unsupported". function addHandler(add_event:Event) { if (stage.colorCorrectionSupport == ColorCorrectionSupport.DEFAULT_ON || stage.colorCorrectionSupport == ColorCorrectionSupport.DEFAULT_OFF) { lblHasCM.text = "stage.colorCorrectionSupport: " + stage.colorCorrectionSupport; } else { lblHasCM.text = "stage.colorCorrectionSupport: unsupported"; } }
flash.display.ColorCorrectionSupportcolorCorrection
colorCorrection Controls Flash runtime color correction for displays.StringAttempts to use monitor color correction Controls Flash runtime color correction for displays. Color correction works only if the main monitor is assigned a valid ICC color profile, which specifies the device's particular color attributes. By default, the Flash runtime tries to match the color correction of its host (usually a browser).

Use the Stage.colorCorrectionSupport property to determine if color correction is available on the current system and the default state. . If color correction is available, all colors on the stage are assumed to be in the sRGB color space, which is the most standard color space. Source profiles of input devices are not considered during color correction. No input color correction is applied; only the stage output is mapped to the main monitor's ICC color profile.

In general, the benefits of activating color management include predictable and consistent color, better conversion, accurate proofing and more efficient cross-media output. Be aware, though, that color management does not provide perfect conversions due to devices having a different gamut from each other or original images. Nor does color management eliminate the need for custom or edited profiles. Color profiles are dependent on browsers, operating systems (OS), OS extensions, output devices, and application support.

Applying color correction degrades the Flash runtime performance. A Flash runtime's color correction is document style color correction because all SWF movies are considered documents with implicit sRGB profiles. Use the Stage.colorCorrectionSupport property to tell the Flash runtime to correct colors when displaying the SWF file (document) to the display color space. Flash runtimes only compensates for differences between monitors, not for differences between input devices (camera/scanner/etc.).

The three possible values are strings with corresponding constants in the flash.display.ColorCorrection class:

  • "default": Use the same color correction as the host system.
  • "on": Always perform color correction.
  • "off": Never perform color correction.
The following example shows an event handler that toggles color correction in the current SWF file and populates a text field with the current state of color correction. If the Stage.colorCorrection value is not a value from the ColorCorrection class, then the handler reports an error. function addHandler(add_event:Event) { switch(stage.colorCorrection) { case ColorCorrection.ON: stage.colorCorrection = ColorCorrection.OFF; lblCMEnableState.text = "State: " + stage.colorCorrection; break; case ColorCorrection.OFF: stage.colorCorrection = ColorCorrection.DEFAULT; lblCMEnableState.text = "State: " + stage.colorCorrection; break; case ColorCorrection.DEFAULT: stage.colorCorrection = ColorCorrection.ON; lblCMEnableState.text = "State: " + stage.colorCorrection; break; default: lblCMEnableState.text = "Error."; break; }
flash.display.ColorCorrectioncolorCorrectionSupport
coloruintdeviceOrientation The physical orientation of the device.String The physical orientation of the device.

On devices with slide-out keyboards, the state of the keyboard has a higher priority in determining the device orientation than the rotation detected by the accelerometer. Thus on a portrait-aspect device with a side-mounted keyboard, the deviceOrientation property will report ROTATED_LEFT when the keyboard is open no matter how the user is holding the device.

Use the constants defined in the StageOrientation class when setting or comparing values for this property.

AIR profile support: This feature is supported on mobile devices, but it is not supported on desktop operating systems or AIR for TV devices. You can test for support at run time using the Stage.supportsOrientationChange property. See AIR Profile Support for more information regarding API support across multiple profiles.

autoOrientsStageOrientation
displayState A value from the StageDisplayState class that specifies which display state to use.StringCalling the displayState property of a Stage object throws an exception for any caller that is not in the same security sandbox as the Stage owner (the main SWF file). To avoid this, the Stage owner can grant permission to the domain of the caller by calling the Security.allowDomain() method or the Security.allowInsecureDomain() method. For more information, see the "Security" chapter in the ActionScript 3.0 Developer's Guide. Trying to set the displayState property while the settings dialog is displayed, without a user response, or if the param or embed HTML tag's allowFullScreen attribute is not set to true throws a security error. SecurityErrorSecurityError A value from the StageDisplayState class that specifies which display state to use. The following are valid values:
  • StageDisplayState.FULL_SCREEN Sets AIR application or Flash runtime to expand the stage over the user's entire screen, with keyboard input disabled.
  • StageDisplayState.FULL_SCREEN_INTERACTIVE Sets the AIR application to expand the stage over the user's entire screen, with keyboard input allowed. (Not available for content running in Flash Player.)
  • StageDisplayState.NORMAL Sets the Flash runtime back to the standard stage display mode.

The scaling behavior of the movie in full-screen mode is determined by the scaleMode setting (set using the Stage.scaleMode property or the SWF file's embed tag settings in the HTML file). If the scaleMode property is set to noScale while the application transitions to full-screen mode, the Stage width and height properties are updated, and the Stage dispatches a resize event. If any other scale mode is set, the stage and its contents are scaled to fill the new screen dimensions. The Stage object retains its original width and height values and does not dispatch a resize event.

The following restrictions apply to SWF files that play within an HTML page (not those using the stand-alone Flash Player or not running in the AIR runtime):

  • To enable full-screen mode, add the allowFullScreen parameter to the object and embed tags in the HTML page that includes the SWF file, with allowFullScreen set to "true", as shown in the following example: <param name="allowFullScreen" value="true" /> ... <embed src="example.swf" allowFullScreen="true" ... >

    An HTML page may also use a script to generate SWF-embedding tags. You need to alter the script so that it inserts the proper allowFullScreen settings. HTML pages generated by Flash Professional and Flash Builder use the AC_FL_RunContent() function to embed references to SWF files, and you need to add the allowFullScreen parameter settings, as in the following:

    AC_FL_RunContent( ... "allowFullScreen", "true", ... )
  • Full-screen mode is initiated in response to a mouse click or key press by the user; the movie cannot change Stage.displayState without user input. Flash runtimes restrict keyboard input in full-screen mode. Acceptable keys include keyboard shortcuts that terminate full-screen mode and non-printing keys such as arrows, space, Shift, and Tab keys. Keyboard shortcuts that terminate full-screen mode are: Escape (Windows, Linux, and Mac), Control+W (Windows), Command+W (Mac), and Alt+F4.

    A Flash runtime dialog box appears over the movie when users enter full-screen mode to inform the users they are in full-screen mode and that they can press the Escape key to end full-screen mode.

  • Starting with Flash Player 9.0.115.0, full-screen works the same in windowless mode as it does in window mode. If you set the Window Mode (wmode in the HTML) to Opaque Windowless (opaque) or Transparent Windowless (transparent), full-screen can be initiated, but the full-screen window will always be opaque.

These restrictions are not present for SWF content running in the stand-alone Flash Player or in AIR. AIR supports an interactive full-screen mode which allows keyboard input.

For AIR content running in full-screen mode, the system screen saver and power saving options are disabled while video content is playing and until either the video stops or full-screen mode is exited.

On Linux, setting displayState to StageDisplayState.FULL_SCREEN or StageDisplayState.FULL_SCREEN_INTERACTIVE is an asynchronous operation.

The following example creates an interactive demonstration of how to create a fullscreen experience by modifying the displayState property.

Note: Fullscreen can only be triggered in certain situations, such as if the user has clicked or pressed a key, due to security restrictions. When run in a browser, the allowFullScreen property must be set to true.

package { import flash.display.Sprite; import flash.display.Stage; import flash.events.*; import flash.net.NetConnection; import flash.net.NetStream; import flash.media.Video; public class FullScreenExample extends Sprite { private var videoURL:String = "testVideo.flv"; private var connection:NetConnection; private var stream:NetStream; private var video:Video; public function FullScreenExample() { connection = new NetConnection(); connection.addEventListener(NetStatusEvent.NET_STATUS, netStatusHandler); connection.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler); connection.connect(null); loaderInfo.addEventListener(Event.INIT, createMouseListener); } private function createMouseListener(event:Event):void { stage.addEventListener(MouseEvent.CLICK,toggleFullScreen); } private function toggleFullScreen(event:MouseEvent):void { switch(stage.displayState) { case "normal": stage.displayState = "fullScreen"; break; case "fullScreen": default: stage.displayState = "normal"; break; } } // Video related: private function netStatusHandler(event:NetStatusEvent):void { switch (event.info.code) { case "NetConnection.Connect.Success": connectStream(); break; case "NetStream.Play.StreamNotFound": trace("Unable to locate video: " + videoURL); break; } } private function connectStream():void { var stream:NetStream = new NetStream(connection); stream.addEventListener(NetStatusEvent.NET_STATUS, netStatusHandler); stream.addEventListener(AsyncErrorEvent.ASYNC_ERROR, asyncErrorHandler); video = new Video(stage.stageWidth,stage.stageHeight); video.attachNetStream(stream); stream.play(videoURL); addChild(video); } private function securityErrorHandler(event:SecurityErrorEvent):void { trace("securityErrorHandler: " + event); } private function asyncErrorHandler(event:AsyncErrorEvent):void { // ignore AsyncErrorEvent events. } } }
flash.display.StageDisplayStateStage.scaleModeflash.events.FullScreenEventflash.events.Event.RESIZE
focus The interactive object with keyboard focus; or null if focus is not set or if the focused object belongs to a security sandbox to which the calling object does not have access.flash.display:InteractiveObjectThrows an error if focus cannot be set to the target. ErrorErrorThe object with keyboard focus. The interactive object with keyboard focus; or null if focus is not set or if the focused object belongs to a security sandbox to which the calling object does not have access. The following sets the initial focus to the text field myTF so the user can start typing without having to click anything. If you test this code within the authoring tool interface, you can only have access to a few keys because the host (browser or tool) interprets most key presses first. To see this example work as intended, compile it and run the SWF file. var myTF:TextField = new TextField(); myTF.border =true; myTF.type = TextFieldType.INPUT; addChild(myTF); stage.focus= myTF; frameRate Gets and sets the frame rate of the stage.NumberCalling the frameRate property of a Stage object throws an exception for any caller that is not in the same security sandbox as the Stage owner (the main SWF file). To avoid this, the Stage owner can grant permission to the domain of the caller by calling the Security.allowDomain() method or the Security.allowInsecureDomain() method. For more information, see the "Security" chapter in the ActionScript 3.0 Developer's Guide. SecurityErrorSecurityError Gets and sets the frame rate of the stage. The frame rate is defined as frames per second. By default the rate is set to the frame rate of the first SWF file loaded. Valid range for the frame rate is from 0.01 to 1000 frames per second.

Note: An application might not be able to follow high frame rate settings, either because the target platform is not fast enough or the player is synchronized to the vertical blank timing of the display device (usually 60 Hz on LCD devices). In some cases, a target platform might also choose to lower the maximum frame rate if it anticipates high CPU usage.

For content running in Adobe AIR, setting the frameRate property of one Stage object changes the frame rate for all Stage objects (used by different NativeWindow objects).

fullScreenHeight Returns the height of the monitor that will be used when going to full screen size, if that state is entered immediately.uint Returns the height of the monitor that will be used when going to full screen size, if that state is entered immediately. If the user has multiple monitors, the monitor that's used is the monitor that most of the stage is on at the time.

Note: If the user has the opportunity to move the browser from one monitor to another between retrieving the value and going to full screen size, the value could be incorrect. If you retrieve the value in an event handler that sets Stage.displayState to StageDisplayState.FULL_SCREEN, the value will be correct.

This is the pixel height of the monitor and is the same as the stage height would be if Stage.align is set to StageAlign.TOP_LEFT and Stage.scaleMode is set to StageScaleMode.NO_SCALE.

This example creates a green rectangle the size of the stage and places a red square on it that it activates as a button. Clicking the red square triggers the enterFullScreen() event handler, which sets the fullScreenSourceRect property and enters full screen mode. To set the fullScreenSourceRect property, the event handler starts with the location and dimensions of the red square. It then compares the aspect ratio (width divided by height) of the red square to the aspect ratio of the stage at full screen width and height so that it can expand the rectangle (fullScreenSourceRect) to match the screen's aspect ratio. The result is that the red square occupies the entire height of the monitor with the green background visible on each side. If the aspect ratio was not matched, the stage background color, which is white by default, would show on each side instead of the green background.

Note: Test this example in the browser. In the Flash Publish Settings dialog, on the HTML tab, select the template Flash Only - Allow Full Screen. Specify the Flash Player version 9.0.115.0, and make sure the Flash and HTML formats are selected on the Formats tab. Then publish and open the resulting HTML file in the browser.

import flash.display.Sprite; import flash.display.Stage; import flash.display.StageDisplayState; import flash.events.MouseEvent; import flash.geom.Rectangle; // cover the stage with a green rectangle var greenRect:Sprite = new Sprite(); greenRect.graphics.beginFill(0x00FF00); greenRect.graphics.drawRect(0, 0, stage.stageWidth, stage.stageHeight); addChild(greenRect); // create red square on stage, turn it into a button for going to full screen var redSquare:Sprite = new Sprite(); redSquare.graphics.beginFill(0xFF0000); redSquare.graphics.drawRect(0, 0, 300, 300); redSquare.x = 50; redSquare.y = 50; redSquare.addEventListener(MouseEvent.CLICK, enterFullScreen); redSquare.buttonMode = true; addChild(redSquare); function enterFullScreen(e:MouseEvent):void { // we will go to full screen zoomed in on the red square var redSquare:Sprite = e.target as Sprite; var fullScreenRect:Rectangle = new Rectangle(redSquare.x, redSquare.y, redSquare.width, redSquare.height); // calculate aspect ratio of the red square var rectAspectRatio:Number = fullScreenRect.width / fullScreenRect.height; // calculate aspect ratio of the screen var screenAspectRatio:Number = stage.fullScreenWidth / stage.fullScreenHeight; // change the fullScreenRect so that it covers the entire screen, keeping it centered on the redSquare // try commenting out this section to see what happens if you do not fix the aspect ratio. if (rectAspectRatio > screenAspectRatio) { var newHeight:Number = fullScreenRect.width / screenAspectRatio; fullScreenRect.y -= ((newHeight - fullScreenRect.height) / 2); fullScreenRect.height = newHeight; } else if (rectAspectRatio < screenAspectRatio) { var newWidth:Number = fullScreenRect.height * screenAspectRatio; fullScreenRect.x -= ((newWidth - fullScreenRect.width) / 2); fullScreenRect.width = newWidth; } // go to full screen stage.fullScreenSourceRect = fullScreenRect; stage.displayState = StageDisplayState.FULL_SCREEN; }
displayStatefullScreenSourceRectfullScreenWidthscaleModeStageDisplayStateflash.events.Event.RESIZEflash.events.FullScreenEvent
fullScreenSourceRect Sets the Flash runtime to scale a specific region of the stage to full-screen mode.flash.geom:Rectangle Sets the Flash runtime to scale a specific region of the stage to full-screen mode. If available, the Flash runtime scales in hardware, which uses the graphics and video card on a user's computer, and generally displays content more quickly than software scaling.

When this property is set to a valid rectangle and the displayState property is set to full-screen mode, the Flash runtime scales the specified area. The actual Stage size in pixels within ActionScript does not change. The Flash runtime enforces a minimum limit for the size of the rectangle to accommodate the standard "Press Esc to exit full-screen mode" message. This limit is usually around 260 by 30 pixels but can vary on platform and Flash runtime version.

This property can only be set when the Flash runtime is not in full-screen mode. To use this property correctly, set this property first, then set the displayState property to full-screen mode, as shown in the code examples.

To enable scaling, set the fullScreenSourceRect property to a rectangle object:

// valid, will enable hardware scaling stage.fullScreenSourceRect = new Rectangle(0,0,320,240);

To disable scaling, set the fullScreenSourceRect=null in ActionScript 3.0, and undefined in ActionScript 2.0.

stage.fullScreenSourceRect = null;

The end user also can select within Flash Player Display Settings to turn off hardware scaling, which is enabled by default. For more information, see www.adobe.com/go/display_settings.

To take advantage of hardware scaling, you set the whole stage or part of the stage to full-screen mode. The following ActionScript 3.0 code sets the whole stage to full-screen mode: import flash.geom.*; { stage.fullScreenSourceRect = new Rectangle(0,0,320,240); stage.displayState = StageDisplayState.FULL_SCREEN; } In the following example, the user can switch between playing a video in full or normal screen mode by clicking on the stage. If the SWF for this example is running in Flash Player 9.0.115.0 or later, then it will use hardware acceleration to improve the full-screen scaling of the display.

Before using the full-screen mode with hardware scaling, the following conditions must be met:

  1. Flash Player version 9.0.115.0 or later is needed, as well as an authoring tool that supports it.
  2. HTML templates need to be modified to support full screen. The allowFullScreen attribute must be set to true for the object and embed tag. (The scripts that generate SWF-embedding tags must also allow for full screen.) For sample of files that can be used for Flash Builder, see the article, Exploring full-screen mode in Flash Player 9.
  3. Your application must have permission and access to an FLV video file. In this example, it is assumed that Flash Video (FLV) file is in the same directory as the SWF file.
  4. The user must allow access to full screen.
  5. For additional information on hardware scaling, see the article Exploring Flash Player support for high-definition H.264 video and AAC audio for Flash Player.

An FLV file is loaded using NetConnection and NetStream objects. Since the FLV file is in the same directory as the SWF file and will connect via HTTP, the NetConnection.connect() method's parameter is set to null. The connect NetConnection object reports its status by dispatching a netStatus event which invokes the netStatusHandler() method. The netStatusHandler() method checks if the connection was successful and invokes connectStream() method, which creates a NetStream object that takes the NetConnection object as a parameter. It also creates a video object and attached the NetStream object to the video object. The video object then is added to the display list and the stream is set to play. Since the FLV video file does not contain metadata or cue point information, an AsyncError event will be dispatched. A listener must be set up to handle the event. Here the listener is set up and it ignores the event. Another listener for netStatus event is also set up for the NetStream object. It will display an error message if the stream was not found. (Note that netStatusHandler() could be used to handle any number of different status information reported for the stream or connection.)

When the properties and methods of a loaded SWF file are accessible, the createMouseListener() method is invoked. It sets up an event listener for when the mouse is clicked on the stage. The toggleFullScreen() method checks if the display state is in the full or normal screen mode. If it is normal, the size of the video object is set to the size of the video stream. The fullScreenSourceRect property is set to a rectangle matching the dimensions of the video object. Then the Stage.displayMode property is set to full screen, which causes the video in the source rectangle to expand to fill the full screen area. If system requirements are met, the machine's graphics hardware will be used to improve the performance of the full-screen video rendering and the display state is set to full-screen mode. In order to catch any security error that may occur while switching to the full-screen mode, a try...catch is used. (Note that the display state must be set to full-screen mode after the fullScreenSourceRect property is set.) Before switching to the normal-screen mode, the video object's width and height are set back to the saved original video object's width and height. Otherwise, the changes made to the video object for the full-screen mode will determine the width and height.

package { import flash.display.Sprite; import flash.display.StageDisplayState; import flash.media.Video; import flash.net.NetConnection; import flash.net.NetStream; import flash.events.NetStatusEvent; import flash.events.AsyncErrorEvent; import flash.events.SecurityErrorEvent; import flash.events.MouseEvent; import flash.events.Event; import flash.geom.Rectangle; public class Stage_fullScreenSourceRectExample2 extends Sprite { private var videoURL:String = "testVideo1.flv"; private var connection:NetConnection; private var stream:NetStream; private var myVideo:Video; private var savedWidth:uint; private var savedHeight:uint; public function Stage_fullScreenSourceRectExample2() { connection = new NetConnection(); connection.addEventListener(NetStatusEvent.NET_STATUS, netStatusHandler); connection.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler); connection.connect(null); loaderInfo.addEventListener(Event.INIT, createMouseListener); } private function createMouseListener(event:Event):void { stage.addEventListener(MouseEvent.CLICK, toggleFullScreen); } private function toggleFullScreen(event:MouseEvent):void { if(stage.displayState == StageDisplayState.NORMAL) { myVideo.width = myVideo.videoWidth; myVideo.height = myVideo.videoHeight; try { stage.fullScreenSourceRect = new Rectangle(myVideo.x, myVideo.y, myVideo.width, myVideo.height); stage.displayState = StageDisplayState.FULL_SCREEN; } catch (e:SecurityError) { trace ("A security error occurred while switching to full screen: " + event); myVideo.width = savedWidth; myVideo.height = savedHeight; } }else { myVideo.width = savedWidth; myVideo.height = savedHeight; stage.displayState = StageDisplayState.NORMAL; } } private function netStatusHandler(event:NetStatusEvent):void { switch (event.info.code) { case "NetConnection.Connect.Success": connectStream(); break; case "NetStream.Play.StreamNotFound": trace ("Unable to locate video: " + videoURL); break; } } private function connectStream():void { var stream:NetStream = new NetStream(connection); stream.addEventListener(NetStatusEvent.NET_STATUS, netStatusHandler); stream.addEventListener(AsyncErrorEvent.ASYNC_ERROR, asyncErrorHandler); myVideo = new Video(); myVideo.attachNetStream(stream); stream.play(videoURL); savedWidth = myVideo.width; savedHeight = myVideo.height; addChild(myVideo); } private function securityErrorHandler(event:SecurityErrorEvent):void { trace("securityErrorHandler: " + event); } private function asyncErrorHandler(event:AsyncErrorEvent):void { } } }
flash.display.StageDisplayStateStage.displayStateStage.scaleModeflash.events.FullScreenEventflash.events.Event.RESIZE
fullScreenWidth Returns the width of the monitor that will be used when going to full screen size, if that state is entered immediately.uint Returns the width of the monitor that will be used when going to full screen size, if that state is entered immediately. If the user has multiple monitors, the monitor that's used is the monitor that most of the stage is on at the time.

Note: If the user has the opportunity to move the browser from one monitor to another between retrieving the value and going to full screen size, the value could be incorrect. If you retrieve the value in an event handler that sets Stage.displayState to StageDisplayState.FULL_SCREEN, the value will be correct.

This is the pixel width of the monitor and is the same as the stage width would be if Stage.align is set to StageAlign.TOP_LEFT and Stage.scaleMode is set to StageScaleMode.NO_SCALE.

This example creates a green rectangle the size of the stage and places a red square on it that it activates as a button. Clicking the red square triggers the enterFullScreen() event handler, which sets the fullScreenSourceRect property and enters full screen mode. To set the fullScreenSourceRect property, the event handler starts with the location and dimensions of the red square. It then compares the aspect ratio (width divided by height) of the red square to the aspect ratio of the stage at full screen width and height so that it can expand the rectangle (fullScreenSourceRect) to match the screen's aspect ratio. The result is that the red square occupies the entire height of the monitor with the green background visible on each side. If the aspect ratio was not matched, the stage background color, which is white by default, would show on each side instead of the green background.

Note: Test this example in the browser. In the Flash Publish Settings dialog, on the HTML tab, select the template Flash Only - Allow Full Screen. Specify the Flash Player version 9.0.115.0, and make sure the Flash and HTML formats are selected on the Formats tab. Then publish and open the resulting HTML file in the browser.

import flash.display.Sprite; import flash.display.Stage; import flash.display.StageDisplayState; import flash.events.MouseEvent; import flash.geom.Rectangle; // cover the stage with a green rectangle var greenRect:Sprite = new Sprite(); greenRect.graphics.beginFill(0x00FF00); greenRect.graphics.drawRect(0, 0, stage.stageWidth, stage.stageHeight); addChild(greenRect); // create red square on stage, turn it into a button for going to full screen var redSquare:Sprite = new Sprite(); redSquare.graphics.beginFill(0xFF0000); redSquare.graphics.drawRect(0, 0, 300, 300); redSquare.x = 50; redSquare.y = 50; redSquare.addEventListener(MouseEvent.CLICK, enterFullScreen); redSquare.buttonMode = true; addChild(redSquare); function enterFullScreen(e:MouseEvent):void { // we will go to full screen zoomed in on the red square var redSquare:Sprite = e.target as Sprite; var fullScreenRect:Rectangle = new Rectangle(redSquare.x, redSquare.y, redSquare.width, redSquare.height); // calculate aspect ratio of the red square var rectAspectRatio:Number = fullScreenRect.width / fullScreenRect.height; // calculate aspect ratio of the screen var screenAspectRatio:Number = stage.fullScreenWidth / stage.fullScreenHeight; // change the fullScreenRect so that it covers the entire screen, keeping it centered on the redSquare // try commenting out this section to see what happens if you do not fix the aspect ratio. if (rectAspectRatio > screenAspectRatio) { var newHeight:Number = fullScreenRect.width / screenAspectRatio; fullScreenRect.y -= ((newHeight - fullScreenRect.height) / 2); fullScreenRect.height = newHeight; } else if (rectAspectRatio < screenAspectRatio) { var newWidth:Number = fullScreenRect.height * screenAspectRatio; fullScreenRect.x -= ((newWidth - fullScreenRect.width) / 2); fullScreenRect.width = newWidth; } // go to full screen stage.fullScreenSourceRect = fullScreenRect; stage.displayState = StageDisplayState.FULL_SCREEN; }
displayStatefullScreenHeightfullScreenSourceRectscaleModeStageDisplayStateflash.events.Event.RESIZEflash.events.FullScreenEvent
height Indicates the height of the display object, in pixels.NumberReferencing the height property of a Stage object throws an exception for any caller that is not in the same security sandbox as the Stage owner (the main SWF file). To avoid this, the Stage owner can grant permission to the domain of the caller by calling the Security.allowDomain() method or the Security.allowInsecureDomain() method. For more information, see the "Security" chapter in the ActionScript 3.0 Developer's Guide. SecurityErrorSecurityErrorIt is always illegal to set the height property of a Stage object, even if the calling object is the Stage owner (the main SWF file). IllegalOperationErrorflash.errors:IllegalOperationError Indicates the height of the display object, in pixels. The height is calculated based on the bounds of the content of the display object. When you set the height property, the scaleY property is adjusted accordingly, as shown in the following code: var rect:Shape = new Shape(); rect.graphics.beginFill(0xFF0000); rect.graphics.drawRect(0, 0, 100, 100); trace(rect.scaleY) // 1; rect.height = 200; trace(rect.scaleY) // 2;

Except for TextField and Video objects, a display object with no content (such as an empty sprite) has a height of 0, even if you try to set height to a different value.

mouseChildren Determines whether or not the children of the object are mouse, or user input device, enabled.BooleanReferencing the mouseChildren property of a Stage object throws an exception for any caller that is not in the same security sandbox as the Stage owner (the main SWF file). To avoid this, the Stage owner can grant permission to the domain of the caller by calling the Security.allowDomain() method or the Security.allowInsecureDomain() method. For more information, see the "Security" chapter in the ActionScript 3.0 Developer's Guide. SecurityErrorSecurityError Determines whether or not the children of the object are mouse, or user input device, enabled. If an object is enabled, a user can interact with it by using a mouse or user input device. The default is true.

This property is useful when you create a button with an instance of the Sprite class (instead of using the SimpleButton class). When you use a Sprite instance to create a button, you can choose to decorate the button by using the addChild() method to add additional Sprite instances. This process can cause unexpected behavior with mouse events because the Sprite instances you add as children can become the target object of a mouse event when you expect the parent instance to be the target object. To ensure that the parent instance serves as the target objects for mouse events, you can set the mouseChildren property of the parent instance to false.

No event is dispatched by setting this property. You must use the addEventListener() method to create interactive functionality.

nativeWindow A reference to the NativeWindow object containing this Stage.flash.display:NativeWindow A reference to the NativeWindow object containing this Stage.

The window represents the native operating system window; the Stage represents the content contained by the window. This property is only valid for content running in AIR on platforms that support the NativeWindow class. On other platforms, this property will be null. In Flash Player (content running in a browser), this property will also be null.

numChildren Returns the number of children of this object.intReferencing the numChildren property of a Stage object throws an exception for any caller that is not in the same security sandbox as the Stage owner (the main SWF file). To avoid this, the Stage owner can grant permission to the domain of the caller by calling the Security.allowDomain() method or the Security.allowInsecureDomain() method. For more information, see the "Security" chapter in the ActionScript 3.0 Developer's Guide. SecurityErrorSecurityError Returns the number of children of this object. orientation The current orientation of the stage.String The current orientation of the stage. This property is set to one of four values, defined as constants in the StageOrientation class: StageOrientation constantStage orientationStageOrientation.DEFAULTThe screen is in the default orientation (right-side up).StageOrientation.ROTATED_RIGHTThe screen is rotated right.StageOrientation.ROTATED_LEFTThe screen is rotated left.StageOrientation.UPSIDE_DOWNThe screen is rotated upside down.StageOrientation.UNKNOWNThe application has not yet determined the initial orientation of the screen. You can add an event listener for the orientationChange event

To set the stage orientation, use the setOrientation() method.

Important: orientation property is supported on Android devices from 2.6 namespace onwards.

StageOrientationautoOrientsdeviceOrientationsupportsOrientationChange
quality A value from the StageQuality class that specifies which rendering quality is used.StringCalling the quality property of a Stage object throws an exception for any caller that is not in the same security sandbox as the Stage owner (the main SWF file). To avoid this, the Stage owner can grant permission to the domain of the caller by calling the Security.allowDomain() method or the Security.allowInsecureDomain() method. For more information, see the "Security" chapter in the ActionScript 3.0 Developer's Guide. SecurityErrorSecurityError A value from the StageQuality class that specifies which rendering quality is used. The following are valid values:
  • StageQuality.LOW—Low rendering quality. Graphics are not anti-aliased, and bitmaps are not smoothed, but runtimes still use mip-mapping.
  • StageQuality.MEDIUM—Medium rendering quality. Graphics are anti-aliased using a 2 x 2 pixel grid, bitmap smoothing is dependent on the Bitmap.smoothing setting. Runtimes use mip-mapping. This setting is suitable for movies that do not contain text.
  • StageQuality.HIGH—High rendering quality. Graphics are anti-aliased using a 4 x 4 pixel grid, and bitmap smoothing is dependent on the Bitmap.smoothing setting. Runtimes use mip-mapping. This is the default rendering quality setting that Flash Player uses.
  • StageQuality.BEST—Very high rendering quality. Graphics are anti-aliased using a 4 x 4 pixel grid. If Bitmap.smoothing is true the runtime uses a high quality downscale algorithm that produces fewer artifacts (however, using StageQuality.BEST with Bitmap.smoothing set to true slows performance significantly and is not a recommended setting).

Higher quality settings produce better rendering of scaled bitmaps. However, higher quality settings are computationally more expensive. In particular, when rendering scaled video, using higher quality settings can reduce the frame rate.

In the desktop profile of Adobe AIR, quality can be set to StageQuality.BEST or StageQuality.HIGH (and the default value is StageQuality.HIGH). Attempting to set it to another value has no effect (and the property remains unchanged). In the moble profile of AIR, all four quality settings are available. The default value on mobile devices is StageQuality.MEDIUM.

For content running in Adobe AIR, setting the quality property of one Stage object changes the rendering quality for all Stage objects (used by different NativeWindow objects).

Note: The operating system draws the device fonts, which are therefore unaffected by the quality property.
flash.display.StageQualityflash.display.Bitmap.smoothing
scaleMode A value from the StageScaleMode class that specifies which scale mode to use.StringCalling the scaleMode property of a Stage object throws an exception for any caller that is not in the same security sandbox as the Stage owner (the main SWF file). To avoid this, the Stage owner can grant permission to the domain of the caller by calling the Security.allowDomain() method or the Security.allowInsecureDomain() method. For more information, see the "Security" chapter in the ActionScript 3.0 Developer's Guide. SecurityErrorSecurityErrorA value from the StageScaleMode class that specifies which scale mode to use. A value from the StageScaleMode class that specifies which scale mode to use. The following are valid values:
  • StageScaleMode.EXACT_FIT—The entire application is visible in the specified area without trying to preserve the original aspect ratio. Distortion can occur, and the application may appear stretched or compressed.
  • StageScaleMode.SHOW_ALL—The entire application is visible in the specified area without distortion while maintaining the original aspect ratio of the application. Borders can appear on two sides of the application.
  • StageScaleMode.NO_BORDER—The entire application fills the specified area, without distortion but possibly with some cropping, while maintaining the original aspect ratio of the application.
  • StageScaleMode.NO_SCALE—The entire application is fixed, so that it remains unchanged even as the size of the player window changes. Cropping might occur if the player window is smaller than the content.
flash.display.StageScaleMode
showDefaultContextMenu Specifies whether to show or hide the default items in the Flash runtime context menu.BooleanCalling the showDefaultContextMenu property of a Stage object throws an exception for any caller that is not in the same security sandbox as the Stage owner (the main SWF file). To avoid this, the Stage owner can grant permission to the domain of the caller by calling the Security.allowDomain() method or the Security.allowInsecureDomain() method. For more information, see the "Security" chapter in the ActionScript 3.0 Developer's Guide. SecurityErrorSecurityErrorSpecifies whether to show or hide the default items in the Flash Player context menu. Specifies whether to show or hide the default items in the Flash runtime context menu.

If the showDefaultContextMenu property is set to true (the default), all context menu items appear. If the showDefaultContextMenu property is set to false, only the Settings and About... menu items appear.

softKeyboardRect The area of the stage that is currently covered by the software keyboard.flash.geom:Rectangle The area of the stage that is currently covered by the software keyboard.

The area has a size of zero (0,0,0,0) when the soft keyboard is not visible.

When the keyboard opens, the softKeyboardRect is set at the time the softKeyboardActivate event is dispatched. If the keyboard changes size while open, the runtime updates the softKeyboardRect property and dispatches an additional softKeyboardActivate event.

Note: On Android, the area covered by the keyboard is estimated when the operating system does not provide the information necessary to determine the exact area. This problem occurs in fullscreen mode and also when the keyboard opens in response to an InteractiveObject receiving focus or invoking the requestSoftKeyboard() method.

SoftKeyboardEventInteractiveObject.needsSoftKeyboard
stageFocusRect Specifies whether or not objects display a glowing border when they have focus.BooleanCalling the stageFocusRect property of a Stage object throws an exception for any caller that is not in the same security sandbox as the Stage owner (the main SWF file). To avoid this, the Stage owner can grant permission to the domain of the caller by calling the Security.allowDomain() method or the Security.allowInsecureDomain() method. For more information, see the "Security" chapter in the ActionScript 3.0 Developer's Guide. SecurityErrorSecurityErrorSpecifies whether or not objects display a glowing border when they have focus. Specifies whether or not objects display a glowing border when they have focus. stageHeight The current height, in pixels, of the Stage.intCalling the stageHeight property of a Stage object throws an exception for any caller that is not in the same security sandbox as the Stage owner (the main SWF file). To avoid this, the Stage owner can grant permission to the domain of the caller by calling the Security.allowDomain() method or the Security.allowInsecureDomain() method. For more information, see the "Security" chapter in the ActionScript 3.0 Developer's Guide. SecurityErrorSecurityError The current height, in pixels, of the Stage.

If the value of the Stage.scaleMode property is set to StageScaleMode.NO_SCALE when the user resizes the window, the Stage content maintains its size while the stageHeight property changes to reflect the new height size of the screen area occupied by the SWF file. (In the other scale modes, the stageHeight property always reflects the original height of the SWF file.) You can add an event listener for the resize event and then use the stageHeight property of the Stage class to determine the actual pixel dimension of the resized Flash runtime window. The event listener allows you to control how the screen content adjusts when the user resizes the window.

Air for TV devices have slightly different behavior than desktop devices when you set the stageHeight property. If the Stage.scaleMode property is set to StageScaleMode.NO_SCALE and you set the stageHeight property, the stage height does not change until the next frame of the SWF.

Note: In an HTML page hosting the SWF file, both the object and embed tags' height attributes must be set to a percentage (such as 100%), not pixels. If the settings are generated by JavaScript code, the height parameter of the AC_FL_RunContent() method must be set to a percentage, too. This percentage is applied to the stageHeight value.

flash.display.StageScaleMode
stageVideos A list of StageVideo objects available for playing external videos. A list of StageVideo objects available for playing external videos.

You can use only a limited number of StageVideo objects at a time. When a SWF begins to run, the number of available StageVideo objects depends on the platform and on available hardware.

To use a StageVideo object, assign a member of the stageVideos Vector object to a StageVideo variable.

All StageVideo objects are displayed on the stage behind any display objects. The StageVideo objects are displayed on the stage in the order they appear in the stageVideos Vector object. For example, if the stageVideos Vector object contains three entries:

  1. The StageVideo object in the 0 index of the stageVideos Vector object is displayed behind all StageVideo objects.
  2. The StageVideo object at index 1 is displayed in front of the StageVideo object at index 0.
  3. The StageVideo object at index 2 is displayed in front of the StageVideo object at index 1.

Use the StageVideo.depth property to change this ordering.

Note: AIR for TV devices support only one StageVideo object.

The following code illustrates how to get a StageVideo object: var stageVideo:StageVideo; if ( stage.stageVideos.length >= 1 ) { stageVideo = stage.stageVideos[0]; }
flash.media.StageVideoflash.events.StageVideoEvent
stageWidth Specifies the current width, in pixels, of the Stage.intCalling the stageWidth property of a Stage object throws an exception for any caller that is not in the same security sandbox as the Stage owner (the main SWF file). To avoid this, the Stage owner can grant permission to the domain of the caller by calling the Security.allowDomain() method or the Security.allowInsecureDomain() method. For more information, see the "Security" chapter in the ActionScript 3.0 Developer's Guide. SecurityErrorSecurityError Specifies the current width, in pixels, of the Stage.

If the value of the Stage.scaleMode property is set to StageScaleMode.NO_SCALE when the user resizes the window, the Stage content maintains its defined size while the stageWidth property changes to reflect the new width size of the screen area occupied by the SWF file. (In the other scale modes, the stageWidth property always reflects the original width of the SWF file.) You can add an event listener for the resize event and then use the stageWidth property of the Stage class to determine the actual pixel dimension of the resized Flash runtime window. The event listener allows you to control how the screen content adjusts when the user resizes the window.

Air for TV devices have slightly different behavior than desktop devices when you set the stageWidth property. If the Stage.scaleMode property is set to StageScaleMode.NO_SCALE and you set the stageWidth property, the stage width does not change until the next frame of the SWF.

Note: In an HTML page hosting the SWF file, both the object and embed tags' width attributes must be set to a percentage (such as 100%), not pixels. If the settings are generated by JavaScript code, the width parameter of the AC_FL_RunContent() method must be set to a percentage, too. This percentage is applied to the stageWidth value.

flash.display.StageScaleMode
supportedOrientations The orientations supported by the current device. The orientations supported by the current device.

You can use the orientation strings included in this list as parameters for the setOrientation() method. Setting an unsupported orientation fails without error.

The possible orientations include:

StageOrientation constantStage orientationStageOrientation.DEFAULTSet the stage orientation to the default orientation (right-side up).StageOrientation.ROTATED_RIGHTSet the stage orientation to be rotated right.StageOrientation.ROTATED_LEFTSet the stage orientation to be rotated left.StageOrientation.UPSIDE_DOWNSet the stage orientation to be rotated upside down.
StageOrientationautoOrientssetOrientationorientation
supportsOrientationChange Whether the application supports changes in the stage orientation (and device rotation).Boolean Whether the application supports changes in the stage orientation (and device rotation). Currently, this property is only true in AIR applications running on mobile devices. autoOrientsdeviceOrientationsupportsOrientationChangetabChildren Determines whether the children of the object are tab enabled.BooleanReferencing the tabChildren property of a Stage object throws an exception for any caller that is not in the same security sandbox as the Stage owner (the main SWF file). To avoid this, the Stage owner can grant permission to the domain of the caller by calling the Security.allowDomain() method or the Security.allowInsecureDomain() method. For more information, see the "Security" chapter in the ActionScript 3.0 Developer's Guide. SecurityErrorSecurityError Determines whether the children of the object are tab enabled. Enables or disables tabbing for the children of the object. The default is true.

Note: Do not use the tabChildren property with Flex. Instead, use the mx.core.UIComponent.hasFocusableChildren property.

textSnapshot Returns a TextSnapshot object for this DisplayObjectContainer instance.flash.text:TextSnapshotReferencing the textSnapshot property of a Stage object throws an exception because the Stage class does not implement this property. To avoid this, call the textSnapshot property of a display object container other than the Stage object. IllegalOperationErrorflash.errors:IllegalOperationError Returns a TextSnapshot object for this DisplayObjectContainer instance. width Indicates the width of the display object, in pixels.NumberReferencing the width property of a Stage object throws an exception for any caller that is not in the same security sandbox as the Stage owner (the main SWF file). To avoid this, the Stage owner can grant permission to the domain of the caller by calling the Security.allowDomain() method or the Security.allowInsecureDomain() method. For more information, see the "Security" chapter in the ActionScript 3.0 Developer's Guide. SecurityErrorSecurityErrorIt is always illegal to set the width property of a Stage object, even if you are the Stage owner. IllegalOperationErrorflash.errors:IllegalOperationError Indicates the width of the display object, in pixels. The width is calculated based on the bounds of the content of the display object. When you set the width property, the scaleX property is adjusted accordingly, as shown in the following code: var rect:Shape = new Shape(); rect.graphics.beginFill(0xFF0000); rect.graphics.drawRect(0, 0, 100, 100); trace(rect.scaleX) // 1; rect.width = 200; trace(rect.scaleX) // 2;

Except for TextField and Video objects, a display object with no content (such as an empty sprite) has a width of 0, even if you try to set width to a different value.

wmodeGPU Indicates whether GPU compositing is available and in use.Boolean Indicates whether GPU compositing is available and in use. The wmodeGPU value is true only when all three of the following conditions exist:

  • GPU compositing has been requested.
  • GPU compositing is available.
  • GPU compositing is in use.

Specifically, the wmodeGPU property indicates one of the following:

  1. GPU compositing has not been requested or is unavailable. In this case, the wmodeGPU property value is false.
  2. GPU compositing has been requested (if applicable and available), but the environment is operating in "fallback mode" (not optimal rendering) due to limitations of the content. In this case, the wmodeGPU property value is true.
  3. GPU compositing has been requested (if applicable and available), and the environment is operating in the best mode. In this case, the wmodeGPU property value is also true.

In other words, the wmodeGPU property identifies the capability and state of the rendering environment. For runtimes that do not support GPU compositing, such as AIR 1.5.2, the value is always false, because (as stated above) the value is true only when GPU compositing has been requested, is available, and is in use.

The wmodeGPU property is useful to determine, at runtime, whether or not GPU compositing is in use. The value of wmodeGPU indicates if your content is going to be scaled by hardware, or not, so you can present graphics at the correct size. You can also determine if you're rendering in a fast path or not, so that you can adjust your content complexity accordingly.

For Flash Player in a browser, GPU compositing can be requested by the value of gpu for the wmode HTML parameter in the page hosting the SWF file. For other configurations, GPU compositing can be requested in the header of a SWF file (set using SWF authoring tools).

However, the wmodeGPU property does not identify the current rendering performance. Even if GPU compositing is "in use" the rendering process might not be operating in the best mode. To adjust your content for optimal rendering, use a Flash runtime debugger version, and set the DisplayGPUBlendsetting in your mm.cfg file.

Note: This property is always false when referenced from ActionScript that runs before the runtime performs its first rendering pass. For example, if you examine wmodeGPU from a script in Frame 1 of Adobe Flash Professional, and your SWF file is the first SWF file loaded in a new instance of the runtime, then the wmodeGPU value is false. To get an accurate value, wait until at least one rendering pass has occurred. If you write an event listener for the exitFrame event of any DisplayObject, the wmodeGPU value at is the correct value.

The following example examines the wmodeGPU property after the display object mySprite is rendered, so you can get an accurate value. mySprite.addEventListener(EXIT_FRAME, exithandler): function exithandler(exiteventobject:Event):void { trace(stage.wmodeGPU); }
DisplayObject exitFrame event
NativeWindowInitOptions The NativeWindowInitOptions class defines the initialization options used to construct a new NativeWindow instance.Object The NativeWindowInitOptions class defines the initialization options used to construct a new NativeWindow instance.

The properties defined in the initialization options cannot be changed after a window is created.

Note: For the initial application window created automatically by AIR, all of these properties (except type) are set in the application descriptor. The initial window is always type NativeWindowType.NORMAL.

flash.display.NativeWindowflash.display.NativeWindowTypeflash.display.NativeWindowSystemChromeNativeWindowInitOptions Creates a new NativeWindowInitOptions object. Creates a new NativeWindowInitOptions object.

The default values of the newly created object are:

  • systemChrome = NativeWindowSystemChrome.STANDARD
  • type = NativeWindowType.NORMAL
  • transparent = false
  • owner = null
  • resizable = true
  • maximizable = true
  • minimizable = true
maximizable Specifies whether the window can be maximized by the user.Booleantrue Specifies whether the window can be maximized by the user.

For windows with system chrome, this setting will affect the appearance of the window maximize button. It will also affect other parts of the system-managed user interface, such as the window menu on Microsoft Windows.

When set to false, the window cannot be maximized by the user. Calling the NativeWindow maximize() method directly will maximize the window.

OS behavior notes:

  • On operating systems, such as Mac OS X, in which maximizing a window does not also prevent resizing, both maximizable and resizable must be set to false to prevent the window from being zoomed or resized.
  • Some Linux window managers allow windows to be maximized by the user even when the maximizable property is set to false.
flash.display.NativeWindow.displayState
minimizable Specifies whether the window can be minimized by the user.Booleantrue Specifies whether the window can be minimized by the user.

For windows with system chrome, this setting will affect the appearance of the window minimize button. It will also affect other parts of the system-managed user interface, such as the window menu on Microsoft Windows.

When set to false, the window cannot be minimized by the user. Calling the NativeWindow minimize() method directly will minimize the window.

Note: Some Linux window managers allow windows to be minimized by the user even when the minimizable property is set to false.

flash.display.NativeWindow.displayState
owner Specifies the NativeWindow object that should own any windows created with this NativeWindowInitOptions.flash.display:NativeWindow<code>null</code> Specifies the NativeWindow object that should own any windows created with this NativeWindowInitOptions.

When a window has an owner, that window is always displayed in front of its owner, is minimized and hidden along with its owner, and closes when its owner closes.

flash.display.NativeWindow.ownerflash.display.NativeWindow.listOwnedWindows()
resizable Specifies whether the window can be resized by the user.Booleantrue Specifies whether the window can be resized by the user.

When set to false, the window cannot be resized by the user using system chrome. Calling the NativeWindow startResize() method in response to a mouse event will allow the user to resize the window. Setting the window bounds directly will also change the window size.

OS behavior notes:

  • On operating systems, such as Mac OS X, in which maximizing windows is a resizing operation, both maximizable and resizable must be set to false to prevent the window from being zoomed or resized.
  • Some Linux window managers allow windows to be resized by the user even when the resizable property is set to false.
flash.display.NativeWindow.bounds
systemChrome Specifies whether system chrome is provided for the window.StringNativeWindowSystemChrome.STANDARD Specifies whether system chrome is provided for the window.

Chrome refers to the window controls that allow a user to control the desktop properties of a window. System chrome uses the standard controls for the desktop environment in which the AIR application is run and conforms to the standard look-and-feel of the native operating system.

To use chrome provided by a framework (such as Flex), or to provide your own window chrome, set systemChrome to NativeWindowSystemChrome.NONE.

Constants for the valid values of this property are defined in the NativeWindowSystemChrome class:

  • NativeWindowSystemChrome.NONE
  • NativeWindowSystemChrome.STANDARD

If not specified, the default value for systemChrome is NativeWindowSystemChrome.STANDARD.

Setting the transparent property to true for a window with system chrome is not supported.

flash.display.NativeWindowSystemChrome
transparent Specifies whether the window supports transparency and alpha blending against the desktop.Booleanfalse Specifies whether the window supports transparency and alpha blending against the desktop.

If true, the window display is composited against the desktop. Areas of the window not covered by a display object, or covered by display objects with an alpha setting near zero, are effectively invisible and will not intercept mouse events (which will be received by the desktop object below the window). The alpha value at which an object will no longer intercepting mouse events varies between about .06 and .01, depending on the operating system.

Setting the transparent property to true for a window with system chrome is not supported.

Note: Not all Linux window managers support transparency. On such systems, transparent areas of a window are composited against black.

type Specifies the type of the window to be created.StringNativeWindowType.NORMAL Specifies the type of the window to be created.

Constants for the valid values of this property are defined in the NativeWindowType class:

  • NativeWindowType.NORMAL — A typical window. Normal windows use full-size chrome and appear on the Windows or Linux task bar.
  • NativeWindowType.UTILITY — A tool palette. Utility windows use a slimmer version of the system chrome and do not appear on the Windows task bar.
  • NativeWindowType.LIGHTWEIGHT — lightweight windows cannot have system chrome and do not appear on the Windows or Linux task bar. In addition, lightweight windows do not have the System (Alt-Space) menu on Windows. Lightweight windows are suitable for notification bubbles and controls such as combo-boxes that open a short-lived display area. When the lightweight type is used, systemChrome must be set to NativeWindowSystemChrome.NONE.

If not specified, the default value for type is NativeWindowType.NORMAL.

flash.display.NativeWindowType
ShaderParameter A ShaderParameter instance represents a single input parameter of a shader kernel.Object A ShaderParameter instance represents a single input parameter of a shader kernel. A kernel can be defined to accept zero, one, or more parameters that are used in the kernel execution. A ShaderParameter provides information about the parameter, such as the type of data it expects. It also provides a mechanism for setting the parameter value that is used when the shader executes. To specify a value or values for the shader parameter, create an Array containing the value or values and assign it to the value property.

A ShaderParameter instance representing a parameter for a Shader instance is accessed as a property of the Shader instance's data property. The ShaderParameter property has the same name as the parameter's name in the shader code. For example, if a shader defines a parameter named radius, the ShaderParameter instance representing the radius parameter is available as the radius property, as shown here:

var radiusParam:ShaderParameter = myShader.data.radius;

In addition to the defined properties of the ShaderParameter class, each ShaderParameter instance has additional properties corresponding to any metadata defined for the parameter. These properties are added to the ShaderParameter object when it is created. The properties' names match the metadata names specified in the shader's source code. The data type of each property varies according to the data type of the corresponding metadata. A text metadata value such as "description" is a String instance. A metadata property with a non-string value (such as minValue or defaultValue) is represented as an Array instance. The number of elements and element data types correspond to the metadata values.

For example, suppose a shader includes the following two parameter declarations:

parameter float2 size < description: "The size of the image to which the kernel is applied"; minValue: float2(0.0, 0.0); maxValue: float2(100.0, 100.0); defaultValue: float2(50.0, 50.0); >; parameter float radius < description: "The radius of the effect"; minValue: 0.0; maxValue: 50.0; defaultValue: 25.0; >;

The ShaderParameter instance corresponding to the size parameter has the following metadata properties in addition to its built-in properties:

Property nameData typeValuenameString"size"descriptionString"The size of the image to which the kernel is applied"minValueArray[0, 0]maxValueArray[100, 100]defaultValueArray[50, 50]

The ShaderParameter corresponding to the radius parameter has the following additional properties:

Property nameData typeValuenameString"radius"descriptionString"The radius of the effect"minValueArray[0]maxValueArray[50]defaultValueArray[25]

Generally, developer code does not create a ShaderParameter instance directly. A ShaderParameter instance is created for each of a shader's parameters when the Shader instance is created.

flash.display.ShaderDataflash.display.Shader.dataShaderParameter Creates a ShaderParameter instance. Creates a ShaderParameter instance. Developer code does not call the ShaderParameter constructor directly. A ShaderParameter instance is created for each of a shader's parameters when the Shader instance is created. index The zero-based index of the parameter.int The zero-based index of the parameter. type The data type of the parameter as defined in the shader.String The data type of the parameter as defined in the shader. The set of possible values for the type property is defined by the constants in the ShaderParameterType class. flash.display.ShaderParameterTypevalue The value or values that are passed in as the parameter value to the shader.Array The value or values that are passed in as the parameter value to the shader. The value property is an indexed Array. The number and type of the elements of the Array correspond to the data type of the parameter, which can be determined using the type property.

The following table indicates the parameter type and corresponding number and data type of the value Array's elements:

Parameter type# ElementsElement data typefloat (ShaderParameterType.FLOAT)1Numberfloat2 (ShaderParameterType.FLOAT2)2Numberfloat3 (ShaderParameterType.FLOAT3)3Numberfloat4 (ShaderParameterType.FLOAT4)4Numberint (ShaderParameterType.INT)1int or uintint2 (ShaderParameterType.INT2)2int or uintint3 (ShaderParameterType.INT3)3int or uintint4 (ShaderParameterType.INT4)4int or uintbool (ShaderParameterType.BOOL)1Booleanbool2 (ShaderParameterType.BOOL2)2Booleanbool3 (ShaderParameterType.BOOL3)3Booleanbool4 (ShaderParameterType.BOOL4)4Booleanfloat2x2 (ShaderParameterType.MATRIX2X2)4Numberfloat3x3 (ShaderParameterType.MATRIX3X3)9Numberfloat4x4 (ShaderParameterType.MATRIX4X4)16Number

For the matrix parameter types, the array elements fill the rows of the matrix, then the columns. For example, suppose the following line of ActionScript is used to fill a float2x2 parameter named myMatrix:

myShader.data.myMatrix.value = [.1, .2, .3, .4];

Within the shader, the matrix elements have the following values:

  • myMatrix[0][0]: .1
  • myMatrix[0][1]: .2
  • myMatrix[1][0]: .3
  • myMatrix[1][1]: .4
GradientType The GradientType class provides values for the type parameter in the beginGradientFill() and lineGradientStyle() methods of the flash.display.Graphics class.Object The GradientType class provides values for the type parameter in the beginGradientFill() and lineGradientStyle() methods of the flash.display.Graphics class. LINEAR Value used to specify a linear gradient fill.linearString Value used to specify a linear gradient fill. RADIAL Value used to specify a radial gradient fill.radialString Value used to specify a radial gradient fill. InterpolationMethod The InterpolationMethod class provides values for the interpolationMethod parameter in the Graphics.beginGradientFill() and Graphics.lineGradientStyle() methods.Object The InterpolationMethod class provides values for the interpolationMethod parameter in the Graphics.beginGradientFill() and Graphics.lineGradientStyle() methods. This parameter determines the RGB space to use when rendering the gradient. flash.display.Graphics.beginGradientFill()flash.display.Graphics.lineGradientStyle()LINEAR_RGB Specifies that the linear RGB interpolation method should be used.linearRGBString Specifies that the linear RGB interpolation method should be used. This means that an RGB color space based on a linear RGB color model is used. RGBRGB Specifies that the RGB interpolation method should be used.rgbString Specifies that the RGB interpolation method should be used. This means that the gradient is rendered with exponential sRGB (standard RGB) space. The sRGB space is a W3C-endorsed standard that defines a non-linear conversion between red, green, and blue component values and the actual intensity of the visible component color.

For example, consider a simple linear gradient between two colors (with the spreadMethod parameter set to SpreadMethod.REFLECT). The different interpolation methods affect the appearance as follows:

InterpolationMethod.LINEAR_RGBInterpolationMethod.RGB
LINEAR_RGB
IGraphicsPath This interface is used to define objects that can be used as path parameters in the flash.display.Graphics methods and drawing classes. This interface is used to define objects that can be used as path parameters in the flash.display.Graphics methods and drawing classes. Use the implementor classes of this interface to create and manage path property data, and to reuse the same data for different instances. flash.display.Graphics.drawGraphicsData()flash.display.Graphics.drawPath()IGraphicsFill This interface is used to define objects that can be used as fill parameters in the flash.display.Graphics methods and drawing classes. This interface is used to define objects that can be used as fill parameters in the flash.display.Graphics methods and drawing classes. Use the implementor classes of this interface to create and manage fill property data, and to reuse the same data for different instances. flash.display.Graphics.drawGraphicsData()flash.display.GraphicsStroke.fillLoaderInfo The LoaderInfo class provides information about a loaded SWF file or a loaded image file (JPEG, GIF, or PNG).flash.events:EventDispatcher The LoaderInfo class provides information about a loaded SWF file or a loaded image file (JPEG, GIF, or PNG). LoaderInfo objects are available for any display object. The information provided includes load progress, the URLs of the loader and loaded content, the number of bytes total for the media, and the nominal height and width of the media.

You can access LoaderInfo objects in two ways:

  • The contentLoaderInfo property of a flash.display.Loader object— The contentLoaderInfo property is always available for any Loader object. For a Loader object that has not called the load() or loadBytes() method, or that has not sufficiently loaded, attempting to access many of the properties of the contentLoaderInfo property throws an error.
  • The loaderInfo property of a display object.

The contentLoaderInfo property of a Loader object provides information about the content that the Loader object is loading, whereas the loaderInfo property of a DisplayObject provides information about the root SWF file for that display object.

When you use a Loader object to load a display object (such as a SWF file or a bitmap), the loaderInfo property of the display object is the same as the contentLoaderInfo property of the Loader object (DisplayObject.loaderInfo = Loader.contentLoaderInfo). Because the instance of the main class of the SWF file has no Loader object, the loaderInfo property is the only way to access the LoaderInfo for the instance of the main class of the SWF file.

The following diagram shows the different uses of the LoaderInfo object—for the instance of the main class of the SWF file, for the contentLoaderInfo property of a Loader object, and for the loaderInfo property of a loaded object:

When a loading operation is not complete, some properties of the contentLoaderInfo property of a Loader object are not available. You can obtain some properties, such as bytesLoaded, bytesTotal, url, loaderURL, and applicationDomain. When the loaderInfo object dispatches the init event, you can access all properties of the loaderInfo object and the loaded image or SWF file.

Note: All properties of LoaderInfo objects are read-only.

The EventDispatcher.dispatchEvent() method is not applicable to LoaderInfo objects. If you call dispatchEvent() on a LoaderInfo object, an IllegalOperationError exception is thrown.

The following example uses the LoaderInfoExample class to display an image on the stage. This is accomplished by performing the following steps:
  1. A property url is created, which is the location and name of the image.
  2. The class constructor creates a Loader object named loader.
  3. The loader object instantiates an event listener to ensure that the image loads properly.
  4. The constructor creates a new instance of a URLRequest object, request, with url passed so that the file name and location are known.
  5. The request object is then passed to the load() method of the loader object, which loads the image onto the display list.

Important: This example requires that you add a file named Image.gif in the same directory as the compiled SWF file. Use an image that has an area that fits within the dimensions of the main SWF file.

package { import flash.display.Loader; import flash.display.LoaderInfo; import flash.display.Sprite; import flash.events.*; import flash.net.URLRequest; public class LoaderInfoExample extends Sprite { private var url:String = "Image.gif"; public function LoaderInfoExample() { var loader:Loader = new Loader(); loader.contentLoaderInfo.addEventListener(Event.INIT, initHandler); loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler); var request:URLRequest = new URLRequest(url); loader.load(request); addChild(loader); } private function initHandler(event:Event):void { var loader:Loader = Loader(event.target.loader); var info:LoaderInfo = LoaderInfo(loader.contentLoaderInfo); trace("initHandler: loaderURL=" + info.loaderURL + " url=" + info.url); } private function ioErrorHandler(event:IOErrorEvent):void { trace("ioErrorHandler: " + event); } } }
flash.display.Loaderflash.display.Loader.contentflash.display.DisplayObjectflash.display.DisplayObject.loaderInfohttpStatus Dispatched when a network request is made over HTTP and an HTTP status code can be detected.flash.events.HTTPStatusEvent.HTTP_STATUSflash.events.HTTPStatusEvent Dispatched when a network request is made over HTTP and an HTTP status code can be detected. Loader.load()unload Dispatched by a LoaderInfo object whenever a loaded object is removed by using the unload() method of the Loader object, or when a second load is performed by the same Loader object and the original content is removed prior to the load beginning.flash.events.Event.UNLOADflash.events.Event Dispatched by a LoaderInfo object whenever a loaded object is removed by using the unload() method of the Loader object, or when a second load is performed by the same Loader object and the original content is removed prior to the load beginning. Loader.load()Loader.unload()progress Dispatched when data is received as the download operation progresses.flash.events.ProgressEvent.PROGRESSflash.events.ProgressEvent Dispatched when data is received as the download operation progresses. Loader.load()open Dispatched when a load operation starts.flash.events.Event.OPENflash.events.Event Dispatched when a load operation starts. Loader.load()ioError Dispatched when an input or output error occurs that causes a load operation to fail.flash.events.IOErrorEvent.IO_ERRORflash.events.IOErrorEvent Dispatched when an input or output error occurs that causes a load operation to fail. Loader.load()init Dispatched when the properties and methods of a loaded SWF file are accessible and ready for use.flash.events.Event.INITflash.events.Event Dispatched when the properties and methods of a loaded SWF file are accessible and ready for use. The content, however, can still be downloading. A LoaderInfo object dispatches the init event when the following conditions exist:
  • All properties and methods associated with the loaded object and those associated with the LoaderInfo object are accessible.
  • The constructors for all child objects have completed.
  • All ActionScript code in the first frame of the loaded SWF's main timeline has been executed.

For example, an Event.INIT is dispatched when the first frame of a movie or animation is loaded. The movie is then accessible and can be added to the display list. The complete movie, however, can take longer to download. The Event.COMPLETE is only dispatched once the full movie is loaded.

The init event always precedes the complete event.

Loader.load()
complete Dispatched when data has loaded successfully.flash.events.Event.COMPLETEflash.events.Event Dispatched when data has loaded successfully. In other words, it is dispatched when all the content has been downloaded and the loading has finished. The complete event is always dispatched after the init event. The init event is dispatched when the object is ready to access, though the content may still be downloading. Loader.load()getLoaderInfoByDefinition Returns the LoaderInfo object associated with a SWF file defined as an object.The caller is not running in the local trusted sandbox. SecurityErrorSecurityErrorThe associated LoaderInfo object. Returns null when called in non-debugger builds (or when debugging is not enabled) or if the referenced object does not have an associated LoaderInfo object (such as some objects used by the AIR runtime). flash.display:LoaderInfoobjectObjectThe object for which you want to get an associated LoaderInfo object. Returns the LoaderInfo object associated with a SWF file defined as an object. actionScriptVersion The ActionScript version of the loaded SWF file.uintIf the file is not downloaded sufficiently to retrieve the requested information. ErrorErrorIf the file is not a SWF file. ErrorError The ActionScript version of the loaded SWF file. The language version is specified by using the enumerations in the ActionScriptVersion class, such as ActionScriptVersion.ACTIONSCRIPT2 and ActionScriptVersion.ACTIONSCRIPT3.

Note: This property always has a value of either ActionScriptVersion.ACTIONSCRIPT2 or ActionScriptVersion.ACTIONSCRIPT3. ActionScript 1.0 and 2.0 are both reported as ActionScriptVersion.ACTIONSCRIPT2 (version 2.0). This property only distinguishes ActionScript 1.0 and 2.0 from ActionScript 3.0.

flash.display.ActionScriptVersion
applicationDomain When an external SWF file is loaded, all ActionScript 3.0 definitions contained in the loaded class are stored in the applicationDomain property.flash.system:ApplicationDomainThis security sandbox of the caller is not allowed to access this ApplicationDomain. SecurityErrorSecurityError When an external SWF file is loaded, all ActionScript 3.0 definitions contained in the loaded class are stored in the applicationDomain property.

All code in a SWF file is defined to exist in an application domain. The current application domain is where your main application runs. The system domain contains all application domains, including the current domain and all classes used by Flash Player or Adobe AIR.

All application domains, except the system domain, have an associated parent domain. The parent domain of your main application's applicationDomain is the system domain. Loaded classes are defined only when their parent doesn't already define them. You cannot override a loaded class definition with a newer definition.

For usage examples of application domains, see the "Client System Environment" chapter in the ActionScript 3.0 Developer's Guide.

flash.system.ApplicationDomain
bytesLoaded The number of bytes that are loaded for the media.uint The number of bytes that are loaded for the media. When this number equals the value of bytesTotal, all of the bytes are loaded. bytesTotal The number of compressed bytes in the entire media file.uint The number of compressed bytes in the entire media file.

Before the first progress event is dispatched by this LoaderInfo object's corresponding Loader object, bytesTotal is 0. After the first progress event from the Loader object, bytesTotal reflects the actual number of bytes to be downloaded.

flash.events.ProgressEventflash.display.Loader
bytes The bytes associated with a LoaderInfo object.flash.utils:ByteArrayIf the object accessing this API is prevented from accessing the loaded object due to security restrictions. This situation can occur, for instance, when a Loader object attempts to access the contentLoaderInfo.content property and it is not granted security permission to access the loaded content.

For more information related to security, see the Flash Player Developer Center Topic: Security.

SecurityErrorSecurityError
The bytes associated with a LoaderInfo object.
childAllowsParent Expresses the trust relationship from content (child) to the Loader (parent).Boolean Thrown if the file is not downloaded sufficiently to retrieve the requested information. ErrorError Expresses the trust relationship from content (child) to the Loader (parent). If the child has allowed the parent access, true; otherwise, false. This property is set to true if the child object has called the allowDomain() method to grant permission to the parent domain or if a URL policy is loaded at the child domain that grants permission to the parent domain. If child and parent are in the same domain, this property is set to true.

For more information related to security, see the Flash Player Developer Center Topic: Security.

childSandboxBridge A object that can be set by the loaded content's code to expose properties and methods that can be accessed by code in the Loader object's sandbox.ObjectOnly content in the loaded content's sandbox can set this property. SecurityErrorSecurityError A object that can be set by the loaded content's code to expose properties and methods that can be accessed by code in the Loader object's sandbox. This sandbox bridge lets content from a non-application domain have controlled access to scripts in the AIR application sandbox, and vice versa. The sandbox bridge serves as a gateway between the sandboxes, providing explicit interaction between application and non-application security sandboxes. parentSandboxBridgecontentType The MIME type of the loaded file.String The MIME type of the loaded file. The value is null if not enough of the file has loaded in order to determine the type. The following list gives the possible values:
  • "application/x-shockwave-flash"
  • "image/jpeg"
  • "image/gif"
  • "image/png"
content The loaded object associated with this LoaderInfo object.flash.display:DisplayObjectIf the object accessing this API is prevented from accessing the loaded object due to security restrictions. This situation can occur, for instance, when a Loader object attempts to access the contentLoaderInfo.content property and it is not granted security permission to access the loaded content.

For more information related to security, see the Flash Player Developer Center Topic: Security.

SecurityErrorSecurityError
The loaded object associated with this LoaderInfo object.
frameRate The nominal frame rate, in frames per second, of the loaded SWF file.NumberIf the file is not downloaded sufficiently to retrieve the requested information. ErrorErrorIf the file is not a SWF file. ErrorError The nominal frame rate, in frames per second, of the loaded SWF file. This number is often an integer, but need not be.

This value may differ from the actual frame rate in use. Flash Player or Adobe AIR only uses a single frame rate for all loaded SWF files at any one time, and this frame rate is determined by the nominal frame rate of the main SWF file. Also, the main frame rate may not be able to be achieved, depending on hardware, sound synchronization, and other factors.

height The nominal height of the loaded file.intIf the file is not downloaded sufficiently to retrieve the requested information. ErrorError The nominal height of the loaded file. This value might differ from the actual height at which the content is displayed, since the loaded content or its parent display objects might be scaled. isURLInaccessible Indicates if the LoaderInfo.url property has been truncated.Boolean Indicates if the LoaderInfo.url property has been truncated. When the isURLInaccessible value is true the LoaderInfo.url value is only the domain of the final URL from which the content loaded. For example, the property is truncated if the content is loaded from http://www.adobe.com/assets/hello.swf, and the LoaderInfo.url property has the value http://www.adobe.com. The isURLInaccessible value is true only when all of the following are also true:
  • An HTTP redirect occurred while loading the content.
  • The SWF file calling Loader.load() is from a different domain than the content's final URL.
  • The SWF file calling Loader.load() does not have permission to access the content. Permission is granted to access the content the same way permission is granted for BitmapData.draw(): call Security.allowDomain() to access a SWF file (or for non-SWF file content, establish a policy file and use the LoaderContext.checkPolicyFile property).

Note: The isURLInaccessible property was added for Flash Player 10.1 and AIR 2.0. However, this property is made available to SWF files of all versions when the Flash runtime supports it. So, using some authoring tools in "strict mode" causes a compilation error. To work around the error use the indirect syntax myLoaderInfo["isURLInaccessible"], or disable strict mode. If you are using Flash Professional CS5 or Flex SDK 4.1, you can use and compile this API for runtimes released before Flash Player 10.1 and AIR 2.

For application content in AIR, the value of this property is always false.

urlBitmapData.draw()flash.system.Security.allowDomain()flash.system.LoaderContext.checkPolicyFile
loaderURL The URL of the SWF file that initiated the loading of the media described by this LoaderInfo object.String The URL of the SWF file that initiated the loading of the media described by this LoaderInfo object. For the instance of the main class of the SWF file, this URL is the same as the SWF file's own URL. loader The Loader object associated with this LoaderInfo object.flash.display:LoaderIf the object accessing this API is prevented from accessing the Loader object because of security restrictions. This can occur, for instance, when a loaded SWF file attempts to access its loaderInfo.loader property and it is not granted security permission to access the loading SWF file.

For more information related to security, see the Flash Player Developer Center Topic: Security.

SecurityErrorSecurityError
The Loader object associated with this LoaderInfo object. If this LoaderInfo object is the loaderInfo property of the instance of the main class of the SWF file, no Loader object is associated.
parameters An object that contains name-value pairs that represent the parameters provided to the loaded SWF file.Object An object that contains name-value pairs that represent the parameters provided to the loaded SWF file.

You can use a for-in loop to extract all the names and values from the parameters object.

The two sources of parameters are: the query string in the URL of the main SWF file, and the value of the FlashVars HTML parameter (this affects only the main SWF file).

The parameters property replaces the ActionScript 1.0 and 2.0 technique of providing SWF file parameters as properties of the main timeline.

The value of the parameters property is null for Loader objects that contain SWF files that use ActionScript 1.0 or 2.0. It is only non-null for Loader objects that contain SWF files that use ActionScript 3.0.

parentAllowsChild Expresses the trust relationship from Loader (parent) to the content (child).Boolean Thrown if the file is not downloaded sufficiently to retrieve the requested information. ErrorError Expresses the trust relationship from Loader (parent) to the content (child). If the parent has allowed the child access, true; otherwise, false. This property is set to true if the parent object called the allowDomain() method to grant permission to the child domain or if a URL policy file is loaded at the parent domain granting permission to the child domain. If child and parent are in the same domain, this property is set to true.

For more information related to security, see the Flash Player Developer Center Topic: Security.

parentSandboxBridge A object that can be set by code in the Loader object's sandbox to expose properties and methods that can be accessed by the loaded content's code.ObjectOnly content in the Loader object's sandbox can set this property. SecurityErrorSecurityError A object that can be set by code in the Loader object's sandbox to expose properties and methods that can be accessed by the loaded content's code. This sandbox bridge lets content from a non-application domain have controlled access to scripts in the AIR application sandbox, and vice versa. The sandbox bridge serves as a gateway between the sandboxes, providing explicit interaction between application and non-application security sandboxes. childSandboxBridgesameDomain Expresses the domain relationship between the loader and the content: true if they have the same origin domain; false otherwise.Boolean Thrown if the file is not downloaded sufficiently to retrieve the requested information. ErrorError Expresses the domain relationship between the loader and the content: true if they have the same origin domain; false otherwise. sharedEvents An EventDispatcher instance that can be used to exchange events across security boundaries.flash.events:EventDispatcher An EventDispatcher instance that can be used to exchange events across security boundaries. Even when the Loader object and the loaded content originate from security domains that do not trust one another, both can access sharedEvents and send and receive events via this object. swfVersion The file format version of the loaded SWF file.uintIf the file is not downloaded sufficiently to retrieve the requested information. ErrorErrorIf the file is not a SWF file. ErrorError The file format version of the loaded SWF file. The file format is specified using the enumerations in the SWFVersion class, such as SWFVersion.FLASH7 and SWFVersion.FLASH9. flash.display.SWFVersionuncaughtErrorEvents An object that dispatches an uncaughtError event when an unhandled error occurs in code in this LoaderInfo object's SWF file.flash.events:UncaughtErrorEvents An object that dispatches an uncaughtError event when an unhandled error occurs in code in this LoaderInfo object's SWF file. An uncaught error happens when an error is thrown outside of any try..catch blocks or when an ErrorEvent object is dispatched with no registered listeners.

This property is created when the SWF associated with this LoaderInfo has finished loading. Until then the uncaughtErrorEvents property is null. In an ActionScript-only project, you can access this property during or after the execution of the constructor function of the main class of the SWF file. For a Flex project, the uncaughtErrorEvents property is available after the applicationComplete event is dispatched.

The following example demonstrates the use of an uncaught error event handler to detect uncaught errors in an ActionScript project. The example defines an uncaughtError event handler to detect uncaught errors. It also provides a button that, when clicked, throws an error that is caught by the uncaught error handler.

In the constructor, the code registers a listener for the uncaughtError event dispatched by the LoaderInfo object's uncaughtErrorEvents property.

In the uncaughtErrorHandler() method, the code checks the data type of the error property and responds accordingly.

package { import flash.display.Sprite; import flash.events.ErrorEvent; import flash.events.MouseEvent; import flash.events.UncaughtErrorEvent; public class UncaughtErrorEventExample extends Sprite { public function UncaughtErrorEventExample() { loaderInfo.uncaughtErrorEvents.addEventListener(UncaughtErrorEvent.UNCAUGHT_ERROR, uncaughtErrorHandler); drawUI(); } private function uncaughtErrorHandler(event:UncaughtErrorEvent):void { if (event.error is Error) { var error:Error = event.error as Error; // do something with the error } else if (event.error is ErrorEvent) { var errorEvent:ErrorEvent = event.error as ErrorEvent; // do something with the error } else { // a non-Error, non-ErrorEvent type was thrown and uncaught } } private function drawUI():void { var btn:Sprite = new Sprite(); btn.graphics.clear(); btn.graphics.beginFill(0xFFCC00); btn.graphics.drawRect(0, 0, 100, 50); btn.graphics.endFill(); addChild(btn); btn.addEventListener(MouseEvent.CLICK, clickHandler); } private function clickHandler(event:MouseEvent):void { throw new Error("Gak!"); } } }
The following example is the Flex equivalent of the previous example, using an MXML document instead of an ActionScript class as the root content. <?xml version="1.0" encoding="utf-8"?> <s:WindowedApplication xmlns:fx="http://ns.adobe.com/mxml/2009" xmlns:s="library://ns.adobe.com/flex/spark" xmlns:mx="library://ns.adobe.com/flex/halo" applicationComplete="applicationCompleteHandler();"> <fx:Script> <![CDATA[ import flash.events.ErrorEvent; import flash.events.MouseEvent; import flash.events.UncaughtErrorEvent; private function applicationCompleteHandler():void { loaderInfo.uncaughtErrorEvents.addEventListener(UncaughtErrorEvent.UNCAUGHT_ERROR, uncaughtErrorHandler); } private function uncaughtErrorHandler(event:UncaughtErrorEvent):void { if (event.error is Error) { var error:Error = event.error as Error; // do something with the error } else if (event.error is ErrorEvent) { var errorEvent:ErrorEvent = event.error as ErrorEvent; // do something with the error } else { // a non-Error, non-ErrorEvent type was thrown and uncaught } } private function clickHandler(event:MouseEvent):void { throw new Error("Gak!"); } ]]> </fx:Script> <s:Button label="Cause Error" click="clickHandler(event);"/> </s:WindowedApplication>
UncaughtErrorEventLoader.uncaughtErrorEvents
url The URL of the media being loaded.String The URL of the media being loaded.

Before the first progress event is dispatched by this LoaderInfo object's corresponding Loader object, the value of the url property might reflect only the initial URL specified in the call to the load() method of the Loader object. After the first progress event, the url property reflects the media's final URL, after any redirects and relative URLs are resolved.

In some cases, the value of the url property is truncated; see the isURLInaccessible property for details.

isURLInaccessibleflash.display.Loader.load()
width The nominal width of the loaded content.intIf the file is not downloaded sufficiently to retrieve the requested information. ErrorError The nominal width of the loaded content. This value might differ from the actual width at which the content is displayed, since the loaded content or its parent display objects might be scaled.
StageQuality The StageQuality class provides values for the Stage.quality property.Object The StageQuality class provides values for the Stage.quality property. flash.display.Stage.qualityBEST Specifies very high rendering quality: graphics are anti-aliased using a 4 x 4 pixel grid and bitmaps are always smoothed.bestString Specifies very high rendering quality: graphics are anti-aliased using a 4 x 4 pixel grid and bitmaps are always smoothed. HIGH Specifies high rendering quality: graphics are anti-aliased using a 4 x 4 pixel grid, and bitmaps are smoothed if the movie is static.highString Specifies high rendering quality: graphics are anti-aliased using a 4 x 4 pixel grid, and bitmaps are smoothed if the movie is static. LOW Specifies low rendering quality: graphics are not anti-aliased, and bitmaps are not smoothed.lowString Specifies low rendering quality: graphics are not anti-aliased, and bitmaps are not smoothed. MEDIUM Specifies medium rendering quality: graphics are anti-aliased using a 2 x 2 pixel grid, but bitmaps are not smoothed.mediumString Specifies medium rendering quality: graphics are anti-aliased using a 2 x 2 pixel grid, but bitmaps are not smoothed. This setting is suitable for movies that do not contain text. BitmapData The BitmapData class lets you work with the data (pixels) of a Bitmap object bitmap image.Lets you work with the bitmap data of a Bitmap object. flash.display:IBitmapDrawableObject The BitmapData class lets you work with the data (pixels) of a Bitmap object . You can use the methods of the BitmapData class to create arbitrarily sized transparent or opaque bitmap images and manipulate them in various ways at runtime. You can also access the BitmapData for a bitmap image that you load with the flash.display.Loader class.

This class lets you separate bitmap rendering operations from the internal display updating routines of Flash Player. By manipulating a BitmapData object directly, you can create complex images without incurring the per-frame overhead of constantly redrawing the content from vector data.

The methods of the BitmapData class support effects that are not available through the filters available to non-bitmap display objects.

A BitmapData object contains an array of pixel data. This data can represent either a fully opaque bitmap or a transparent bitmap that contains alpha channel data. Either type of BitmapData object is stored as a buffer of 32-bit integers. Each 32-bit integer determines the properties of a single pixel in the bitmap.

Each 32-bit integer is a combination of four 8-bit channel values (from 0 to 255) that describe the alpha transparency and the red, green, and blue (ARGB) values of the pixel. (For ARGB values, the most significant byte represents the alpha channel value, followed by red, green, and blue.)

The four channels (alpha, red, green, and blue) are represented as numbers when you use them with the BitmapData.copyChannel() method or the DisplacementMapFilter.componentX and DisplacementMapFilter.componentY properties, and these numbers are represented by the following constants in the BitmapDataChannel class:

  • BitmapDataChannel.ALPHA
  • BitmapDataChannel.RED
  • BitmapDataChannel.GREEN
  • BitmapDataChannel.BLUE

You can attach BitmapData objects to a Bitmap object by using the bitmapData property of the Bitmap object.

You can use a BitmapData object to fill a Graphics object by using the Graphics.beginBitmapFill() method.

In the AIR runtime, the DockIcon, Icon, InteractiveIcon, and SystemTrayIcon classes each include a bitmaps property that is an array of BitmapData objects that define the bitmap images for an icon.

In AIR 1.5 and Flash Player 10, the maximum size for a BitmapData object is 8,191 pixels in width or height, and the total number of pixels cannot exceed 16,777,215 pixels. (So, if a BitmapData object is 8,191 pixels wide, it can only be 2,048 pixels high.) In Flash Player 9 and earlier and AIR 1.1 and earlier, the limitation is 2,880 pixels in height and 2,880 in width.

Calls to any method or property of a BitmapData object throw an ArgumentError error if the BitmapData object is invalid (for example, if it has height == 0 and width == 0) or it has been disposed of via dispose().

The following example uses the class BitmapDataExample to load the image Image.gif into a DisplayObject in the default location (0, 0). A copy of Image.gif is then placed to the right of the original, which has new colors applied to pixels that pass a test using the threshold() method. The task is accomplished using the following steps:
  1. A url property is created, which is the location and name of the image file
  2. The class constructor creates a Loader object, which then instantiates an event listener, which is dispatched when the completeHandler() method completes the image manipulation.
  3. The request URLRequest object is then passed to loader.load(), which loads the image into memory by using a display object.
  4. The image is then placed on the display list, which displays the image on screen at coordinates x = 0, y = 0.
  5. The completeHandler() method then does the following:
    • Creates a second Loader, along with a Bitmap object, which is initialized with the Loader object.
    • Creates a second Bitmap object, duplicate, which in turn calls the duplicateImage() method, which creates a duplicate of the original image.
    • Creates a BitmapData object that is assigned to the duplicate object's BitmapData object.
    • Creates a new Rectangle object initialized with the same coordinates, width, and height as the original image.
    • Creates a new Point object, which defaults to x = 0, y = 0.
    • Creates the following variables:
      • operation — Applies the new color when the threshold value is greater than or equal to the original.
      • threshold — The value against which each pixel is compared (in this example, light gray with an alpha of 0xCC).
      • color — The color that the pixels are set to that pass the threshold test, which is solid yellow in this case.
      • mask — The exact opposite of color (transparent blue).
      • copySource — Set to false, indicating the pixel values are not copied if the threshold value does not pass. This value has no meaning because the image is duplicated and only pixels that pass the threshold test are changed.
    • Calls the threshold() method using the preceding variables. The resulting threshold equation is as follows: if (current pixel Value & 0x000000FF) >= (0xCCCCCCCC & 0x000000FF) then set pixel to 0xFFFFFF00.

Notes:

  • You will need to compile the SWF file with Local Playback Security set to Access Local Files Only.
  • This example requires that a file named Image.gif be placed in the same directory as your SWF file.
  • It is recommended that you use an image of up to approximately 80 pixels in width.

package { import flash.display.Bitmap; import flash.display.BitmapData; import flash.display.Loader; import flash.display.Sprite; import flash.events.*; import flash.geom.Point; import flash.geom.Rectangle; import flash.net.URLRequest; public class BitmapDataExample extends Sprite { private var url:String = "Image.gif"; private var size:uint = 80; public function BitmapDataExample() { configureAssets(); } private function configureAssets():void { var loader:Loader = new Loader(); loader.contentLoaderInfo.addEventListener(Event.COMPLETE, completeHandler); loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler); var request:URLRequest = new URLRequest(url); loader.x = size * numChildren; loader.load(request); addChild(loader); } private function duplicateImage(original:Bitmap):Bitmap { var image:Bitmap = new Bitmap(original.bitmapData.clone()); image.x = size * numChildren; addChild(image); return image; } private function completeHandler(event:Event):void { var loader:Loader = Loader(event.target.loader); var image:Bitmap = Bitmap(loader.content); var duplicate:Bitmap = duplicateImage(image); var bitmapData:BitmapData = duplicate.bitmapData; var sourceRect:Rectangle = new Rectangle(0, 0, bitmapData.width, bitmapData.height); var destPoint:Point = new Point(); var operation:String = ">="; var threshold:uint = 0xCCCCCCCC; var color:uint = 0xFFFFFF00; var mask:uint = 0x000000FF; var copySource:Boolean = true; bitmapData.threshold(bitmapData, sourceRect, destPoint, operation, threshold, color, mask, copySource); } private function ioErrorHandler(event:IOErrorEvent):void { trace("Unable to load image: " + url); } } }
flash.display.Bitmap.bitmapDataflash.desktop.DockIcon.bitmapsflash.display.Graphics.beginBitmapFill()flash.desktop.Icon.bitmapsflash.desktop.InteractiveIcon.bitmapsflash.display.Loaderflash.desktop.SystemTrayIcon.bitmapsBitmapData Creates a BitmapData object with a specified width and height.width and/or height exceed the maximum dimensions. ArgumentErrorArgumentErrorwidthintThe width of the bitmap image in pixels. heightintThe height of the bitmap image in pixels. transparentBooleantrueSpecifies whether the bitmap image supports per-pixel transparency. The default value is true (transparent). To create a fully transparent bitmap, set the value of the transparent parameter to true and the value of the fillColor parameter to 0x00000000 (or to 0). Setting the transparent property to false can result in minor improvements in rendering performance. fillColoruint0xFFFFFFFFA 32-bit ARGB color value that you use to fill the bitmap image area. The default value is 0xFFFFFFFF (solid white). Creates a BitmapData object with a specified width and height. If you specify a value for the fillColor parameter, every pixel in the bitmap is set to that color.

By default, the bitmap is created as transparent, unless you pass the value false for the transparent parameter. After you create an opaque bitmap, you cannot change it to a transparent bitmap. Every pixel in an opaque bitmap uses only 24 bits of color channel information. If you define the bitmap as transparent, every pixel uses 32 bits of color channel information, including an alpha transparency channel.

In AIR 1.5 and Flash Player 10, the maximum size for a BitmapData object is 8,191 pixels in width or height, and the total number of pixels cannot exceed 16,777,215 pixels. (So, if a BitmapData object is 8,191 pixels wide, it can only be 2,048 pixels high.) In Flash Player 9 and earlier and AIR 1.1 and earlier, the limitation is 2,880 pixels in height and 2,880 pixels in width. If you specify a width or height value that is greater than 2880, a new instance is not created.

applyFilter Takes a source image and a filter object and generates the filtered image.The sourceBitmapData, sourceRect, destPoint or filter are null. TypeErrorTypeErrorThe transparency of the BitmapData objects are not compatible with the filter operation. IllegalOperationErrorflash.errors:IllegalOperationErrorA number that indicates whether the filter was applied successfully. If 0 is returned, the filter was applied successfully. If a negative number is returned, an error occurred during the application of the filter. sourceBitmapDataflash.display:BitmapDataThe input bitmap image to use. The source image can be a different BitmapData object or it can refer to the current BitmapData instance. sourceRectflash.geom:RectangleA rectangle that defines the area of the source image to use as input. destPointflash.geom:PointThe point within the destination image (the current BitmapData instance) that corresponds to the upper-left corner of the source rectangle. filterflash.filters:BitmapFilterThe filter object that you use to perform the filtering operation. Each type of filter has certain requirements, as follows:
  • BlurFilter — This filter can use source and destination images that are either opaque or transparent. If the formats of the images do not match, the copy of the source image that is made during the filtering matches the format of the destination image.
  • BevelFilter, DropShadowFilter, GlowFilter, ChromeFilter — The destination image of these filters must be a transparent image. Calling DropShadowFilter or GlowFilter creates an image that contains the alpha channel data of the drop shadow or glow. It does not create the drop shadow onto the destination image. If you use any of these filters with an opaque destination image, an exception is thrown.
  • ConvolutionFilter — This filter can use source and destination images that are either opaque or transparent.
  • ColorMatrixFilter — This filter can use source and destination images that are either opaque or transparent.
  • DisplacementMapFilter — This filter can use source and destination images that are either opaque or transparent, but the source and destination image formats must be the same.
Takes a source image and a filter object and generates the filtered image.

This method relies on the behavior of built-in filter objects, which determine the destination rectangle that is affected by an input source rectangle.

After a filter is applied, the resulting image can be larger than the input image. For example, if you use a BlurFilter class to blur a source rectangle of (50,50,100,100) and a destination point of (10,10), the area that changes in the destination image is larger than (10,10,60,60) because of the blurring. This happens internally during the applyFilter() call.

If the sourceRect parameter of the sourceBitmapData parameter is an interior region, such as (50,50,100,100) in a 200 x 200 image, the filter uses the source pixels outside the sourceRect parameter to generate the destination rectangle.

If the BitmapData object and the object specified as the sourceBitmapData parameter are the same object, the application uses a temporary copy of the object to perform the filter. For best performance, avoid this situation.

The following example shows how to apply a blur filter to a BitmapData instance: import flash.display.Bitmap; import flash.display.BitmapData; import flash.geom.Point; import flash.geom.Rectangle; import flash.filters.BlurFilter; var bmd:BitmapData = new BitmapData(80, 30, false, 0xFFCC00); var rect:Rectangle = new Rectangle(10, 10, 40, 10); bmd.fillRect(rect, 0xFF0000); var pt:Point = new Point(10, 10); var filter:BlurFilter = new BlurFilter(); bmd.applyFilter(bmd, rect, pt, filter); var bm:Bitmap = new Bitmap(bmd); addChild(bm);
flash.filters.BevelFilterflash.filters.BlurFilterflash.filters.ColorMatrixFilterflash.filters.ConvolutionFilterflash.filters.DisplacementMapFilterflash.filters.DropShadowFilterflash.filters.GlowFilterflash.display.DisplayObject.filters
clone Returns a new BitmapData object that is a clone of the original instance with an exact copy of the contained bitmap.A new BitmapData object that is identical to the original. flash.display:BitmapDataReturns a new BitmapData object with an exact copy of the original bitmap. Returns a new BitmapData object that is a clone of the original instance with an exact copy of the contained bitmap. The following example shows how to clone a BitmapData instance, and it shows that when you modify the cloned BitmapData instance, the original remains unmodified: import flash.display.Bitmap; import flash.display.BitmapData; var bmd1:BitmapData = new BitmapData(100, 80, false, 0x00000000); var bmd2:BitmapData = bmd1.clone(); bmd1.setPixel32(1, 1, 0xFFFFFFFF); trace(bmd1.getPixel32(1, 1).toString(16)); // ffffffff trace(bmd2.getPixel32(1, 1).toString(16)); // ff000000 var bm1:Bitmap = new Bitmap(bmd1); this.addChild(bm1); var bm2:Bitmap = new Bitmap(bmd2); bm2.x = 110; this.addChild(bm2); colorTransform Adjusts the color values in a specified area of a bitmap image by using a ColorTransform object.The rect or colorTransform are null. TypeErrorTypeErrorrectflash.geom:RectangleA Rectangle object that defines the area of the image in which the ColorTransform object is applied. colorTransformflash.geom:ColorTransformA ColorTransform object that describes the color transformation values to apply. Adjusts the color values in a specified area of a bitmap image by using a ColorTransform object. If the rectangle matches the boundaries of the bitmap image, this method transforms the color values of the entire image. The following example shows how to apply a color transform to the left half (rectangle) of a BitmapData object: import flash.display.Bitmap; import flash.display.BitmapData; import flash.geom.Rectangle; import flash.geom.ColorTransform; var bmd:BitmapData = new BitmapData(80, 30, false, 0xFF0000); var cTransform:ColorTransform = new ColorTransform(); cTransform.alphaMultiplier = 0.5 var rect:Rectangle = new Rectangle(0, 0, 40, 30); bmd.colorTransform(rect, cTransform); var bm:Bitmap = new Bitmap(bmd); addChild(bm); flash.geom.ColorTransformflash.geom.Rectanglecompare Compares two BitmapData objects.The otherBitmapData is null. TypeErrorTypeErrorIf the two BitmapData objects have the same dimensions (width and height), the method returns a new BitmapData object that has the difference between the two objects (see the main discussion). If the BitmapData objects are equivalent, the method returns the number 0. If the widths of the BitmapData objects are not equal, the method returns the number -3. If the heights of the BitmapData objects are not equal, the method returns the number -4. ObjectotherBitmapDataflash.display:BitmapDataThe BitmapData object to compare with the source BitmapData object. Compares two BitmapData objects. If the two BitmapData objects have the same dimensions (width and height), the method returns a new BitmapData object, in which each pixel is the "difference" between the pixels in the two source objects:
  • If two pixels are equal, the difference pixel is 0x00000000.
  • If two pixels have different RGB values (ignoring the alpha value), the difference pixel is 0xRRGGBB where RR/GG/BB are the individual difference values between red, green, and blue channels (the pixel value in the source object minus the pixel value in the otherBitmapData object). Alpha channel differences are ignored in this case.
  • If only the alpha channel value is different, the pixel value is 0xZZFFFFFF, where ZZ is the difference in the alpha values (the alpha value in the source object minus the alpha value in the otherBitmapData object).

For example, consider the following two BitmapData objects:

var bmd1:BitmapData = new BitmapData(50, 50, true, 0xFFFF8800); var bmd2:BitmapData = new BitmapData(50, 50, true, 0xCCCC6600); var diffBmpData:BitmapData = bmd1.compare(bmd2) as BitmapData; trace ("0x" + diffBmpData.getPixel(0,0).toString(16); // 0x332200

Note: The colors used to fill the two BitmapData objects have slightly different RGB values (0xFF0000 and 0xFFAA00). The result of the compare() method is a new BitmapData object with each pixel showing the difference in the RGB values between the two bitmaps.

Consider the following two BitmapData objects, in which the RGB colors are the same, but the alpha values are different:

var bmd1:BitmapData = new BitmapData(50, 50, true, 0xFFFFAA00); var bmd2:BitmapData = new BitmapData(50, 50, true, 0xCCFFAA00); var diffBmpData:BitmapData = bmd1.compare(bmd2) as BitmapData; trace ("0x" + diffBmpData.getPixel32(0,0).toString(16); // 0x33ffffff

The result of the compare() method is a new BitmapData object with each pixel showing the difference in the alpha values between the two bitmaps.

If the BitmapData objects are equivalent (with the same width, height, and identical pixel values), the method returns the number 0.

If the widths of the BitmapData objects are not equal, the method returns the number -3.

If the heights of the BitmapData objects are not equal, but the widths are the same, the method returns the number -4.

The following example compares two Bitmap objects with different widths (50 and 60):

var bmd1:BitmapData = new BitmapData(100, 50, false, 0xFFFF0000); var bmd2:BitmapData = new BitmapData(100, 60, false, 0xFFFFAA00); trace(bmd1.compare(bmd2)); // -4
The following example shows the value of a pixel in the BitmapData object that results from comparing two BitmapData objects of the same dimensions: import flash.display.Bitmap; import flash.display.BitmapData; var bmd1:BitmapData = new BitmapData(50, 50, true, 0xFFFFAA00); var bmd2:BitmapData = new BitmapData(50, 50, true, 0xCCFFAA00); var diffBmpData:BitmapData = BitmapData(bmd1.compare(bmd2)); var diffValue:String = diffBmpData.getPixel32(1, 1).toString(16); trace (diffValue); // 33ffffff var bm1:Bitmap = new Bitmap(bmd1); addChild(bm1); var bm2:Bitmap = new Bitmap(bmd2); addChild(bm2); bm2.x = 60;
copyChannel Transfers data from one channel of another BitmapData object or the current BitmapData object into a channel of the current BitmapData object.The sourceBitmapData, sourceRect or destPoint are null. TypeErrorTypeErrorsourceBitmapDataflash.display:BitmapDataThe input bitmap image to use. The source image can be a different BitmapData object or it can refer to the current BitmapData object. sourceRectflash.geom:RectangleThe source Rectangle object. To copy only channel data from a smaller area within the bitmap, specify a source rectangle that is smaller than the overall size of the BitmapData object. destPointflash.geom:PointThe destination Point object that represents the upper-left corner of the rectangular area where the new channel data is placed. To copy only channel data from one area to a different area in the destination image, specify a point other than (0,0). sourceChanneluintThe source channel. Use a value from the BitmapDataChannel class (BitmapDataChannel.RED, BitmapDataChannel.BLUE, BitmapDataChannel.GREEN, BitmapDataChannel.ALPHA). destChanneluintThe destination channel. Use a value from the BitmapDataChannel class (BitmapDataChannel.RED, BitmapDataChannel.BLUE, BitmapDataChannel.GREEN, BitmapDataChannel.ALPHA). Transfers data from one channel of another BitmapData object or the current BitmapData object into a channel of the current BitmapData object. All of the data in the other channels in the destination BitmapData object are preserved.

The source channel value and destination channel value can be one of following values:

  • BitmapDataChannel.RED
  • BitmapDataChannel.GREEN
  • BitmapDataChannel.BLUE
  • BitmapDataChannel.ALPHA
The following example shows how to copy the red channel in a BitmapData object to its own blue channel in a 20 x 20 pixel region: import flash.display.Bitmap; import flash.display.BitmapData; import flash.geom.Rectangle; import flash.geom.Point; var bmd:BitmapData = new BitmapData(100, 80, false, 0x00FF0000); var rect:Rectangle = new Rectangle(0, 0, 20, 20); var pt:Point = new Point(10, 10); bmd.copyChannel(bmd, rect, pt, BitmapDataChannel.RED, BitmapDataChannel.BLUE); var bm:Bitmap = new Bitmap(bmd); this.addChild(bm);
flash.geom.Rectangle
copyPixels Provides a fast routine to perform pixel manipulation between images with no stretching, rotation, or color effects.The sourceBitmapData, sourceRect, destPoint are null. TypeErrorTypeErrorsourceBitmapDataflash.display:BitmapDataThe input bitmap image from which to copy pixels. The source image can be a different BitmapData instance, or it can refer to the current BitmapData instance. sourceRectflash.geom:RectangleA rectangle that defines the area of the source image to use as input. destPointflash.geom:PointThe destination point that represents the upper-left corner of the rectangular area where the new pixels are placed. alphaBitmapDataflash.display:BitmapDatanullA secondary, alpha BitmapData object source. alphaPointflash.geom:PointnullThe point in the alpha BitmapData object source that corresponds to the upper-left corner of the sourceRect parameter. mergeAlphaBooleanfalseTo use the alpha channel, set the value to true. To copy pixels with no alpha channel, set the value to false. Provides a fast routine to perform pixel manipulation between images with no stretching, rotation, or color effects. This method copies a rectangular area of a source image to a rectangular area of the same size at the destination point of the destination BitmapData object.

If you include the alphaBitmap and alphaPoint parameters, you can use a secondary image as an alpha source for the source image. If the source image has alpha data, both sets of alpha data are used to composite pixels from the source image to the destination image. The alphaPoint parameter is the point in the alpha image that corresponds to the upper-left corner of the source rectangle. Any pixels outside the intersection of the source image and alpha image are not copied to the destination image.

The mergeAlpha property controls whether or not the alpha channel is used when a transparent image is copied onto another transparent image. To copy pixels with the alpha channel data, set the mergeAlpha property to true. By default, the mergeAlpha property is false.

The following example shows how to copy pixels from a 20 x 20 pixel region in one BitmapData object to another BitmapData object: import flash.display.Bitmap; import flash.display.BitmapData; import flash.geom.Rectangle; import flash.geom.Point; var bmd1:BitmapData = new BitmapData(40, 40, false, 0x000000FF); var bmd2:BitmapData = new BitmapData(80, 40, false, 0x0000CC44); var rect:Rectangle = new Rectangle(0, 0, 20, 20); var pt:Point = new Point(10, 10); bmd2.copyPixels(bmd1, rect, pt); var bm1:Bitmap = new Bitmap(bmd1); this.addChild(bm1); var bm2:Bitmap = new Bitmap(bmd2); this.addChild(bm2); bm2.x = 50;
dispose Frees memory that is used to store the BitmapData object. Frees memory that is used to store the BitmapData object.

When the dispose() method is called on an image, the width and height of the image are set to 0. All subsequent calls to methods or properties of this BitmapData instance fail, and an exception is thrown.

BitmapData.dispose() releases the memory occupied by the actual bitmap data, immediately (a bitmap can consume up to 64 MB of memory). After using BitmapData.dispose(), the BitmapData object is no longer usable and the Flash runtime throws an exception if you call functions on the BitmapData object. However, BitmapData.dispose() does not garbage collect the BitmapData object (approximately 128 bytes); the memory occupied by the actual BitmapData object is released at the time the BitmapData object is collected by the garbage collector.

The following example shows the effect of calling a method of a BitmapData object after a call to the dispose() method (an exception is thrown): import flash.display.BitmapData; var myBitmapData:BitmapData = new BitmapData(100, 80, false, 0x000000FF); trace(myBitmapData.getPixel(1, 1)); // 255 == 0xFF myBitmapData.dispose(); try { trace(myBitmapData.getPixel(1, 1)); } catch (error:Error) { trace(error); // ArgumentError }
flash.system.System.gc()
draw Draws the source display object onto the bitmap image, using the Flash runtime vector renderer.The source parameter is not a BitmapData or DisplayObject object. ArgumentErrorArgumentErrorThe source object and (in the case of a Sprite or MovieClip object) all of its child objects do not come from the same domain as the caller, or are not in a content that is accessible to the caller by having called the Security.allowDomain() method. This restriction does not apply to AIR content in the application security sandbox. SecurityErrorSecurityErrorThe source is null or not a valid IBitmapDrawable object. ArgumentErrorArgumentErrorsourceflash.display:IBitmapDrawableThe display object or BitmapData object to draw to the BitmapData object. (The DisplayObject and BitmapData classes implement the IBitmapDrawable interface.) matrixflash.geom:MatrixnullA Matrix object used to scale, rotate, or translate the coordinates of the bitmap. If you do not want to apply a matrix transformation to the image, set this parameter to an identity matrix, created with the default new Matrix() constructor, or pass a null value. colorTransformflash.geom:ColorTransformnullA ColorTransform object that you use to adjust the color values of the bitmap. If no object is supplied, the bitmap image's colors are not transformed. If you must pass this parameter but you do not want to transform the image, set this parameter to a ColorTransform object created with the default new ColorTransform() constructor. blendModeStringnullA string value, from the flash.display.BlendMode class, specifying the blend mode to be applied to the resulting bitmap. clipRectflash.geom:RectanglenullA Rectangle object that defines the area of the source object to draw. If you do not supply this value, no clipping occurs and the entire source object is drawn. smoothingBooleanfalseA Boolean value that determines whether a BitmapData object is smoothed when scaled or rotated, due to a scaling or rotation in the matrix parameter. The smoothing parameter only applies if the source parameter is a BitmapData object. With smoothing set to false, the rotated or scaled BitmapData image can appear pixelated or jagged. For example, the following two images use the same BitmapData object for the source parameter, but the smoothing parameter is set to true on the left and false on the right:

Drawing a bitmap with smoothing set to true takes longer than doing so with smoothing set to false.

Draws the source display object onto the bitmap image, using the Flash runtime vector renderer. You can specify matrix, colorTransform, blendMode, and a destination clipRect parameter to control how the rendering performs. Optionally, you can specify whether the bitmap should be smoothed when scaled (this works only if the source object is a BitmapData object).

This method directly corresponds to how objects are drawn with the standard vector renderer for objects in the authoring tool interface.

The source display object does not use any of its applied transformations for this call. It is treated as it exists in the library or file, with no matrix transform, no color transform, and no blend mode. To draw a display object (such as a movie clip) by using its own transform properties, you can copy its transform property object to the transform property of the Bitmap object that uses the BitmapData object.

This method is supported over RTMP in Flash Player 9.0.115.0 and later and in Adobe AIR. You can control access to streams on Flash Media Server in a server-side script. For more information, see the Client.audioSampleAccess and Client.videoSampleAccess properties in Server-Side ActionScript Language Reference for Adobe Flash Media Server.

If the source object and (in the case of a Sprite or MovieClip object) all of its child objects do not come from the same domain as the caller, or are not in a content that is accessible to the caller by having called the Security.allowDomain() method, a call to the draw() throws a SecurityError exception. This restriction does not apply to AIR content in the application security sandbox.

There are also restrictions on using a loaded bitmap image as the source. A call to the draw() method is successful if the loaded image comes from the same domain as the caller. Also, a cross-domain policy file on the image's server can grant permission to the domain of the SWF content calling the draw() method. In this case, you must set the checkPolicyFile property of a LoaderContext object, and use this object as the context parameter when calling the load() method of the Loader object used to load the image. These restrictions do not apply to AIR content in the application security sandbox.

On Windows, the draw() method cannot capture SWF content embedded in an HTML page in an HTMLLoader object in Adobe AIR.

The draw() method cannot capture PDF content in Adobe AIR. Nor can it capture or SWF content embedded in HTML in which the wmode attribute is set to "window" in Adobe AIR.

The following example shows how to draw a TextField object to a BitmapData object: import flash.display.Bitmap; import flash.display.BitmapData; import flash.text.TextField; var tf:TextField = new TextField(); tf.text = "bitmap text"; var myBitmapData:BitmapData = new BitmapData(80, 20); myBitmapData.draw(tf); var bmp:Bitmap = new Bitmap(myBitmapData); this.addChild(bmp);
flash.display.BlendModeflash.geom.ColorTransformflash.geom.Matrixflash.system.JPEGLoaderContext
fillRect Fills a rectangular area of pixels with a specified ARGB color.The rect is null. TypeErrorTypeErrorrectflash.geom:RectangleThe rectangular area to fill. coloruintThe ARGB color value that fills the area. ARGB colors are often specified in hexadecimal format; for example, 0xFF336699. Fills a rectangular area of pixels with a specified ARGB color. The following example shows how to fill a rectangular region of a BitmapData object with blue: import flash.display.Bitmap; import flash.display.BitmapData; import flash.geom.Rectangle; var myBitmapData:BitmapData = new BitmapData(40, 40, false, 0x0000FF00); var rect:Rectangle = new Rectangle(0, 0, 20, 20); myBitmapData.fillRect(rect, 0x0000FF); var bm:Bitmap = new Bitmap(myBitmapData); addChild(bm); flash.geom.RectanglefloodFill Performs a flood fill operation on an image starting at an (x, y) coordinate and filling with a certain color.xintThe x coordinate of the image. yintThe y coordinate of the image. coloruintThe ARGB color to use as a fill. Performs a flood fill operation on an image starting at a (x, y) coordinate. Performs a flood fill operation on an image starting at an (x, y) coordinate and filling with a certain color. The floodFill() method is similar to the paint bucket tool in various paint programs. The color is an ARGB color that contains alpha information and color information. The following example shows how to fill a region of a BitmapData object — that is, the region surrounding the pixel defined by the point (10, 10) in which all colors match the color at that point — with red import flash.display.Bitmap; import flash.display.BitmapData; import flash.geom.Rectangle; var myBitmapData:BitmapData = new BitmapData(40, 40, false, 0x0000FF00); var rect:Rectangle = new Rectangle(0, 0, 20, 20); myBitmapData.fillRect(rect, 0x000000FF); rect = new Rectangle(15, 15, 25, 25); myBitmapData.fillRect(rect, 0x000000FF); myBitmapData.floodFill(10, 10, 0x00FF0000); var bm:Bitmap = new Bitmap(myBitmapData); addChild(bm); generateFilterRect Determines the destination rectangle that the applyFilter() method call affects, given a BitmapData object, a source rectangle, and a filter object.The sourceRect or filter are null. TypeErrorTypeErrorA destination rectangle computed by using an image, the sourceRect parameter, and a filter. flash.geom:RectanglesourceRectflash.geom:RectangleA rectangle defining the area of the source image to use as input. filterflash.filters:BitmapFilterA filter object that you use to calculate the destination rectangle. Determines the destination rectangle that will be affected by the applyFilter() call. Determines the destination rectangle that the applyFilter() method call affects, given a BitmapData object, a source rectangle, and a filter object.

For example, a blur filter normally affects an area larger than the size of the original image. A 100 x 200 pixel image that is being filtered by a default BlurFilter instance, where blurX = blurY = 4 generates a destination rectangle of (-2,-2,104,204). The generateFilterRect() method lets you find out the size of this destination rectangle in advance so that you can size the destination image appropriately before you perform a filter operation.

Some filters clip their destination rectangle based on the source image size. For example, an inner DropShadow does not generate a larger result than its source image. In this API, the BitmapData object is used as the source bounds and not the source rect parameter.

The following example shows how you can use the generateFilterRect() method to determine the rectangular area that the result of a blur filter will occupy. The results of the generateFilterRect() method are output by the trace() function: import flash.display.Bitmap; import flash.display.BitmapData; import flash.geom.Point; import flash.geom.Rectangle; import flash.filters.BlurFilter; var bmd:BitmapData = new BitmapData(80, 30, false, 0xFFCC00); var rect:Rectangle = new Rectangle(10, 10, 40, 10); bmd.fillRect(rect, 0xFF0000); var pt:Point = new Point(10, 10); var filter:BlurFilter = new BlurFilter(); trace(bmd.generateFilterRect(rect, filter)); // (x=8, y=8, w=44, h=14) bmd.applyFilter(bmd, rect, pt, filter); var bm:Bitmap = new Bitmap(bmd); addChild(bm); Note that the generateFilterRect() method does not apply the filter. Call the applyFilter() method to apply the filter.
getColorBoundsRect Determines a rectangular region that either fully encloses all pixels of a specified color within the bitmap image (if the findColor parameter is set to true) or fully encloses all pixels that do not include the specified color (if the findColor parameter is set to false).The region of the image that is the specified color. flash.geom:RectanglemaskuintA hexadecimal value, specifying the bits of the ARGB color to consider. The color value is combined with this hexadecimal value, by using the & (bitwise AND) operator. coloruintA hexadecimal value, specifying the ARGB color to match (if findColor is set to true) or not to match (if findColor is set to false). findColorBooleantrueIf the value is set to true, returns the bounds of a color value in an image. If the value is set to false, returns the bounds of where this color doesn't exist in an image. Determines a rectangular region that either fully encloses all pixels of a specified color within the bitmap image (if the findColor parameter is set to true) or fully encloses all pixels that do not include the specified color (if the findColor parameter is set to false).

For example, if you have a source image and you want to determine the rectangle of the image that contains a nonzero alpha channel, pass {mask: 0xFF000000, color: 0x00000000} as parameters. If the findColor parameter is set to true, the entire image is searched for the bounds of pixels for which (value & mask) == color (where value is the color value of the pixel). If the findColor parameter is set to false, the entire image is searched for the bounds of pixels for which (value & mask) != color (where value is the color value of the pixel). To determine white space around an image, pass {mask: 0xFFFFFFFF, color: 0xFFFFFFFF} to find the bounds of nonwhite pixels.

The following example creates a BitmapData object with red in the top half of its pixels. It then calls the getColorBoundsRect() method to determine the rectangle in which pixels are red (0xFF0000), and then it calls the same method to determine the rectangle in which pixels are not red (by setting the findColor parameter to false: import flash.display.Bitmap; import flash.display.BitmapData; import flash.geom.Rectangle; var bmd:BitmapData = new BitmapData(80, 40, false, 0xFFFFFF); var rect:Rectangle = new Rectangle(0, 0, 80, 20); bmd.fillRect(rect, 0xFF0000); var maskColor:uint = 0xFFFFFF; var color:uint = 0xFF0000; var redBounds:Rectangle = bmd.getColorBoundsRect(maskColor, color, true); trace(redBounds); // (x=0, y=0, w=80, h=20) var notRedBounds:Rectangle = bmd.getColorBoundsRect(maskColor, color, false); trace(notRedBounds); // (x=0, y=20, w=80, h=20) var bm:Bitmap = new Bitmap(bmd); addChild(bm);
getPixel32 Returns an ARGB color value that contains alpha channel data and RGB data.A number representing an ARGB pixel value. If the (x, y) coordinates are outside the bounds of the image, 0 is returned. uintxintThe x position of the pixel. yintThe y position of the pixel. Returns an ARGB color value that contains alpha channel data and RGB data. This method is similar to the getPixel() method, which returns an RGB color without alpha channel data.

All pixels in a BitmapData object are stored as premultiplied color values. A premultiplied image pixel has the red, green, and blue color channel values already multiplied by the alpha data. For example, if the alpha value is 0, the values for the RGB channels are also 0, independent of their unmultiplied values. This loss of data can cause some problems when you perform operations. All BitmapData methods take and return unmultiplied values. The internal pixel representation is converted from premultiplied to unmultiplied before it is returned as a value. During a set operation, the pixel value is premultiplied before the raw image pixel is set.

The following example creates a BitmapData object filled with a color, then uses the getPixel32() method to determine the color value in the upper-left pixel, and then determines the hexidecimal values for each color component (alpha, red, green, and blue): import flash.display.BitmapData; var bmd:BitmapData = new BitmapData(80, 40, true, 0xFF44AACC); var pixelValue:uint = bmd.getPixel32(0, 0); var alphaValue:uint = pixelValue >> 24 & 0xFF; var red:uint = pixelValue >> 16 & 0xFF; var green:uint = pixelValue >> 8 & 0xFF; var blue:uint = pixelValue & 0xFF; trace(alphaValue.toString(16)); // ff trace(red.toString(16)); // 44 trace(green.toString(16)); // aa trace(blue.toString(16)); // cc
getPixel()setPixel32()
getPixel Returns an integer that represents an RGB pixel value from a BitmapData object at a specific point (x, y).A number that represents an RGB pixel value. If the (x, y) coordinates are outside the bounds of the image, the method returns 0. uintxintThe x position of the pixel. yintThe y position of the pixel. Returns an integer representing a RGB pixel value from a BitmapData object at a specific point. Returns an integer that represents an RGB pixel value from a BitmapData object at a specific point (x, y). The getPixel() method returns an unmultiplied pixel value. No alpha information is returned.

All pixels in a BitmapData object are stored as premultiplied color values. A premultiplied image pixel has the red, green, and blue color channel values already multiplied by the alpha data. For example, if the alpha value is 0, the values for the RGB channels are also 0, independent of their unmultiplied values. This loss of data can cause some problems when you perform operations. All BitmapData methods take and return unmultiplied values. The internal pixel representation is converted from premultiplied to unmultiplied before it is returned as a value. During a set operation, the pixel value is premultiplied before the raw image pixel is set.

The following example creates a BitmapData object filled with red, then uses the getPixel() method to determine the color value in the upper-left pixel: import flash.display.BitmapData; var bmd:BitmapData = new BitmapData(80, 40, false, 0xFF0000); var pixelValue:uint = bmd.getPixel(0, 0); trace(pixelValue.toString(16)); // ff0000;
getPixel32()setPixel()
getPixels Generates a byte array from a rectangular region of pixel data.The rect is null. TypeErrorTypeErrorA ByteArray representing the pixels in the given Rectangle. flash.utils:ByteArrayrectflash.geom:RectangleA rectangular area in the current BitmapData object. Generates a byte array from a rectangular region of pixel data. Writes an unsigned integer (a 32-bit unmultiplied pixel value) for each pixel into the byte array. The following example creates a BitmapData object filled with random noise pixels, then uses the getPixels() method to fill a ByteArray object with the pixel values of the BitmapData object import flash.display.BitmapData; import flash.geom.Rectangle; import flash.utils.ByteArray; var bmd:BitmapData = new BitmapData(80, 40, true); var seed:int = int(Math.random() * int.MAX_VALUE); bmd.noise(seed); var bounds:Rectangle = new Rectangle(0, 0, bmd.width, bmd.height); var pixels:ByteArray = bmd.getPixels(bounds); flash.utils.ByteArraygetVector Generates a vector array from a rectangular region of pixel data.The rect is null. TypeErrorTypeErrorA Vector representing the given Rectangle. rectflash.geom:RectangleA rectangular area in the current BitmapData object. Generates a vector array from a rectangular region of pixel data. Returns a Vector object of unsigned integers (a 32-bit unmultiplied pixel value) for the specified rectangle. histogram Computes a 256-value binary number histogram of a BitmapData object.hRectflash.geom:RectanglenullThe area of the BitmapData object to use. Computes a 256-value binary number histogram of a BitmapData object. This method returns a Vector object containing four Vector.<Number> instances (four Vector objects that contain Number objects). The four Vector instances represent the red, green, blue and alpha components in order. Each Vector instance contains 256 values that represent the population count of an individual component value, from 0 to 255. hitTest Performs pixel-level hit detection between one bitmap image and a point, rectangle, or other bitmap image.The secondObject parameter is not a Point, Rectangle, Bitmap, or BitmapData object. ArgumentErrorArgumentErrorThe firstPoint is null. TypeErrorTypeErrorA value of true if a hit occurs; otherwise, false. BooleanfirstPointflash.geom:Point A position of the upper-left corner of the BitmapData image in an arbitrary coordinate space. The same coordinate space is used in defining the secondBitmapPoint parameter. firstAlphaThresholduintThe smallest alpha channel value that is considered opaque for this hit test. secondObjectObjectA Rectangle, Point, Bitmap, or BitmapData object. secondBitmapDataPointflash.geom:PointnullA point that defines a pixel location in the second BitmapData object. Use this parameter only when the value of secondObject is a BitmapData object. secondAlphaThresholduint1The smallest alpha channel value that is considered opaque in the second BitmapData object. Use this parameter only when the value of secondObject is a BitmapData object and both BitmapData objects are transparent. Performs pixel-level hit detection between one bitmap image and a point, rectangle, or other bitmap image. A hit is defined as an overlap of a point or rectangle over an opaque pixel, or two overlapping opaque pixels. No stretching, rotation, or other transformation of either object is considered when the hit test is performed.

If an image is an opaque image, it is considered a fully opaque rectangle for this method. Both images must be transparent images to perform pixel-level hit testing that considers transparency. When you are testing two transparent images, the alpha threshold parameters control what alpha channel values, from 0 to 255, are considered opaque.

The following example creates a BitmapData object that is only opaque in a rectangular region (20, 20, 40, 40) and calls the hitTest() method with a Point object as the secondObject. In the first call, the Point object defines the upper-left corner of the BitmapData object, which is not opaque, and in the second call, the Point object defines the center of the BitmapData object, which is opaque. import flash.display.BitmapData; import flash.geom.Rectangle; import flash.geom.Point; var bmd1:BitmapData = new BitmapData(80, 80, true, 0x00000000); var rect:Rectangle = new Rectangle(20, 20, 40, 40); bmd1.fillRect(rect, 0xFF0000FF); var pt1:Point = new Point(1, 1); trace(bmd1.hitTest(pt1, 0xFF, pt1)); // false var pt2:Point = new Point(40, 40); trace(bmd1.hitTest(pt1, 0xFF, pt2)); // true
lock Locks an image so that any objects that reference the BitmapData object, such as Bitmap objects, are not updated when this BitmapData object changes. Locks an image so that any objects that reference the BitmapData object, such as Bitmap objects, are not updated when this BitmapData object changes. To improve performance, use this method along with the unlock() method before and after numerous calls to the setPixel() or setPixel32() method. The following example creates a BitmapData object based on the bitmapData property of a Bitmap object, picture. It then calls the lock() method before calling a complicated custom function, complexTransformation(), that modifies the BitmapData object. (The picture object and the complexTransformation() function are not defined in this example.) Even if the complexTransformation() function updates the bitmapData property of the picture object, changes are not reflected until the code calls the unlock() method on the bitmapData object: import flash.display.BitmapData; var bitmapData:BitmapData = picture.bitmapData; bitmapData.lock(); bitmapData = complexTransformation(bitmapData); bitmapData.unlock(); picture.bitmapData = bitmapData; setPixel()setPixel32()unlock()merge Performs per-channel blending from a source image to a destination image.The sourceBitmapData, sourceRect or destPoint are null. TypeErrorTypeErrorsourceBitmapDataflash.display:BitmapDataThe input bitmap image to use. The source image can be a different BitmapData object, or it can refer to the current BitmapData object. sourceRectflash.geom:RectangleA rectangle that defines the area of the source image to use as input. destPointflash.geom:PointThe point within the destination image (the current BitmapData instance) that corresponds to the upper-left corner of the source rectangle. redMultiplieruintA hexadecimal uint value by which to multiply the red channel value. greenMultiplieruintA hexadecimal uint value by which to multiply the green channel value. blueMultiplieruintA hexadecimal uint value by which to multiply the blue channel value. alphaMultiplieruintA hexadecimal uint value by which to multiply the alpha transparency value. Performs per-channel blending from a source image to a destination image. For each channel and each pixel, a new value is computed based on the channel values of the source and destination pixels. For example, in the red channel, the new value is computed as follows (where redSrc is the red channel value for a pixel in the source image and redDest is the red channel value at the corresponding pixel of the destination image):

new redDest = [(redSrc * redMultiplier) + (redDest * (256 - redMultiplier))] / 256;

The redMultiplier, greenMultiplier, blueMultiplier, and alphaMultiplier values are the multipliers used for each color channel. Use a hexadecimal value ranging from 0 to 0x100 (256) where 0 specifies the full value from the destination is used in the result, 0x100 specifies the full value from the source is used, and numbers in between specify a blend is used (such as 0x80 for 50%).

The following example creates two BitmapData objects. Both are 100 x 80 pixels in size. The first is filled with green and the second is filled with red. The code calls the merge() method, merging the second BitmapData pixels into the first BitmapData object, but only on a specified rectangular area: import flash.display.Bitmap; import flash.display.BitmapData; import flash.geom.Rectangle; import flash.geom.Point; var bmd1:BitmapData = new BitmapData(100, 80, true, 0xFF00FF00); var bmd2:BitmapData = new BitmapData(100, 80, true, 0xFFFF0000); var rect:Rectangle = new Rectangle(0, 0, 20, 20); var pt:Point = new Point(20, 20); var mult:uint = 0x80; // 50% bmd1.merge(bmd2, rect, pt, mult, mult, mult, mult); var bm1:Bitmap = new Bitmap(bmd1); addChild(bm1); var bm2:Bitmap = new Bitmap(bmd2); addChild(bm2); bm2.x = 110;
noise Fills an image with pixels representing random noise.randomSeedintThe random seed number to use. If you keep all other parameters the same, you can generate different pseudo-random results by varying the random seed value. The noise function is a mapping function, not a true random-number generation function, so it creates the same results each time from the same random seed. lowuint0The lowest value to generate for each channel (0 to 255). highuint255The highest value to generate for each channel (0 to 255). channelOptionsuint7A number that can be a combination of any of the four color channel values (BitmapDataChannel.RED, BitmapDataChannel.BLUE, BitmapDataChannel.GREEN, and BitmapDataChannel.ALPHA). You can use the logical OR operator (|) to combine channel values. grayScaleBooleanfalseA Boolean value. If the value is true, a grayscale image is created by setting all of the color channels to the same value. The alpha channel selection is not affected by setting this parameter to true. Fills an image with pixels representing random noise. The following example creates two BitmapData objects and calls the noise() method on both. However, the grayscale parameter is set to false for the call to the noise() method of the first object, and it is set to true for the call to the noise() method of the second object: import flash.display.Bitmap; import flash.display.BitmapData; import flash.display.BitmapDataChannel; var bmd1:BitmapData = new BitmapData(80, 80); var bmd2:BitmapData = new BitmapData(80, 80); var seed:int = int(Math.random() * int.MAX_VALUE); bmd1.noise(seed, 0, 0xFF, BitmapDataChannel.RED, false); bmd2.noise(seed, 0, 0xFF, BitmapDataChannel.RED, true); var bm1:Bitmap = new Bitmap(bmd1); this.addChild(bm1); var bm2:Bitmap = new Bitmap(bmd2); this.addChild(bm2); bm2.x = 90; flash.display.BitmapDataChannel.REDflash.display.BitmapDataChannel.BLUEflash.display.BitmapDataChannel.GREENflash.display.BitmapDataChannel.ALPHApaletteMap Remaps the color channel values in an image that has up to four arrays of color palette data, one for each channel.The sourceBitmapData, sourceRect or destPoint are null. TypeErrorTypeErrorsourceBitmapDataflash.display:BitmapDataThe input bitmap image to use. The source image can be a different BitmapData object, or it can refer to the current BitmapData instance. sourceRectflash.geom:RectangleA rectangle that defines the area of the source image to use as input. destPointflash.geom:PointThe point within the destination image (the current BitmapData object) that corresponds to the upper-left corner of the source rectangle. redArrayArraynullIf redArray is not null, red = redArray[source red value] else red = source rect value. greenArrayArraynullIf greenArray is not null, green = greenArray[source green value] else green = source green value. blueArrayArraynullIf blueArray is not null, blue = blueArray[source blue value] else blue = source blue value. alphaArrayArraynullIf alphaArray is not null, alpha = alphaArray[source alpha value] else alpha = source alpha value. Remaps the color channel values in an image that has up to four arrays of color palette data, one for each channel.

Flash runtimes use the following steps to generate the resulting image:

  1. After the red, green, blue, and alpha values are computed, they are added together using standard 32-bit-integer arithmetic.
  2. The red, green, blue, and alpha channel values of each pixel are extracted into separate 0 to 255 values. These values are used to look up new color values in the appropriate array: redArray, greenArray, blueArray, and alphaArray. Each of these four arrays should contain 256 values.
  3. After all four of the new channel values are retrieved, they are combined into a standard ARGB value that is applied to the pixel.

Cross-channel effects can be supported with this method. Each input array can contain full 32-bit values, and no shifting occurs when the values are added together. This routine does not support per-channel clamping.

If no array is specified for a channel, the color channel is copied from the source image to the destination image.

You can use this method for a variety of effects such as general palette mapping (taking one channel and converting it to a false color image). You can also use this method for a variety of advanced color manipulation algorithms, such as gamma, curves, levels, and quantizing.

The following example creates a green BitmapData object with a red center square, and then uses the paletteMap() method to swap red with green in the bottom rectangular half of the BitmapData object: import flash.display.Bitmap; import flash.display.BitmapData; import flash.geom.Rectangle; import flash.geom.Point; var myBitmapData:BitmapData = new BitmapData(80, 80, false, 0x00FF0000); myBitmapData.fillRect(new Rectangle(20, 20, 40, 40), 0x0000FF00); var redArray:Array = new Array(256); var greenArray:Array = new Array(256); for(var i:uint = 0; i < 255; i++) { redArray[i] = 0x00000000; greenArray[i] = 0x00000000; } redArray[0xFF] = 0x0000FF00; greenArray[0xFF] = 0x00FF0000; var bottomHalf:Rectangle = new Rectangle(0, 0, 100, 40); var pt:Point = new Point(0, 0); myBitmapData.paletteMap(myBitmapData, bottomHalf, pt, redArray, greenArray); var bm1:Bitmap = new Bitmap(myBitmapData); addChild(bm1);
perlinNoise Generates a Perlin noise image.baseXNumberFrequency to use in the x direction. For example, to generate a noise that is sized for a 64 x 128 image, pass 64 for the baseX value. baseYNumberFrequency to use in the y direction. For example, to generate a noise that is sized for a 64 x 128 image, pass 128 for the baseY value. numOctavesuintNumber of octaves or individual noise functions to combine to create this noise. Larger numbers of octaves create images with greater detail. Larger numbers of octaves also require more processing time. randomSeedintThe random seed number to use. If you keep all other parameters the same, you can generate different pseudo-random results by varying the random seed value. The Perlin noise function is a mapping function, not a true random-number generation function, so it creates the same results each time from the same random seed. stitchBooleanA Boolean value. If the value is true, the method attempts to smooth the transition edges of the image to create seamless textures for tiling as a bitmap fill. fractalNoiseBooleanA Boolean value. If the value is true, the method generates fractal noise; otherwise, it generates turbulence. An image with turbulence has visible discontinuities in the gradient that can make it better approximate sharper visual effects like flames and ocean waves. channelOptionsuint7 A number that can be a combination of any of the four color channel values (BitmapDataChannel.RED, BitmapDataChannel.BLUE, BitmapDataChannel.GREEN, and BitmapDataChannel.ALPHA). You can use the logical OR operator (|) to combine channel values. grayScaleBooleanfalseA Boolean value. If the value is true, a grayscale image is created by setting each of the red, green, and blue color channels to identical values. The alpha channel value is not affected if this value is set to true. offsetsArraynullAn array of points that correspond to x and y offsets for each octave. By manipulating the offset values you can smoothly scroll the layers of a perlinNoise image. Each point in the offset array affects a specific octave noise function. Generates a Perlin noise image.

The Perlin noise generation algorithm interpolates and combines individual random noise functions (called octaves) into a single function that generates more natural-seeming random noise. Like musical octaves, each octave function is twice the frequency of the one before it. Perlin noise has been described as a "fractal sum of noise" because it combines multiple sets of noise data with different levels of detail.

You can use Perlin noise functions to simulate natural phenomena and landscapes, such as wood grain, clouds, and mountain ranges. In most cases, the output of a Perlin noise function is not displayed directly but is used to enhance other images and give them pseudo-random variations.

Simple digital random noise functions often produce images with harsh, contrasting points. This kind of harsh contrast is not often found in nature. The Perlin noise algorithm blends multiple noise functions that operate at different levels of detail. This algorithm results in smaller variations among neighboring pixel values.

The following example creates a 200 x 200 pixel BitmapData object that calls the perlinNoise() method to generate a red and blue watercolor effect: import flash.display.Bitmap; import flash.display.BitmapData; var bmd:BitmapData = new BitmapData(200, 200, false, 0x00CCCCCC); var seed:Number = Math.floor(Math.random() * 10); var channels:uint = BitmapDataChannel.RED | BitmapDataChannel.BLUE; bmd.perlinNoise(100, 80, 6, seed, false, true, channels, false, null); var bm:Bitmap = new Bitmap(bmd); addChild(bm);
pixelDissolve Performs a pixel dissolve either from a source image to a destination image or by using the same image.The sourceBitmapData, sourceRect or destPoint are null. TypeErrorTypeErrorThe numPixels value is negative TypeErrorTypeErrorThe new random seed value to use for subsequent calls. intsourceBitmapDataflash.display:BitmapDataThe input bitmap image to use. The source image can be a different BitmapData object, or it can refer to the current BitmapData instance. sourceRectflash.geom:RectangleA rectangle that defines the area of the source image to use as input. destPointflash.geom:PointThe point within the destination image (the current BitmapData instance) that corresponds to the upper-left corner of the source rectangle. randomSeedint0The random seed to use to start the pixel dissolve. numPixelsint0The default is 1/30 of the source area (width x height). fillColoruint0An ARGB color value that you use to fill pixels whose source value equals its destination value. Performs a pixel dissolve either from a source image to a destination image or by using the same image. Flash runtimes use a randomSeed value to generate a random pixel dissolve. The return value of the function must be passed in on subsequent calls to continue the pixel dissolve until it is finished.

If the source image does not equal the destination image, pixels are copied from the source to the destination by using all of the properties. This process allows dissolving from a blank image into a fully populated image.

If the source and destination images are equal, pixels are filled with the color parameter. This process allows dissolving away from a fully populated image. In this mode, the destination point parameter is ignored.

The following example uses the pixelDissolve() method to convert a grey BitmapData object to a red one by dissolving 40 pixels at a time until all pixels have changed colors: import flash.display.BitmapData; import flash.display.Bitmap; import flash.geom.Point; import flash.geom.Rectangle; import flash.utils.Timer; import flash.events.TimerEvent; var bmd:BitmapData = new BitmapData(100, 80, false, 0x00CCCCCC); var bitmap:Bitmap = new Bitmap(bmd); addChild(bitmap); var tim:Timer = new Timer(20); tim.start(); tim.addEventListener(TimerEvent.TIMER, timerHandler); function timerHandler(event:TimerEvent):void { var randomNum:Number = Math.floor(Math.random() * int.MAX_VALUE); dissolve(randomNum); } function dissolve(randomNum:Number):void { var rect:Rectangle = bmd.rect; var pt:Point = new Point(0, 0); var numberOfPixels:uint = 100; var red:uint = 0x00FF0000; bmd.pixelDissolve(bmd, rect, pt, randomNum, numberOfPixels, red); var grayRegion:Rectangle = bmd.getColorBoundsRect(0xFFFFFFFF, 0x00CCCCCC, true); if(grayRegion.width == 0 && grayRegion.height == 0 ) { tim.stop(); } }
scroll Scrolls an image by a certain (x, y) pixel amount.xintThe amount by which to scroll horizontally. yintThe amount by which to scroll vertically. Scrolls an image by a certain (x, y) pixel amount. Edge regions outside the scrolling area are left unchanged. The following example shows the effect of scrolling a Bitmap data object 40 pixels to the right: import flash.display.Bitmap; import flash.display.BitmapData; import flash.geom.Rectangle; var bmd:BitmapData = new BitmapData(80, 80, true, 0xFFCCCCCC); var rect:Rectangle = new Rectangle(0, 0, 40, 40); bmd.fillRect(rect, 0xFFFF0000); var bm:Bitmap = new Bitmap(bmd); addChild(bm); trace (bmd.getPixel32(50, 20).toString(16)); // ffcccccccc bmd.scroll(30, 0); trace (bmd.getPixel32(50, 20).toString(16)); // ffff0000 setPixel32 Sets the color and alpha transparency values of a single pixel of a BitmapData object.xintThe x position of the pixel whose value changes. yintThe y position of the pixel whose value changes. coloruintThe resulting ARGB color for the pixel. If the bitmap is opaque (not transparent), the alpha transparency portion of this color value is ignored. Sets the color and alpha transparency values of a single pixel of a BitmapData object. This method is similar to the setPixel() method; the main difference is that the setPixel32() method takes an ARGB color value that contains alpha channel information.

All pixels in a BitmapData object are stored as premultiplied color values. A premultiplied image pixel has the red, green, and blue color channel values already multiplied by the alpha data. For example, if the alpha value is 0, the values for the RGB channels are also 0, independent of their unmultiplied values. This loss of data can cause some problems when you perform operations. All BitmapData methods take and return unmultiplied values. The internal pixel representation is converted from premultiplied to unmultiplied before it is returned as a value. During a set operation, the pixel value is premultiplied before the raw image pixel is set.

Note: To increase performance, when you use the setPixel() or setPixel32() method repeatedly, call the lock() method before you call the setPixel() or setPixel32() method, and then call the unlock() method when you have made all pixel changes. This process prevents objects that reference this BitmapData instance from updating until you finish making the pixel changes.

The following example uses the setPixel32() method to draw a transparent (alpha == 0x60) red line in a BitmapData object: import flash.display.Bitmap; import flash.display.BitmapData; var bmd:BitmapData = new BitmapData(80, 80, true, 0xFFCCCCCC); for (var i:uint = 0; i < 80; i++) { var red:uint = 0x60FF0000; bmd.setPixel32(i, 40, red); } var bm:Bitmap = new Bitmap(bmd); addChild(bm);
setPixel()getPixel32()lock()unlock()
setPixel Sets a single pixel of a BitmapData object.xintThe x position of the pixel whose value changes. yintThe y position of the pixel whose value changes. coloruintThe resulting RGB color for the pixel. Sets a single pixel of a BitmapData object. The current alpha channel value of the image pixel is preserved during this operation. The value of the RGB color parameter is treated as an unmultiplied color value.

Note: To increase performance, when you use the setPixel() or setPixel32() method repeatedly, call the lock() method before you call the setPixel() or setPixel32() method, and then call the unlock() method when you have made all pixel changes. This process prevents objects that reference this BitmapData instance from updating until you finish making the pixel changes.

The following example uses the setPixel() method to draw a red line in a BitmapData object: import flash.display.Bitmap; import flash.display.BitmapData; var bmd:BitmapData = new BitmapData(80, 80, false, 0xCCCCCC); for (var i:uint = 0; i < 80; i++) { var red:uint = 0xFF0000; bmd.setPixel(i, 40, red); } var bm:Bitmap = new Bitmap(bmd); addChild(bm);
getPixel()setPixel32()lock()unlock()
setPixels Converts a byte array into a rectangular region of pixel data.The inputByteArray object does not include enough data to fill the area of the rect rectangle. The method fills as many pixels as possible before throwing the exception. EOFErrorflash.errors:EOFErrorThe rect or inputByteArray are null. TypeErrorTypeErrorrectflash.geom:RectangleSpecifies the rectangular region of the BitmapData object. inputByteArrayflash.utils:ByteArrayA ByteArray object that consists of 32-bit unmultiplied pixel values to be used in the rectangular region. Converts a byte array into a rectangular region of pixel data. For each pixel, the ByteArray.readUnsignedInt() method is called and the return value is written into the pixel. If the byte array ends before the full rectangle is written, the function returns. The data in the byte array is expected to be 32-bit ARGB pixel values. No seeking is performed on the byte array before or after the pixels are read. The following example uses the getPixels() and setPixels() methods to copy pixels from one BitmapData object to another: import flash.display.Bitmap; import flash.display.BitmapData; import flash.utils.ByteArray; import flash.geom.Rectangle; var bmd1:BitmapData = new BitmapData(100, 100, true, 0xFFCCCCCC); var bmd2:BitmapData = new BitmapData(100, 100, true, 0xFFFF0000); var rect:Rectangle = new Rectangle(0, 0, 100, 100); var bytes:ByteArray = bmd1.getPixels(rect); bytes.position = 0; bmd2.setPixels(rect, bytes); var bm1:Bitmap = new Bitmap(bmd1); addChild(bm1); var bm2:Bitmap = new Bitmap(bmd2); addChild(bm2); bm2.x = 110; flash.utils.ByteArray.readUnsignedInt()setVector Converts a Vector into a rectangular region of pixel data.The vector array is not large enough to read all the pixel data. RangeErrorRangeErrorrectflash.geom:RectangleSpecifies the rectangular region of the BitmapData object. inputVectorA Vector object that consists of 32-bit unmultiplied pixel values to be used in the rectangular region. Converts a Vector into a rectangular region of pixel data. For each pixel, a Vector element is read and written into the BitmapData pixel. The data in the Vector is expected to be 32-bit ARGB pixel values. threshold Tests pixel values in an image against a specified threshold and sets pixels that pass the test to new color values.The sourceBitmapData, sourceRect destPoint or operation are null. TypeErrorTypeErrorThe operation string is not a valid operation ArgumentErrorArgumentErrorThe number of pixels that were changed. uintsourceBitmapDataflash.display:BitmapDataThe input bitmap image to use. The source image can be a different BitmapData object or it can refer to the current BitmapData instance. sourceRectflash.geom:RectangleA rectangle that defines the area of the source image to use as input. destPointflash.geom:PointThe point within the destination image (the current BitmapData instance) that corresponds to the upper-left corner of the source rectangle. operationStringOne of the following comparison operators, passed as a String: "<", "<=", ">", ">=", "==", "!=" thresholduintThe value that each pixel is tested against to see if it meets or exceeds the threshhold. coloruint0The color value that a pixel is set to if the threshold test succeeds. The default value is 0x00000000. maskuint0xFFFFFFFFThe mask to use to isolate a color component. copySourceBooleanfalseIf the value is true, pixel values from the source image are copied to the destination when the threshold test fails. If the value is false, the source image is not copied when the threshold test fails. Tests pixel values in an image against a specified threshold and sets pixels that pass the test to new color values. Using the threshold() method, you can isolate and replace color ranges in an image and perform other logical operations on image pixels.

The threshold() method's test logic is as follows:

  1. If ((pixelValue & mask) operation (threshold & mask)), then set the pixel to color;
  2. Otherwise, if copySource == true, then set the pixel to corresponding pixel value from sourceBitmap.

The operation parameter specifies the comparison operator to use for the threshold test. For example, by using "==" as the operation parameter, you can isolate a specific color value in an image. Or by using {operation: "<", mask: 0xFF000000, threshold: 0x7F000000, color: 0x00000000}, you can set all destination pixels to be fully transparent when the source image pixel's alpha is less than 0x7F. You can use this technique for animated transitions and other effects.

The following example uses the perlinNoise() method to add a blue and red pattern to one BitmapData object, and then uses the threshold() method to copy those pixels from the first BitmapData object to a second one, replacing those pixels in which the red value is greater than 0x80 (50%) with a pixel set to transparent red (0x20FF0000): import flash.display.Bitmap; import flash.display.BitmapData; import flash.display.BitmapDataChannel; import flash.geom.Point; import flash.geom.Rectangle; var bmd1:BitmapData = new BitmapData(200, 200, true, 0xFFCCCCCC); var seed:int = int(Math.random() * int.MAX_VALUE); var channels:uint = BitmapDataChannel.RED | BitmapDataChannel.BLUE; bmd1.perlinNoise(100, 80, 12, seed, false, true, channels, false, null); var bitmap1:Bitmap = new Bitmap(bmd1); addChild(bitmap1); var bmd2:BitmapData = new BitmapData(200, 200, true, 0xFFCCCCCC); var pt:Point = new Point(0, 0); var rect:Rectangle = new Rectangle(0, 0, 200, 200); var threshold:uint = 0x00800000; var color:uint = 0x20FF0000; var maskColor:uint = 0x00FF0000; bmd2.threshold(bmd1, rect, pt, ">", threshold, color, maskColor, true); var bitmap2:Bitmap = new Bitmap(bmd2); bitmap2.x = bitmap1.x + bitmap1.width + 10; addChild(bitmap2);
unlock Unlocks an image so that any objects that reference the BitmapData object, such as Bitmap objects, are updated when this BitmapData object changes.changeRectflash.geom:RectanglenullThe area of the BitmapData object that has changed. If you do not specify a value for this parameter, the entire area of the BitmapData object is considered changed. This parameter requires Flash Player version 9.0.115.0 or later. Unlocks an image so that any objects that reference the BitmapData object, such as Bitmap objects, are updated when this BitmapData object changes. To improve performance, use this method along with the lock() method before and after numerous calls to the setPixel() or setPixel32() method. The following example creates a BitmapData object based on the bitmapData property of a Bitmap object, picture. It then calls the lock() method before calling a complicated custom function, complexTransformation(), that modifies the BitmapData object. (The picture object and the complexTransformation() function are not defined in this example.) Even if the complexTransformation() function updates the bitmapData property of the picture object, changes are not reflected until the code calls the unlock() method on the bitmapData object: import flash.display.BitmapData; var bitmapData:BitmapData = picture.bitmapData; bitmapData.lock(); bitmapData = complexTransformation(bitmapData); bitmapData.unlock(); picture.bitmapData = bitmapData; lock()setPixel()setPixel32()height The height of the bitmap image in pixels.int The height of the bitmap image in pixels. rect The rectangle that defines the size and location of the bitmap image.flash.geom:Rectangle The rectangle that defines the size and location of the bitmap image. The top and left of the rectangle are 0; the width and height are equal to the width and height in pixels of the BitmapData object. transparent Defines whether the bitmap image supports per-pixel transparency.Boolean Defines whether the bitmap image supports per-pixel transparency. You can set this value only when you construct a BitmapData object by passing in true for the transparent parameter of the constructor. Then, after you create a BitmapData object, you can check whether it supports per-pixel transparency by determining if the value of the transparent property is true. width The width of the bitmap image in pixels.int The width of the bitmap image in pixels.
JointStyle The JointStyle class is an enumeration of constant values that specify the joint style to use in drawing lines.Object The JointStyle class is an enumeration of constant values that specify the joint style to use in drawing lines. These constants are provided for use as values in the joints parameter of the flash.display.Graphics.lineStyle() method. The method supports three types of joints: miter, round, and bevel, as the following example shows:

The following example uses the JointStyleExample class to show the result of three different joint styles applied to three sets of joined lines. This task is accomplished by performing the following steps:
  1. The properties of each line are set as follows:
    • The line length is set to 80 pixels.
    • The border color is set to orange.
    • The border size is set to 30 pixels.
    • The highlight color is set to gray.
    • The highlight size is set to zero pixels.
    • The alpha is set to 1, making it solid.
    • The pixel hinting is set to false (strokes not hinted to full pixels).
    • The line scale mode is set to normal, which scales the thickness.
    • The border caps and miter limit are declared but not set, so the default values are used.
  2. The class constructor creates three sets of two connected line segments. The segments start at x = 0, y = 0 by calling the doDrawCorner() method three times using the three joint styles (miter, round, and bevel). Each of the three calls to doDrawCorner() uses the joint style and properties previously listed to draw two connected line segments and associated line highlights. This is done by first creating a new Shape object child and then using methods of the Graphics class to set the line style and draw the lines and highlights. Each instance of child is added to the display list and promptly drawn on the stage.
  3. The connected line segments are then redrawn by using the refreshLayout() method at y = 80 pixels and starting at x = 80 pixels, with a 25-pixel separation between the line segments.
package { import flash.display.DisplayObject; import flash.display.Graphics; import flash.display.JointStyle; import flash.display.LineScaleMode; import flash.display.Shape; import flash.display.Sprite; public class JointStyleExample extends Sprite { private var size:uint = 80; private var borderColor:uint = 0xFFCC00; private var borderSize:uint = 30; private var highlightColor:uint = 0x666666; private var highlightSize:uint = 0; private var gutter:uint = 25; private var borderAlpha:uint = 1; private var borderPixelHinting:Boolean = false; private var borderScaleMode:String = LineScaleMode.NORMAL; private var borderCaps:String; private var borderMiterLimit:uint; public function JointStyleExample() { doDrawCorner(JointStyle.MITER); doDrawCorner(JointStyle.ROUND); doDrawCorner(JointStyle.BEVEL); refreshLayout(); } private function doDrawCorner(jointStyle:String):void { var halfSize:uint = Math.round(size / 2); var child:Shape = new Shape(); child.graphics.lineStyle(borderSize, borderColor, borderAlpha, borderPixelHinting, borderScaleMode, borderCaps, jointStyle, borderMiterLimit); child.graphics.lineTo(0, 0); child.graphics.lineTo(size, 0); child.graphics.lineTo(halfSize, size); child.graphics.endFill(); child.graphics.moveTo(0, 0); child.graphics.lineStyle(highlightSize, highlightColor); child.graphics.lineTo(0, 0); child.graphics.lineTo(size, 0); child.graphics.lineTo(halfSize, size); addChild(child); } private function refreshLayout():void { var ln:uint = numChildren; var child:DisplayObject; var lastChild:DisplayObject = getChildAt(0); lastChild.x = size; lastChild.y = size; for (var i:uint = 1; i < ln; i++) { child = getChildAt(i); child.x = gutter + lastChild.x + lastChild.width; child.y = size; lastChild = child; } } } }
flash.display.Graphics.lineStyle()BEVEL Specifies beveled joints in the joints parameter of the flash.display.Graphics.lineStyle() method.bevelString Specifies beveled joints in the joints parameter of the flash.display.Graphics.lineStyle() method. MITER Specifies mitered joints in the joints parameter of the flash.display.Graphics.lineStyle() method.miterString Specifies mitered joints in the joints parameter of the flash.display.Graphics.lineStyle() method. ROUND Specifies round joints in the joints parameter of the flash.display.Graphics.lineStyle() method.roundString Specifies round joints in the joints parameter of the flash.display.Graphics.lineStyle() method.
AVM1Movie AVM1Movie is a simple class that represents AVM1 movie clips, which use ActionScript 1.0 or 2.0.flash.display:DisplayObject AVM1Movie is a simple class that represents AVM1 movie clips, which use ActionScript 1.0 or 2.0. (AVM1 is the ActionScript virtual machine used to run ActionScript 1.0 and 2.0. AVM2 is the ActionScript virtual machine used to run ActionScript 3.0.) When a Flash Player 8, or older, SWF file is loaded by a Loader object, an AVM1Movie object is created. The AVM1Movie object can use methods and properties inherited from the DisplayObject class (such as x, y, width, and so on). However, no interoperability (such as calling methods or using parameters) between the AVM1Movie object and AVM2 objects is allowed.

There are several restrictions on an AVM1 SWF file loaded by an AVM2 SWF file:

  • The loaded AVM1Movie object operates as a psuedo-root object for the AVM1 SWF file and all AVM1 SWF files loaded by it (as if the ActionScript 1.0 lockroot property were set to true). The AVM1 movie is always the top of any ActionScript 1.0 or 2.0 code execution in any children. The _root property for loaded children is always this AVM1 SWF file, unless the lockroot property is set in a loaded AVM1 SWF file.
  • The AVM1 content cannot load files into levels. For example, it cannot load files by calling loadMovieNum("url", levelNum).
  • The AVM1 SWF file that is loaded by an AVM2 SWF file cannot load another SWF file into this. That is, it cannot load another SWF file over itself. However, child Sprite objects, MovieClip objects, or other AVM1 SWF files loaded by this SWF file can load into this.
DisplayObjectLoader
ShaderInput A ShaderInput instance represents a single input image for a shader kernel.Object A ShaderInput instance represents a single input image for a shader kernel. A kernel can be defined to accept zero, one, or more source images that are used in the kernel execution. A ShaderInput instance provides a mechanism for specifying the input image that is used when the shader executes. To specify a value for the input, create a BitmapData, ByteArray, or Vector.<Number> instance containing the image data and assign it to the input property.

The ShaderInput instance representing a Shader instance's input image is accessed as a property of the Shader instance's data property. The ShaderInput property has the same name as the input's name in the shader code. For example, if a shader defines an input named src, the ShaderInput instance representing the src input is available as the src property, as this example shows:

myShader.data.src.image = new BitmapData(50, 50, true, 0xFF990000);

For some uses of a Shader instance, you do not need to specify an input image, because it is automatically specified by the operation. You only need to specify an input when a Shader is used for the following:

  • Shader fill
  • ShaderFilter, only for the second or additional inputs if the shader is defined to use more than one input. (The object to which the filter is applied is automatically used as the first input.)
  • Shader blend mode, only for the third or additional inputs if the shader is defined to use more than two inputs. (The objects being blended are automatically used as the first and second inputs.)
  • ShaderJob background execution

If the shader is being executed using a ShaderJob instance to process a ByteArray containing a linear array of data, set the ShaderInput instance's height to 1 and width to the number of 32-bit floating point values in the ByteArray. In that case, the input in the shader must be defined with the image1 data type.

Generally, developer code does not create a ShaderInput instance directly. A ShaderInput instance is created for each of a shader's inputs when the Shader instance is created.

flash.display.ShaderDataflash.display.Shader.dataflash.display.ShaderJobShaderInput Creates a ShaderInput instance. Creates a ShaderInput instance. Developer code does not call the ShaderInput constructor directly. A ShaderInput instance is created for each of a shader's inputs when the Shader instance is created. channels The number of channels that a shader input expects.int The number of channels that a shader input expects. This property must be accounted for when the input data is a ByteArray or Vector.<Number> instance. height The height of the shader input.int The height of the shader input. This property is only used when the input data is a ByteArray or Vector.<Number> instance. When the input is a BitmapData instance the height is automatically determined. index The zero-based index of the input in the shader, indicating the order of the input definitions in the shader.int The zero-based index of the input in the shader, indicating the order of the input definitions in the shader. input The input data that is used when the shader executes.Object The input data that is used when the shader executes. This property can be a BitmapData instance, a ByteArray instance, or a Vector.<Number> instance.

If a ByteArray value is assigned to the input property, the following conditions must be met:

  • The height and width properties must be set.
  • The byte array's contents must only consist of 32-bit floating-point values. These values can be written using the ByteArray.writeFloat() method.
  • The total length in bytes of the ByteArray must be exactly width times height times channels times 4.
  • The byte array's endian property must be Endian.LITTLE_ENDIAN.

If a Vector.<Number> instance is assigned to the input property, the length of the Vector must be equal to width times height times channels.

width The width of the shader input.int The width of the shader input. This property is only used when the input data is a ByteArray or Vector.<Number> instance. When the input is a BitmapData instance the width is automatically determined.
ColorCorrection The ColorCorrection class provides values for the flash.display.Stage.colorCorrection property.Object The ColorCorrection class provides values for the flash.display.Stage.colorCorrection property. flash.display.Stage.colorCorrectionDEFAULT Uses the host's default color correction.defaultString Uses the host's default color correction. For the web player the host is usually a browser, and Flash Player tries to use the same color correction as the web page hosting the SWF file. OFF Turns off color correction regardless of the player host environment.offString Turns off color correction regardless of the player host environment. This setting provides faster performance. ON Turns on color correction regardless of the player host environment, if available.onString Turns on color correction regardless of the player host environment, if available. Shader A Shader instance represents a Pixel Bender shader kernel in ActionScript.Object A Shader instance represents a Pixel Bender shader kernel in ActionScript. To use a shader in your application, you create a Shader instance for it. You then use that Shader instance in the appropriate way according to the effect you want to create. For example, to use the shader as a filter, you assign the Shader instance to the shader property of a ShaderFilter object.

A shader defines a function that executes on all the pixels in an image, one pixel at a time. The result of each call to the function is the output color at that pixel coordinate in the image. A shader can specify one or more input images, which are images whose content can be used in determining the output of the function. A shader can also specify one or more parameters, which are input values that can be used in calculating the function output. In a single shader execution, the input and parameter values are constant. The only thing that varies is the coordinate of the pixel whose color is the function result. Shader function calls for multiple output pixel coordinates execute in parallel to improve shader execution performance.

The shader bytecode can be loaded at run time using a URLLoader instance. The following example demonstrates loading a shader bytecode file at run time and linking it to a Shader instance.

var loader:URLLoader = new URLLoader(); loader.dataFormat = URLLoaderDataFormat.BINARY; loader.addEventListener(Event.COMPLETE, onLoadComplete); loader.load(new URLRequest("myShader.pbj")); var shader:Shader; function onLoadComplete(event:Event):void { // Create a new shader and set the loaded data as its bytecode shader = new Shader(); shader.byteCode = loader.data; // You can also pass the bytecode to the Shader() constructor like this: // shader = new Shader(loader.data); // do something with the shader }

You can also embed the shader into the SWF at compile time using the [Embed] metadata tag. The [Embed] metadata tag is only available if you use the Flex SDK to compile the SWF. The [Embed] tag's source parameter points to the shader file, and its mimeType parameter is "application/octet-stream", as in this example:

[Embed(source="myShader.pbj", mimeType="application/octet-stream)] var MyShaderClass:Class; // ... // create a new shader and set the embedded shader as its bytecode var shaderShader = new Shader(); shader.byteCode = new MyShaderClass(); // You can also pass the bytecode to the Shader() constructor like this: // var shader:Shader = new Shader(new MyShaderClass()); // do something with the shader

In either case, you link the raw shader (the URLLoader.data property or an instance of the [Embed] data class) to the Shader instance. As the previous examples demonstrate, you can do this in two ways. You can pass the shader bytecode as an argument to the Shader() constructor. Alternatively, you can set it as the Shader instance's byteCode property.

Once a Shader instance is created, it can be used in one of several ways:

  • A shader fill: The output of the shader is used as a fill for content drawn with the drawing API. Pass the Shader instance as an argument to the Graphics.beginShaderFill() method.
  • A shader filter: The output of the shader is used as a graphic filter applied to a display object. Assign the Shader instance to the shader property of a ShaderFilter instance.
  • A blend mode: The output of the shader is rendered as the blending between two overlapping display objects. Assign the Shader instance to the blendShader property of the upper of the two display objects.
  • Background shader processing: The shader executes in the background, avoiding the possibility of freezing the display, and dispatches an event when processing is complete. Assign the Shader instance to the shader property of a ShaderJob instance.

Shader fills, filters, and blends are not supported under GPU rendering.

Mobile Browser Support: This feature is not supported in mobile browsers.

AIR profile support: This feature is supported on all desktop operating systems, but it is not supported on all mobile devices. It is not supported on AIR for TV devices. See AIR Profile Support for more information regarding API support across multiple profiles.

The following example loads a shader bytecode file at run time and creates a Shader instance linked to it.

Note that this example assumes there's a shader bytecode file named "donothing.pbj" in the same directory as the output directory for the application. The Pixel Bender source code for the DoNothing shader is available in the ShaderData class example.

package { import flash.display.Shader; import flash.display.Sprite; import flash.events.Event; import flash.net.URLLoader; import flash.net.URLLoaderDataFormat; import flash.net.URLRequest; public class LoadedShaderExample extends Sprite { private var loader:URLLoader; public function LoadedShaderExample() { loader = new URLLoader(); loader.dataFormat = URLLoaderDataFormat.BINARY; loader.addEventListener(Event.COMPLETE, loadCompleteHandler); loader.load(new URLRequest("donothing.pbj")); } private function loadCompleteHandler(event:Event):void { var shader:Shader = new Shader(); shader.byteCode = loader.data; // do something with the Shader instance } } }
The following example embeds a shader bytecode file by compiling it into the SWF, and creates a Shader instance linked to it.

Note that this example assumes there's a shader bytecode file named "donothing.pbj" in the same directory as the source code for the application, and that the Flex SDK is used to compile the SWF. The Pixel Bender source code for the DoNothing shader is available in the ShaderData class example.

package { import flash.display.Shader; import flash.display.Sprite; public class EmbeddedShaderExample extends Sprite { [Embed(source="donothing.pbj", mimeType="application/octet-stream")] private static var DoNothingShader:Class; public function EmbeddedShaderExample() { var shader:Shader = new Shader(); shader.byteCode = new DoNothingShader(); // do something with the Shader instance } } }
flash.display.DisplayObject.blendShaderflash.display.Graphics.beginShaderFill()flash.display.ShaderJobflash.filters.ShaderFilterflash.net.URLLoaderShader Creates a new Shader instance.codeflash.utils:ByteArraynullThe raw shader bytecode to link to the Shader. Creates a new Shader instance. data Provides access to parameters, input images, and metadata for the Shader instance.flash.display:ShaderData Provides access to parameters, input images, and metadata for the Shader instance. ShaderParameter objects representing parameters for the shader, ShaderInput objects representing the input images for the shader, and other values representing the shader's metadata are dynamically added as properties of the data property object when the Shader instance is created. Those properties can be used to introspect the shader and to set parameter and input values.

For information about accessing and manipulating the dynamic properties of the data object, see the ShaderData class description.

flash.display.ShaderDataflash.display.ShaderInputflash.display.ShaderParameter
precisionHint The precision of math operations performed by the shader.String The precision of math operations performed by the shader.

The set of possible values for the precisionHint property is defined by the constants in the ShaderPrecision class.

The default value is ShaderPrecision.FULL. Setting the precision to ShaderPrecision.FAST can speed up math operations at the expense of precision.

Full precision mode (ShaderPrecision.FULL) computes all math operations to the full width of the IEEE 32-bit floating standard and provides consistent behavior on all platforms. In this mode, some math operations such as trigonometric and exponential functions can be slow.

Fast precision mode (ShaderPrecision.FAST) is designed for maximum performance but does not work consistently on different platforms and individual CPU configurations. In many cases, this level of precision is sufficient to create graphic effects without visible artifacts.

The precision mode selection affects the following shader operations. These operations are faster on an Intel processor with the SSE instruction set:

  • sin(x)
  • cos(x)
  • tan(x)
  • asin(x)
  • acos(x)
  • atan(x)
  • atan(x, y)
  • exp(x)
  • exp2(x)
  • log(x)
  • log2(x)
  • pow(x, y)
  • reciprocal(x)
  • sqrt(x)
flash.display.ShaderPrecision
byteCode The raw shader bytecode for this Shader instance.flash.utils:ByteArray The raw shader bytecode for this Shader instance.
LineScaleMode The LineScaleMode class provides values for the scaleMode parameter in the Graphics.lineStyle() method.Object The LineScaleMode class provides values for the scaleMode parameter in the Graphics.lineStyle() method. flash.display.Graphics.lineStyle()HORIZONTAL With this setting used as the scaleMode parameter of the lineStyle() method, the thickness of the line scales only vertically.horizontalString With this setting used as the scaleMode parameter of the lineStyle() method, the thickness of the line scales only vertically. For example, consider the following circles, drawn with a one-pixel line, and each with the scaleMode parameter set to LineScaleMode.VERTICAL. The circle on the left is scaled only vertically, and the circle on the right is scaled both vertically and horizontally.

NONE With this setting used as the scaleMode parameter of the lineStyle() method, the thickness of the line never scales.noneString With this setting used as the scaleMode parameter of the lineStyle() method, the thickness of the line never scales. NORMAL With this setting used as the scaleMode parameter of the lineStyle() method, the thickness of the line always scales when the object is scaled (the default).normalString With this setting used as the scaleMode parameter of the lineStyle() method, the thickness of the line always scales when the object is scaled (the default). VERTICAL With this setting used as the scaleMode parameter of the lineStyle() method, the thickness of the line scales only horizontally.verticalString With this setting used as the scaleMode parameter of the lineStyle() method, the thickness of the line scales only horizontally. For example, consider the following circles, drawn with a one-pixel line, and each with the scaleMode parameter set to LineScaleMode.HORIZONTAL. The circle on the left is scaled only horizontally, and the circle on the right is scaled both vertically and horizontally.

IGraphicsData This interface is used to define objects that can be used as parameters in the flash.display.Graphics methods, including fills, strokes, and paths. This interface is used to define objects that can be used as parameters in the flash.display.Graphics methods, including fills, strokes, and paths. Use the implementor classes of this interface to create and manage drawing property data, and to reuse the same data for different instances. Then, use the methods of the Graphics class to render the drawing objects. flash.display.Graphics.drawGraphicsData()MovieClip The MovieClip class inherits from the following classes: Sprite, DisplayObjectContainer, InteractiveObject, DisplayObject, and EventDispatcher.The basic display object for ActionScript created objects. flash.display:Sprite The MovieClip class inherits from the following classes: Sprite, DisplayObjectContainer, InteractiveObject, DisplayObject, and EventDispatcher.

Unlike the Sprite object, a MovieClip object has a timeline.

>In Flash Professional, the methods for the MovieClip class provide the same functionality as actions that target movie clips. Some additional methods do not have equivalent actions in the Actions toolbox in the Actions panel in the Flash authoring tool.

Children instances placed on the Stage in Flash Professional cannot be accessed by code from within the constructor of a parent instance since they have not been created at that point in code execution. Before accessing the child, the parent must instead either create the child instance by code or delay access to a callback function that listens for the child to dispatch its Event.ADDED_TO_STAGE event.

If you modify any of the following properties of a MovieClip object that contains a motion tween, the playhead is stopped in that MovieClip object: alpha, blendMode, filters, height, opaqueBackground, rotation, scaleX, scaleY, scale9Grid, scrollRect, transform, visible, width, x, or y. However, it does not stop the playhead in any child MovieClip objects of that MovieClip object.

Note:Flash Lite 4 supports the MovieClip.opaqueBackground property only if FEATURE_BITMAPCACHE is defined. The default configuration of Flash Lite 4 does not define FEATURE_BITMAPCACHE. To enable the MovieClip.opaqueBackground property for a suitable device, define FEATURE_BITMAPCACHE in your project.

The following example uses the MovieClipExample class to illustrate how to monitor various properties of a MovieClip. This task is accomplished by performing the following steps:
  1. The constructor function defines a text field, which is used to display values of properties of the MovieClipExample object (which extends MovieClip).
  2. The return value of the getPropertiesString() method is used as text for the outputText text field. The getPropertiesString() method returns a string that is populated with values of the following properties of the movie clip: currentFrame, currentLabel, currentScene, framesLoaded, totalFrames, and trackAsMenu.
  3. Two lines of code in the constructor function adjust the width and height properties of the outputText text field.
  4. The last line of the constructor function adds the outputText text field to the display list.
package { import flash.display.MovieClip; import flash.text.TextField; public class MovieClipExample extends MovieClip { public function MovieClipExample() { var outputText:TextField = new TextField(); outputText.text = getPropertiesString(); outputText.width = stage.stageWidth; outputText.height = outputText.textHeight; addChild(outputText); } private function getPropertiesString():String { var str:String = "" + "currentFrame: " + currentFrame + "\n" + "currentLabel: " + currentLabel + "\n" + "currentScene: " + currentScene + "\n" + "framesLoaded: " + framesLoaded + "\n" + "totalFrames: " + totalFrames + "\n" + "trackAsMenu: " + trackAsMenu + "\n"; return str; } } }
MovieClip Creates a new MovieClip instance. Creates a new MovieClip instance. After creating the MovieClip, call the addChild() or addChildAt() method of a display object container that is onstage. gotoAndPlay Starts playing the SWF file at the specified frame.frameObjectA number representing the frame number, or a string representing the label of the frame, to which the playhead is sent. If you specify a number, it is relative to the scene you specify. If you do not specify a scene, the current scene determines the global frame number to play. If you do specify a scene, the playhead jumps to the frame number in the specified scene. sceneStringnullThe name of the scene to play. This parameter is optional. Starts playing the SWF file at the specified frame. This happens after all remaining actions in the frame have finished executing. To specify a scene as well as a frame, specify a value for the scene parameter. The following code uses the gotoAndPlay() method to direct the playhead of the mc1 movie clip to advance five frames ahead of its current location: mc1.gotoAndPlay(mc1.currentFrame + 5); The following code uses the gotoAndPlay() method to direct the playhead of the mc1 movie clip to the frame labeled "intro" in the scene named "Scene 12": mc1.gotoAndPlay("intro", "Scene 12"); gotoAndStop Brings the playhead to the specified frame of the movie clip and stops it there.If the scene or frame specified are not found in this movie clip. ArgumentErrorArgumentErrorframeObjectA number representing the frame number, or a string representing the label of the frame, to which the playhead is sent. If you specify a number, it is relative to the scene you specify. If you do not specify a scene, the current scene determines the global frame number at which to go to and stop. If you do specify a scene, the playhead goes to the frame number in the specified scene and stops. sceneStringnullThe name of the scene. This parameter is optional. Brings the playhead to the specified frame of the movie clip and stops it there. This happens after all remaining actions in the frame have finished executing. If you want to specify a scene in addition to a frame, specify a scene parameter. The following code uses the gotoAndStop() method and the currentFrame property to direct the playhead of the mc1 movie clip to advance five frames ahead of its current location and stop: mc1.gotoAndStop(mc1.currentFrame + 5); The following code uses the gotoAndStop() to direct the playhead of the mc1 movie clip to the frame labeled "finale" in the scene named "Scene 12" and stop the playhead: mc1.gotoAndStop("finale", "Scene 12"); nextFrame Sends the playhead to the next frame and stops it. Sends the playhead to the next frame and stops it. This happens after all remaining actions in the frame have finished executing. In the following example, two SimpleButton objects control the timeline. The prev button moves the playhead to the previous frame, and the nextBtn button moves the playhead to the next frame: import flash.events.MouseEvent; mc1.stop(); prevBtn.addEventListener(MouseEvent.CLICK, goBack); nextBtn.addEventListener(MouseEvent.CLICK, goForward); function goBack(event:MouseEvent):void { mc1.prevFrame(); } function goForward(event:MouseEvent):void { mc1.nextFrame(); } prevFrame()nextScene Moves the playhead to the next scene of the MovieClip instance. Moves the playhead to the next scene of the MovieClip instance. This happens after all remaining actions in the frame have finished executing. In the following example, two SimpleButton objects control the timeline. The prevBtn button moves the playhead to the previous scene, and the nextBtn button moves the playhead to the next scene: import flash.events.MouseEvent; mc1.stop(); prevBtn.addEventListener(MouseEvent.CLICK, goBack); nextBtn.addEventListener(MouseEvent.CLICK, goForward); function goBack(event:MouseEvent):void { mc1.prevScene(); } function goForward(event:MouseEvent):void { mc1.nextScene(); } play Moves the playhead in the timeline of the movie clip. Moves the playhead in the timeline of the movie clip. The following code uses the stop() method to stop a movie clip named mc1 and to resume playing when the user clicks the text field named continueText: import flash.text.TextField; import flash.events.MouseEvent; var continueText:TextField = new TextField(); continueText.text = "Play movie..."; addChild(continueText); mc1.stop(); continueText.addEventListener(MouseEvent.CLICK, resumeMovie); function resumeMovie(event:MouseEvent):void { mc1.play(); } gotoAndPlay()prevFrame Sends the playhead to the previous frame and stops it. Sends the playhead to the previous frame and stops it. This happens after all remaining actions in the frame have finished executing. In the following example, two SimpleButton objects control the timeline. The prev button moves the playhead to the previous frame, and the nextBtn button moves the playhead to the next frame: import flash.events.MouseEvent; mc1.stop(); prevBtn.addEventListener(MouseEvent.CLICK, goBack); nextBtn.addEventListener(MouseEvent.CLICK, goForward); function goBack(event:MouseEvent):void { mc1.prevFrame(); } function goForward(event:MouseEvent):void { mc1.nextFrame(); } prevScene Moves the playhead to the previous scene of the MovieClip instance. Moves the playhead to the previous scene of the MovieClip instance. This happens after all remaining actions in the frame have finished executing. In the following example, two SimpleButton objects control the timeline. The prevBtn button moves the playhead to the previous scene, and the nextBtn button moves the playhead to the next scene: import flash.events.MouseEvent; mc1.stop(); prevBtn.addEventListener(MouseEvent.CLICK, goBack); nextBtn.addEventListener(MouseEvent.CLICK, goForward); function goBack(event:MouseEvent):void { mc1.prevScene(); } function goForward(event:MouseEvent):void { mc1.nextScene(); } stop Stops the playhead in the movie clip. Stops the playhead in the movie clip. currentFrameLabel The label at the current frame in the timeline of the MovieClip instance.String The label at the current frame in the timeline of the MovieClip instance. If the current frame has no label, currentLabel is null. currentFrame Specifies the number of the frame in which the playhead is located in the timeline of the MovieClip instance.int Specifies the number of the frame in which the playhead is located in the timeline of the MovieClip instance. If the movie clip has multiple scenes, this value is the frame number in the current scene. The following code uses the gotoAndStop() method and the currentFrame property to direct the playhead of the mc1 movie clip to advance five frames ahead of its current location and stop: mc1.gotoAndStop(mc1.currentFrame + 5); currentLabel The current label in which the playhead is located in the timeline of the MovieClip instance.String The current label in which the playhead is located in the timeline of the MovieClip instance. If the current frame has no label, currentLabel is set to the name of the previous frame that includes a label. If the current frame and previous frames do not include a label, currentLabel returns null. The following code illustrates how to access the currentLabel property of a MovieClip object named mc1: trace(mc1.currentLabel); currentLabels Returns an array of FrameLabel objects from the current scene.Array Returns an array of FrameLabel objects from the current scene. If the MovieClip instance does not use scenes, the array includes all frame labels from the entire MovieClip instance. The following code illustrates how to use the currentLabels property of a MovieClip object named mc1: import flash.display.FrameLabel; var labels:Array = mc1.currentLabels; for (var i:uint = 0; i < labels.length; i++) { var label:FrameLabel = labels[i]; trace("frame " + label.frame + ": " + label.name); } flash.display.FrameLabelcurrentScene The current scene in which the playhead is located in the timeline of the MovieClip instance.flash.display:Scene The current scene in which the playhead is located in the timeline of the MovieClip instance. The following code illustrates how to use the currentScene property of a MovieClip object named mc1: import flash.display.Scene; var scene:Scene = mc1.currentScene; trace(scene.name + ": " + scene.numFrames + " frames"); Sceneenabled A Boolean value that indicates whether a movie clip is enabled.Boolean A Boolean value that indicates whether a movie clip is enabled. The default value of enabled is true. If enabled is set to false, the movie clip's Over, Down, and Up frames are disabled. The movie clip continues to receive events (for example, mouseDown, mouseUp, keyDown, and keyUp).

The enabled property governs only the button-like properties of a movie clip. You can change the enabled property at any time; the modified movie clip is immediately enabled or disabled. If enabled is set to false, the object is not included in automatic tab ordering.

The following code illustrates how to use the enabled property to disable the button-like properties of a MovieClip object named mc1: mc1.enabled = false;
framesLoaded The number of frames that are loaded from a streaming SWF file.int The number of frames that are loaded from a streaming SWF file. You can use the framesLoaded property to determine whether the contents of a specific frame and all the frames before it loaded and are available locally in the browser. You can also use it to monitor the downloading of large SWF files. For example, you might want to display a message to users indicating that the SWF file is loading until a specified frame in the SWF file finishes loading.

If the movie clip contains multiple scenes, the framesLoaded property returns the number of frames loaded for all scenes in the movie clip.

The following code illustrates how to use the framesLoaded property and the totalFrames property to determine if a streaming MovieClip object named mc1 is fully loaded: if (mc1.framesLoaded == mc1.totalFrames) { trace("OK."); }
Loader class
scenes An array of Scene objects, each listing the name, the number of frames, and the frame labels for a scene in the MovieClip instance.Array An array of Scene objects, each listing the name, the number of frames, and the frame labels for a scene in the MovieClip instance. The following code illustrates how to use the scenes property of a MovieClip object named mc1: import flash.display.Scene; for (var i:uint = 0; i < mc1.scenes.length; i++) { var scene:Scene = mc1.scenes[i]; trace("scene " + scene.name + ": " + scene.numFrames + " frames"); } ScenetotalFrames The total number of frames in the MovieClip instance.int The total number of frames in the MovieClip instance.

If the movie clip contains multiple frames, the totalFrames property returns the total number of frames in all scenes in the movie clip.

The following code illustrates the use of the totalFrames property of a MovieClip object named mc1: trace(mc1.totalFrames);
trackAsMenu Indicates whether other display objects that are SimpleButton or MovieClip objects can receive mouse release events or other user input release events.Boolean Indicates whether other display objects that are SimpleButton or MovieClip objects can receive mouse release events or other user input release events. The trackAsMenu property lets you create menus. You can set the trackAsMenu property on any SimpleButton or MovieClip object. The default value of the trackAsMenu property is false.

You can change the trackAsMenu property at any time; the modified movie clip immediately uses the new behavior.

The following code illustrates how to use the trackAsMenu property to enable mouse release events for a MovieClip object named mc1: mc1.trackAsMenu = true;
SWFVersion The SWFVersion class is an enumeration of constant values that indicate the file format version of a loaded SWF file.Object The SWFVersion class is an enumeration of constant values that indicate the file format version of a loaded SWF file. The SWFVersion constants are provided for use in checking the swfVersion property of a flash.display.LoaderInfo object. flash.display.LoaderInfo.swfVersionFLASH10 SWF file format version 10.0.10uint SWF file format version 10.0. FLASH11 SWF file format version 11.0.11uint SWF file format version 11.0. FLASH1 SWF file format version 1.0.1uint SWF file format version 1.0. FLASH2 SWF file format version 2.0.2uint SWF file format version 2.0. FLASH3 SWF file format version 3.0.3uint SWF file format version 3.0. FLASH4 SWF file format version 4.0.4uint SWF file format version 4.0. FLASH5 SWF file format version 5.0.5uint SWF file format version 5.0. FLASH6 SWF file format version 6.0.6uint SWF file format version 6.0. FLASH7 SWF file format version 7.0.7uint SWF file format version 7.0. FLASH8 SWF file format version 8.0.8uint SWF file format version 8.0. FLASH9 SWF file format version 9.0.9uint SWF file format version 9.0. NativeWindowResize The NativeWindowResize class defines constants for the possible values of the edgeOrCorner parameter of the NativeWindow startResize() method.Defines constants used when resizing a window in response to a user action. Object The NativeWindowResize class defines constants for the possible values of the edgeOrCorner parameter of the NativeWindow startResize() method.

A constant is defined to name each edge and corner of a window.

flash.display.NativeWindow.startResize()BOTTOM_LEFT The bottom-left corner of the window.BLString The bottom-left corner of the window. BOTTOM_RIGHT The bottom-right corner of the window.BRString The bottom-right corner of the window. BOTTOM The bottom edge of the window.BString The bottom edge of the window. LEFT The left edge of the window.LString The left edge of the window. NONE Used for keyboard resizing on systems (such as Windows) that support keyboard resizing.String Used for keyboard resizing on systems (such as Windows) that support keyboard resizing. On Windows, this is similar to choosing the Size command from the Alt+Space menu. When calling NativeWindow.startResize(NativeWindowResize.NONE), a Windows user can resize the window using the keyboard arrow keys. RIGHT The right edge of the window.RString The right edge of the window. TOP_LEFT The top-left corner of the window.TLString The top-left corner of the window. TOP_RIGHT The top-right corner of the window.TRString The top-right corner of the window. TOP The top edge of the window.TString The top edge of the window.
BitmapDataChannel The BitmapDataChannel class is an enumeration of constant values that indicate which channel to use: red, blue, green, or alpha transparency.Object The BitmapDataChannel class is an enumeration of constant values that indicate which channel to use: red, blue, green, or alpha transparency.

When you call some methods, you can use the bitwise OR operator (|) to combine BitmapDataChannel constants to indicate multiple color channels.

The BitmapDataChannel constants are provided for use as values in the following:

  • The sourceChannel and destChannel parameters of the flash.display.BitmapData.copyChannel() method
  • The channelOptions parameter of the flash.display.BitmapData.noise() method
  • The flash.filters.DisplacementMapFilter.componentX and flash.filters.DisplacementMapFilter.componentY properties
flash.display.BitmapData.copyChannel()flash.display.BitmapData.noise()flash.filters.DisplacementMapFilter.componentXflash.filters.DisplacementMapFilter.componentYALPHA The alpha channel.8uint The alpha channel. BLUE The blue channel.4uint The blue channel. GREEN The green channel.2uint The green channel. RED The red channel.1uint The red channel.
GraphicsSolidFill Defines a solid fill.flash.display:IGraphicsFillflash.display:IGraphicsDataObject Defines a solid fill.

Use a GraphicsSolidFill object with the Graphics.drawGraphicsData() method. Drawing a GraphicsSolidFill object is the equivalent of calling the Graphics.beginFill() method.

flash.display.Graphics.beginFill()flash.display.Graphics.drawGraphicsData()GraphicsSolidFill Creates a new GraphicsSolidFill object.coloruint0The color value. Valid values are in the hexadecimal format 0xRRGGBB. alphaNumber1.0The alpha transparency value. Valid values are 0 (fully transparent) to 1 (fully opaque). Creates a new GraphicsSolidFill object. alpha Indicates the alpha transparency value of the fill.1.0Number Indicates the alpha transparency value of the fill. Valid values are 0 (fully transparent) to 1 (fully opaque). The default value is 1. Display objects with alpha set to 0 are active, even though they are invisible. color The color of the fill.0uint The color of the fill. Valid values are in the hexadecimal format 0xRRGGBB. The default value is 0xFF0000 (or the uint 0).
IBitmapDrawable The IBitmapDrawable interface is implemented by objects that can be passed as the source parameter of the draw() method of the BitmapData class. The IBitmapDrawable interface is implemented by objects that can be passed as the source parameter of the draw() method of the BitmapData class. These objects are of type BitmapData or DisplayObject. flash.display.BitmapData.draw()flash.display.BitmapDataflash.display.DisplayObjectCapsStyle The CapsStyle class is an enumeration of constant values that specify the caps style to use in drawing lines.Object The CapsStyle class is an enumeration of constant values that specify the caps style to use in drawing lines. The constants are provided for use as values in the caps parameter of the flash.display.Graphics.lineStyle() method. You can specify the following three types of caps:

The following example uses the CapsStyleExample class to draw three parallel lines, each with a different line cap style.
  1. The properties of each line are set as follows:
    • The line length is set to 80 pixels.
    • The border color is set to orange.
    • The border size is set to 30 pixels.
    • The highlight color is set to gray.
    • The highlight size is set to 0 pixels.
    • The alpha is set to 1, making it solid.
    • The pixel hinting is set to false (strokes not hinted to full pixels).
    • The line scale mode is set to normal, which scales the thickness.
    • The joint style of the border caps are set to MITER.
    • The miter limit is set to 1, indicating that the miter is cut off close to the line.
  2. The class constructor creates three vertical lines, starting at x = 0, y = 0 by calling the drawLine() method three times using the three different line cap styles (none, round, and square). Each of the three calls to the drawLine() method uses the cap style and properties listed previously to draw a vertical line and associated line highlight. The calls first create a new child Shape object and then use methods of the Graphics class to set the line style and draw the lines and highlights. Each instance of child is added to the display list and drawn on the stage.
  3. The connected line segments are redrawn by using the refreshLayout() method at y = 80 pixels and starting at x = 80 pixels, with a 25-pixel separation between the line segments.
package { import flash.display.CapsStyle; import flash.display.DisplayObject; import flash.display.Graphics; import flash.display.JointStyle; import flash.display.LineScaleMode; import flash.display.Shape; import flash.display.Sprite; public class CapsStyleExample extends Sprite { private var lineLength:uint = 80; private var borderColor:uint = 0xFFCC00; private var borderSize:uint = 30; private var highlightColor:uint = 0x666666; private var highlightSize:uint = 0; private var gutter:uint = 25; private var borderAlpha:uint = 1; private var borderPixelHinting:Boolean = false; private var borderScaleMode:String = LineScaleMode.NORMAL; private var borderJointStyle:String = JointStyle.MITER; private var borderMiterLimit:uint = 1; public function CapsStyleExample() { drawLine(CapsStyle.NONE); drawLine(CapsStyle.ROUND); drawLine(CapsStyle.SQUARE); refreshLayout(); } private function drawLine(capsStyle:String):void { var child:Shape = new Shape(); child.graphics.lineStyle(borderSize, borderColor, borderAlpha, borderPixelHinting, borderScaleMode, capsStyle, borderJointStyle, borderMiterLimit); child.graphics.lineTo(0, 0); child.graphics.lineTo(0, lineLength); child.graphics.endFill(); child.graphics.moveTo(0, 0); child.graphics.lineStyle(highlightSize, highlightColor); child.graphics.lineTo(0, 0); child.graphics.lineTo(0, lineLength); addChild(child); } private function refreshLayout():void { var ln:uint = numChildren; var child:DisplayObject; var lastChild:DisplayObject = getChildAt(0); lastChild.x = lineLength; lastChild.y = lineLength; for (var i:uint = 1; i < ln; i++) { child = getChildAt(i); child.x = gutter + lastChild.x + lastChild.width; child.y = lineLength; lastChild = child; } } } }
flash.display.Graphics.lineStyle()NONE Used to specify no caps in the caps parameter of the flash.display.Graphics.lineStyle() method.noneString Used to specify no caps in the caps parameter of the flash.display.Graphics.lineStyle() method. ROUND Used to specify round caps in the caps parameter of the flash.display.Graphics.lineStyle() method.roundString Used to specify round caps in the caps parameter of the flash.display.Graphics.lineStyle() method. SQUARE Used to specify square caps in the caps parameter of the flash.display.Graphics.lineStyle() method.squareString Used to specify square caps in the caps parameter of the flash.display.Graphics.lineStyle() method.
StageScaleMode The StageScaleMode class provides values for the Stage.scaleMode property.Object The StageScaleMode class provides values for the Stage.scaleMode property. flash.display.Stage.scaleModeEXACT_FIT Specifies that the entire application be visible in the specified area without trying to preserve the original aspect ratio.exactFitString Specifies that the entire application be visible in the specified area without trying to preserve the original aspect ratio. Distortion can occur. NO_BORDER Specifies that the entire application fill the specified area, without distortion but possibly with some cropping, while maintaining the original aspect ratio of the application.noBorderString Specifies that the entire application fill the specified area, without distortion but possibly with some cropping, while maintaining the original aspect ratio of the application. NO_SCALE Specifies that the size of the application be fixed, so that it remains unchanged even as the size of the player window changes.noScaleString Specifies that the size of the application be fixed, so that it remains unchanged even as the size of the player window changes. Cropping might occur if the player window is smaller than the content. SHOW_ALL Specifies that the entire application be visible in the specified area without distortion while maintaining the original aspect ratio of the application.showAllString Specifies that the entire application be visible in the specified area without distortion while maintaining the original aspect ratio of the application. Borders can appear on two sides of the application. SpreadMethod The SpreadMethod class provides values for the spreadMethod parameter in the beginGradientFill() and lineGradientStyle() methods of the Graphics class.Object The SpreadMethod class provides values for the spreadMethod parameter in the beginGradientFill() and lineGradientStyle() methods of the Graphics class.

The following example shows the same gradient fill using various spread methods:

SpreadMethod.PADSpreadMethod.REFLECTSpreadMethod.REPEAT
flash.display.Graphics.beginGradientFill()flash.display.Graphics.lineGradientStyle()PAD Specifies that the gradient use the pad spread method.padString Specifies that the gradient use the pad spread method. REFLECT Specifies that the gradient use the reflect spread method.reflectString Specifies that the gradient use the reflect spread method. REPEAT Specifies that the gradient use the repeat spread method.repeatString Specifies that the gradient use the repeat spread method.
FocusDirection The FocusDirection class enumerates values to be used for the direction parameter of the assignFocus() method of a Stage object and for the direction property of a FocusEvent object.Object The FocusDirection class enumerates values to be used for the direction parameter of the assignFocus() method of a Stage object and for the direction property of a FocusEvent object. flash.events.FocusEvent.directionflash.display.Stage.assignFocus()BOTTOM Indicates that focus should be given to the object at the end of the reading order.bottomString Indicates that focus should be given to the object at the end of the reading order. NONE Indicates that focus object within the interactive object should not change.noneString Indicates that focus object within the interactive object should not change. TOP Indicates that focus should be given to the object at the beginning of the reading order.topString Indicates that focus should be given to the object at the beginning of the reading order. StageAlign The StageAlign class provides constant values to use for the Stage.align property.Object The StageAlign class provides constant values to use for the Stage.align property. flash.display.Stage.alignBOTTOM_LEFT Specifies that the Stage is aligned in the bottom-left corner.BLString Specifies that the Stage is aligned in the bottom-left corner. BOTTOM_RIGHT Specifies that the Stage is aligned in the bottom-right corner.BRString Specifies that the Stage is aligned in the bottom-right corner. BOTTOM Specifies that the Stage is aligned at the bottom.BString Specifies that the Stage is aligned at the bottom. LEFT Specifies that the Stage is aligned on the left.LString Specifies that the Stage is aligned on the left. RIGHT Specifies that the Stage is aligned to the right.RString Specifies that the Stage is aligned to the right. TOP_LEFT Specifies that the Stage is aligned in the top-left corner.TLString Specifies that the Stage is aligned in the top-left corner. TOP_RIGHT Specifies that the Stage is aligned in the top-right corner.TRString Specifies that the Stage is aligned in the top-right corner. TOP Specifies that the Stage is aligned at the top.TString Specifies that the Stage is aligned at the top. ColorCorrectionSupport The ColorCorrectionSupport class provides values for the flash.display.Stage.colorCorrectionSupport property.Object The ColorCorrectionSupport class provides values for the flash.display.Stage.colorCorrectionSupport property. flash.display.Stage.colorCorrectionSupportDEFAULT_OFF Color correction is supported, but off by default.defaultOffString Color correction is supported, but off by default. DEFAULT_ON Color correction is supported, and on by default.defaultOnString Color correction is supported, and on by default. UNSUPPORTED Color correction is not supported by the host environment.unsupportedString Color correction is not supported by the host environment. GraphicsShaderFill Defines a shader fill.flash.display:IGraphicsFillflash.display:IGraphicsDataObject Defines a shader fill.

Use a GraphicsShaderFill object with the Graphics.drawGraphicsData() method. Drawing a GraphicsShaderFill object is the equivalent of calling the Graphics.beginShaderFill() method.

flash.display.Graphics.beginShaderFill()flash.display.Graphics.drawGraphicsData()GraphicsShaderFill Creates a new GraphicsShaderFill object.shaderflash.display:ShadernullThe shader to use for the fill. This Shader instance is not required to specify an image input. However, if an image input is specified in the shader, the input must be provided manually by setting the input property of the corresponding ShaderInput property of the Shader.data property. matrixflash.geom:MatrixnullA matrix object (of the flash.geom.Matrix class), which you can use to define transformations on the shader. Creates a new GraphicsShaderFill object. flash.geom.Matrixflash.display.Shadermatrix A matrix object (of the flash.geom.Matrix class), which you can use to define transformations on the shader.flash.geom:Matrix A matrix object (of the flash.geom.Matrix class), which you can use to define transformations on the shader. For example, you can use the following matrix to rotate a shader by 45 degrees (pi/4 radians): matrix = new flash.geom.Matrix(); matrix.rotate(Math.PI / 4);

The coordinates received in the shader are based on the matrix that is specified for the matrix parameter. For a default (null) matrix, the coordinates in the shader are local pixel coordinates which can be used to sample an input.

flash.geom.Matrix
shader The shader to use for the fill.flash.display:Shader The shader to use for the fill. This Shader instance is not required to specify an image input. However, if an image input is specified in the shader, the input must be provided manually by setting the input property of the corresponding ShaderInput property of the Shader.data property.

When you pass a Shader instance as an argument the shader is copied internally and the drawing fill operation uses that internal copy, not a reference to the original shader. Any changes made to the shader, such as changing a parameter value, input, or bytecode, are not applied to the copied shader that's used for the fill.

flash.display.Shader
Shape This class is used to create lightweight shapes using the ActionScript drawing application program interface (API).A display object used for shapes. flash.display:DisplayObject This class is used to create lightweight shapes using the ActionScript drawing application program interface (API). The Shape class includes a graphics property, which lets you access methods from the Graphics class.

The Sprite class also includes a graphicsproperty, and it includes other features not available to the Shape class. For example, a Sprite object is a display object container, whereas a Shape object is not (and cannot contain child display objects). For this reason, Shape objects consume less memory than Sprite objects that contain the same graphics. However, a Sprite object supports user input events, while a Shape object does not.

The following example uses the ShapeExample class to draw a circle, a rounded rectangle, and a square. This task is accomplished by performing the following steps:
  1. Declare a size property for later use in determining the size of each shape.
  2. Declare properties that set the background color to orange, the border color to dark gray, the border size to 0 pixels, the corner radius to 9 pixels, and set the space between the stage edge and the other objects to be 5 pixels.
  3. Use the properties declared in the preceding steps along with the built-in methods of the Graphics class to draw the circle, rounded rectangle, and square at coordinates x = 0, y = 0.
  4. Redraw each of the shapes along the top of the stage, starting at x = 5, y = 5, with a 5-pixel spacing between shapes by using the refreshLayout() method.
package { import flash.display.DisplayObject; import flash.display.Graphics; import flash.display.JointStyle; import flash.display.LineScaleMode; import flash.display.Shape; import flash.display.Sprite; public class ShapeExample extends Sprite { private var size:uint = 80; private var bgColor:uint = 0xFFCC00; private var borderColor:uint = 0x666666; private var borderSize:uint = 0; private var cornerRadius:uint = 9; private var gutter:uint = 5; public function ShapeExample() { doDrawCircle(); doDrawRoundRect(); doDrawRect(); refreshLayout(); } private function refreshLayout():void { var ln:uint = numChildren; var child:DisplayObject; var lastChild:DisplayObject = getChildAt(0); lastChild.x = gutter; lastChild.y = gutter; for (var i:uint = 1; i < ln; i++) { child = getChildAt(i); child.x = gutter + lastChild.x + lastChild.width; child.y = gutter; lastChild = child; } } private function doDrawCircle():void { var child:Shape = new Shape(); var halfSize:uint = Math.round(size/2); child.graphics.beginFill(bgColor); child.graphics.lineStyle(borderSize, borderColor); child.graphics.drawCircle(halfSize, halfSize, halfSize); child.graphics.endFill(); addChild(child); } private function doDrawRoundRect():void { var child:Shape = new Shape(); child.graphics.beginFill(bgColor); child.graphics.lineStyle(borderSize, borderColor); child.graphics.drawRoundRect(0, 0, size, size, cornerRadius); child.graphics.endFill(); addChild(child); } private function doDrawRect():void { var child:Shape = new Shape(); child.graphics.beginFill(bgColor); child.graphics.lineStyle(borderSize, borderColor); child.graphics.drawRect(0, 0, size, size); child.graphics.endFill(); addChild(child); } } }
flash.display.Graphicsflash.display.SpriteShape Creates a new Shape object. Creates a new Shape object. graphics Specifies the Graphics object belonging to this Shape object, where vector drawing commands can occur.flash.display:GraphicsSpecifies the Graphics object for the Shape object. Specifies the Graphics object belonging to this Shape object, where vector drawing commands can occur.
ShaderParameterType This class defines the constants that represent the possible values for the ShaderParameter class's type property.Object This class defines the constants that represent the possible values for the ShaderParameter class's type property. Each constant represents one of the data types available in Flash Player for parameters in the Pixel Bender shader language. flash.display.ShaderParameter.typeBOOL2 Indicates that the shader parameter is defined as a bool2 value, equivalent to an Array of two Boolean instances in ActionScript.bool2String Indicates that the shader parameter is defined as a bool2 value, equivalent to an Array of two Boolean instances in ActionScript. BOOL3 Indicates that the shader parameter is defined as a bool3 value, equivalent to an Array of three Boolean instances in ActionScript.bool3String Indicates that the shader parameter is defined as a bool3 value, equivalent to an Array of three Boolean instances in ActionScript. BOOL4 Indicates that the shader parameter is defined as a bool4 value, equivalent to an Array of four Boolean instances in ActionScript.bool4String Indicates that the shader parameter is defined as a bool4 value, equivalent to an Array of four Boolean instances in ActionScript. BOOL Indicates that the shader parameter is defined as a bool value, equivalent to a single Boolean instance in ActionScript.boolString Indicates that the shader parameter is defined as a bool value, equivalent to a single Boolean instance in ActionScript.

Note that even though the parameter only expects a single value, the ShaderParameter.value property is an Array, so the single value must be the only element of an Array assigned to the value property, like this:

// assumes the shader has a parameter named "param" // whose data type is bool myShader.data.param.value = [true];
FLOAT2 Indicates that the shader parameter is defined as a float2 value, equivalent to an Array of two Number instances in ActionScript.float2String Indicates that the shader parameter is defined as a float2 value, equivalent to an Array of two Number instances in ActionScript. flash.display.ShaderParameter.typeFLOAT3 Indicates that the shader parameter is defined as a float3 value, equivalent to an Array of three Number instances in ActionScript.float3String Indicates that the shader parameter is defined as a float3 value, equivalent to an Array of three Number instances in ActionScript. FLOAT4 Indicates that the shader parameter is defined as a float4 value, equivalent to an Array of four Number instances in ActionScript.float4String Indicates that the shader parameter is defined as a float4 value, equivalent to an Array of four Number instances in ActionScript. FLOAT Indicates that the shader parameter is defined as a float value, equivalent to a single Number instance in ActionScript.floatString Indicates that the shader parameter is defined as a float value, equivalent to a single Number instance in ActionScript.

Note that even though the parameter only expects a single value, the ShaderParameter.value property is an Array, so the single value must be the only element of an Array assigned to the value property, like this:

// assumes the shader has a parameter named "param" // whose data type is float myShader.data.param.value = [22.5];
flash.display.ShaderParameter.type
INT2 Indicates that the shader parameter is defined as an int2 value, equivalent to an Array of two int or uint instances in ActionScript.int2String Indicates that the shader parameter is defined as an int2 value, equivalent to an Array of two int or uint instances in ActionScript. INT3 Indicates that the shader parameter is defined as an int3 value, equivalent to an Array of three int or uint instances in ActionScript.int3String Indicates that the shader parameter is defined as an int3 value, equivalent to an Array of three int or uint instances in ActionScript. INT4 Indicates that the shader parameter is defined as an int4 value, equivalent to an Array of four int or uint instances in ActionScript.int4String Indicates that the shader parameter is defined as an int4 value, equivalent to an Array of four int or uint instances in ActionScript. INT Indicates that the shader parameter is defined as an int value, equivalent to a single int or uint instance in ActionScript.intString Indicates that the shader parameter is defined as an int value, equivalent to a single int or uint instance in ActionScript.

Note that even though the parameter only expects a single value, the ShaderParameter.value property is an Array, so the single value must be the only element of an Array assigned to the value property, like this:

// assumes the shader has a parameter named "param" // whose data type is int myShader.data.param.value = [275];
MATRIX2X2 Indicates that the shader parameter is defined as a float2x2 value, equivalent to a 2-by-2 matrix.matrix2x2String Indicates that the shader parameter is defined as a float2x2 value, equivalent to a 2-by-2 matrix. This matrix is represented as an Array of four Number instances in ActionScript. MATRIX3X3 Indicates that the shader parameter is defined as a float3x3 value, equivalent to a 3-by-3 matrix.matrix3x3String Indicates that the shader parameter is defined as a float3x3 value, equivalent to a 3-by-3 matrix. This matrix is represented as an Array of nine Number instances in ActionScript. MATRIX4X4 Indicates that the shader parameter is defined as a float4x4 value, equivalent to a 4-by-4 matrix.matrix4x4String Indicates that the shader parameter is defined as a float4x4 value, equivalent to a 4-by-4 matrix. This matrix is represented as an Array of 16 Number instances in ActionScript.
GraphicsPathWinding The GraphicsPathWinding class provides values for the flash.display.GraphicsPath.winding property and the flash.display.Graphics.drawPath() method to determine the direction to draw a path.Object The GraphicsPathWinding class provides values for the flash.display.GraphicsPath.winding property and the flash.display.Graphics.drawPath() method to determine the direction to draw a path. A clockwise path is positively wound, and a counter-clockwise path is negatively wound:

When paths intersect or overlap, the winding direction determines the rules for filling the areas created by the intersection or overlap:

flash.display.GraphicsPath.windingflash.display.Graphics.drawPath()EVEN_ODD Establishes the even-odd winding type.evenOddString Establishes the even-odd winding type. The even-odd winding type is the rule used by all of the original drawing API and is the default type for the flash.display.Graphics.drawPath() method. Any overlapping paths will alternate between open and closed fills. If two squares drawn with the same fill intersect, the area of the intersection is not filled. Adjacent areas are not the same (neither both filled nor both unfilled). NON_ZERO Establishes the non-zero winding type.nonZeroString Establishes the non-zero winding type. The non-zero winding type determines that when paths of opposite winding intersect, the intersection area is unfilled (as with the even-odd winding type). For paths of the same winding, the intersection area is filled.
ActionScriptVersion The ActionScriptVersion class is an enumeration of constant values that indicate the language version of a loaded SWF file.Object The ActionScriptVersion class is an enumeration of constant values that indicate the language version of a loaded SWF file. The language version constants are provided for use in checking the actionScriptVersion property of a flash.display.LoaderInfo object. flash.display.LoaderInfo.actionScriptVersionACTIONSCRIPT2 ActionScript language version 2.0 and earlier.2uint ActionScript language version 2.0 and earlier. ACTIONSCRIPT3 ActionScript language version 3.0.3uint ActionScript language version 3.0. GraphicsPath A collection of drawing commands and the coordinate parameters for those commands.flash.display:IGraphicsPathflash.display:IGraphicsDataObject A collection of drawing commands and the coordinate parameters for those commands.

Use a GraphicsPath object with the Graphics.drawGraphicsData() method. Drawing a GraphicsPath object is the equivalent of calling the Graphics.drawPath() method.

The GraphicsPath class also has its own set of methods (curveTo(), lineTo(), moveTo() wideLineTo() and wideMoveTo()) similar to those in the Graphics class for making adjustments to the GraphicsPath.commands and GraphicsPath.data vector arrays.

flash.display.Graphics.drawGraphicsData()flash.display.Graphics.drawPath()GraphicsPath Creates a new GraphicsPath object.commandsnullA Vector of integers representing commands defined by the GraphicsPathCommand class. datanullA Vector of Numbers where each pair of numbers is treated as a point (an x, y pair). windingStringevenOddSpecifies the winding rule using a value defined in the GraphicsPathWinding class. Creates a new GraphicsPath object. flash.display.GraphicsPathCommandflash.display.GraphicsPathWindingcurveTo Adds a new "curveTo" command to the commands vector and new coordinates to the data vector.controlXNumberA number that specifies the horizontal position of the control point relative to the registration point of the parent display object. controlYNumberA number that specifies the vertical position of the control point relative to the registration point of the parent display object. anchorXNumberA number that specifies the horizontal position of the next anchor point relative to the registration point of the parent display object. anchorYNumberA number that specifies the vertical position of the next anchor point relative to the registration point of the parent display object. Adds a new "curveTo" command to the commands vector and new coordinates to the data vector. flash.display.GraphicsPathCommand.CURVE_TOflash.display.Graphics.curveTo()lineTo Adds a new "lineTo" command to the commands vector and new coordinates to the data vector.xNumberThe x coordinate of the destination point for the line. yNumberThe y coordinate of the destination point for the line. Adds a new "lineTo" command to the commands vector and new coordinates to the data vector. flash.display.GraphicsPathCommand.LINE_TOflash.display.Graphics.lineTo()moveTo Adds a new "moveTo" command to the commands vector and new coordinates to the data vector.xNumberThe x coordinate of the destination point. yNumberThe y coordinate of the destination point. Adds a new "moveTo" command to the commands vector and new coordinates to the data vector. flash.display.GraphicsPathCommand.MOVE_TOflash.display.Graphics.moveTo()wideLineTo Adds a new "wideLineTo" command to the commands vector and new coordinates to the data vector.xNumberThe x-coordinate of the destination point for the line. yNumberThe y-coordinate of the destination point for the line. Adds a new "wideLineTo" command to the commands vector and new coordinates to the data vector. flash.display.GraphicsPathCommand.WIDE_LINE_TOwideMoveTo Adds a new "wideMoveTo" command to the commands vector and new coordinates to the data vector.xNumberThe x-coordinate of the destination point. yNumberThe y-coordinate of the destination point. Adds a new "wideMoveTo" command to the commands vector and new coordinates to the data vector. flash.display.GraphicsPathCommand.WIDE_MOVE_TOcommands The Vector of drawing commands as integers representing the path. The Vector of drawing commands as integers representing the path. Each command can be one of the values defined by the GraphicsPathCommand class. flash.display.GraphicsPathCommanddata The Vector of Numbers containing the parameters used with the drawing commands. The Vector of Numbers containing the parameters used with the drawing commands. winding Specifies the winding rule using a value defined in the GraphicsPathWinding class.String Specifies the winding rule using a value defined in the GraphicsPathWinding class. flash.display.GraphicsPathWinding
MorphShape The MorphShape class represents MorphShape objects on the display list.flash.display:DisplayObject The MorphShape class represents MorphShape objects on the display list. You cannot create MorphShape objects directly in ActionScript; they are created when you create a shape tween in the Flash authoring tool. PixelSnapping The PixelSnapping class is an enumeration of constant values for setting the pixel snapping options by using the pixelSnapping property of a Bitmap object.Object The PixelSnapping class is an enumeration of constant values for setting the pixel snapping options by using the pixelSnapping property of a Bitmap object. flash.display.Bitmap.pixelSnappingALWAYS A constant value used in the pixelSnapping property of a Bitmap object to specify that the bitmap image is always snapped to the nearest pixel, independent of any transformation.alwaysString A constant value used in the pixelSnapping property of a Bitmap object to specify that the bitmap image is always snapped to the nearest pixel, independent of any transformation. AUTO A constant value used in the pixelSnapping property of a Bitmap object to specify that the bitmap image is snapped to the nearest pixel if it is drawn with no rotation or skew and it is drawn at a scale factor of 99.9% to 100.1%.autoString A constant value used in the pixelSnapping property of a Bitmap object to specify that the bitmap image is snapped to the nearest pixel if it is drawn with no rotation or skew and it is drawn at a scale factor of 99.9% to 100.1%. If these conditions are satisfied, the image is drawn at 100% scale, snapped to the nearest pixel. Internally, this setting allows the image to be drawn as fast as possible by using the vector renderer. NEVER A constant value used in the pixelSnapping property of a Bitmap object to specify that no pixel snapping occurs.neverString A constant value used in the pixelSnapping property of a Bitmap object to specify that no pixel snapping occurs. GraphicsPathCommand Defines the values to use for specifying path-drawing commands.Object Defines the values to use for specifying path-drawing commands.

The values in this class are used by the Graphics.drawPath() method, or stored in the commands vector of a GraphicsPath object.

flash.display.Graphics.drawPath()flash.display.GraphicsPath.commandsCURVE_TO Specifies a drawing command that draws a curve from the current drawing position to the x- and y-coordinates specified in the data vector, using a control point.3int Specifies a drawing command that draws a curve from the current drawing position to the x- and y-coordinates specified in the data vector, using a control point. This command produces the same effect as the Graphics.lineTo() method, and uses two points in the data vector control and anchor: (cx, cy, ax, ay ). flash.display.Graphics.curveTo()LINE_TO Specifies a drawing command that draws a line from the current drawing position to the x- and y-coordinates specified in the data vector.2int Specifies a drawing command that draws a line from the current drawing position to the x- and y-coordinates specified in the data vector. This command produces the same effect as the Graphics.lineTo() method, and uses one point in the data vector: (x,y). flash.display.Graphics.lineTo()MOVE_TO Specifies a drawing command that moves the current drawing position to the x- and y-coordinates specified in the data vector.1int Specifies a drawing command that moves the current drawing position to the x- and y-coordinates specified in the data vector. This command produces the same effect as the Graphics.moveTo() method, and uses one point in the data vector: (x,y). flash.display.Graphics.moveTo()NO_OP Represents the default "do nothing" command.0int Represents the default "do nothing" command. WIDE_LINE_TO Specifies a "line to" drawing command, but uses two sets of coordinates (four values) instead of one set.5int Specifies a "line to" drawing command, but uses two sets of coordinates (four values) instead of one set. This command allows you to switch between "line to" and "curve to" commands without changing the number of data values used per command. This command uses two sets in the data vector: one dummy location and one (x,y) location.

The WIDE_LINE_TO and WIDE_MOVE_TO command variants consume the same number of parameters as does the CURVE_TO command.

LINE_TOflash.display.Graphics.lineTo()
WIDE_MOVE_TO Specifies a "move to" drawing command, but uses two sets of coordinates (four values) instead of one set.4int Specifies a "move to" drawing command, but uses two sets of coordinates (four values) instead of one set. This command allows you to switch between "move to" and "curve to" commands without changing the number of data values used per command. This command uses two sets in the data vector: one dummy location and one (x,y) location.

The WIDE_LINE_TO and WIDE_MOVE_TO command variants consume the same number of parameters as does the CURVE_TO command.

MOVE_TOflash.display.Graphics.moveTo()