You are on page 1of 224

Web Animation and

Interactivity
Web Animation and Interactivity

© 2013 Aptech Limited

All rights reserved.

No part of this book may be reproduced or copied in any form or by any means – graphic, electronic or
mechanical, including photocopying, recording, taping, or storing in information retrieval system or sent
or transferred without the prior written permission of copyright owner Aptech Limited.

All trademarks acknowledged.

APTECH LIMITED

Contact E-mail: ov-support@onlinevarsity.com

Edition 1 – 2013

Disclaimer: Arena Multimedia is registered Brand of Aptech Ltd.


Preface

This book, Web Animation and Interactivity, introduces you to the various features of Flash CS6 and ActionScript 3.0
(AS3.0). It meets almost all your requirements of Web related graphics and basic concepts of programming that provides
a foundation for developing applications in ActionScript.

The ARENA Design team has designed this course keeping in mind that motivation coupled with relevant training and
methodology can bring out the best. The team will be glad to receive your feedback, suggestions, and recommendations
for improvement of the book.

ARENA Design Team


Table of Content

Working with Flash CS6


Getting Started
Flash Workspace
Drawing and Reshaping Objects
Working with Layers
Summary
Exercise

Working with Colors and Images


Working with Fills
Using the Kuler Panel
Paint Using the Brush Tool
Organizing Objects
Getting Images in Flash
Summary
Exercise

Working with Text


Overview
Formatting Text
Creating Text Columns
Changing Advanced Character Options
Multilanguage Text
Summary
Exercise

Symbols and Effects


Understanding Symbols and Instances
Working with Instances
Editing Symbols
Swapping Symbols
Working with Filters
Understanding the Flash Library
Creating Patterns with the Spray Brush and Deco Tool
3D Spaces
Summary
Exercise
Frame-by-Frame Animation and Shape Tweening
Understanding Timeline
Changing the Frame Rate
Frame-by-Frame Animation
Using Onion Skin
Creating Simple Frame-by-Frame Animation
Previewing the Animation
Shape Tweening
Summary
Exercise

Motion Tweening and Classic Tweening


Introduction
Understanding Motion Tween
Understanding Classic Tween
Summary
Exercise

Working with Audio and Video


Working with Videos
Working with Sound
Summary
Exercise

Exporting and Publishing


Exporting Images and Graphics
Exporting Video and Sound
Publishing Movies
Summary
Exercise

Introduction to ActionScript 3.0 and Programming Concept


Core Concepts
Conditionals, Loops, and Operators
Static Variables and Static Methods
Functions
Arrays
Summary
Exercise

Working with Built-in Classes (Text, Video, and Sound)


Working with Text
Working with Video
Working with Sound
Summary
Exercise

Object-Oriented Programming with ActionScript 3.0


Basics of Object-Oriented Programming
Classes
Interfaces
Inheritance
Summary
Exercise

Working with ActionScript 3.0 Objects


Introduction
Properties
Methods
Events and Handling Events
Creating Object Instances
Toolkit for CreateJS
Summary
Exercise

Iconography


: System Requirements



: Note

: Tip

: Quick Test


: Quick Answers

: Exercise Answers
S e s s io n 1
Working with Flash CS6
Learning Outcomes
In this session, you will learn to:
¾¾ Describe the Flash CS6 interface
¾¾ Draw and reshape objects
¾¾ Work with layers

Adobe Flash Professional CS6 is a useful tool for the creation of multimedia content and animation. The interactive
designs thus created can be presented consistently in desktops as well as other multiple devices, which include tablets,
smartphones, and televisions.

System Requirements
• Windows Operating System

• Intel® Pentium® 4 or AMD Athlon® 64 processor

• Microsoft Windows XP with Service Pack 3 or Windows 7 with Service Pack 1

• 2 GB of RAM (3 GB recommended)

• 3.5 GB of available hard-disk

• Java™ Runtime Environment 1.6

• Graphics card with at least 64 MB of VRAM

• QuickTime 7.6.6 software required for multimedia features

• 1024×768 display (1280×800 recommended)

1.1 Getting Started


1.1.1 Welcome Screen
A welcome panel appears as soon as Flash is launched. Options for creating a Flash file are provided in the welcome
panel.

In order to begin working, you can either use the commands available in the File menu or select an option present in the
welcome panel. It includes the following three columns:
¾¾ Predefined templates, which define standard workspace sizes, are present in the left column.
¾¾ Different Flash variants are present in the middle column.
¾¾ Links to Adobe’s introductory text from Flash development center are present in the right column. The respective
content open in the default Web browser.

Refer to Figure 1.1. On clicking the Don’t show again option, which appears on the bottom left corner, the welcome
panel does not appear anymore. However, the options present in the welcome panel can be accessed through the File
menu. It is possible to launch the welcome panel again. To do so, from the Edit menu, click Preferences. In the dialog
box that appears, under the General category, select Welcome Screen from the On Launch: drop-down list.
Figure 1.1: Welcome screen

ActionScript 3.0 is the latest Flash scripting standard. Hence, it is recommended to select AS3 before beginning work in
Flash. A 550x400 px workspace opens, where Flash can be configured for AS3.

1.1.2 Creating a New Document


Each file in Flash is referred to as a document. Flash documents have a .fla extension. They store information for
developing, designing, and testing interactive content. To convert a Flash file into a movie file, the Flash document
should be published as a Flash movie. For this, the Flash file should be saved with a .swf extension.

Flash documents are based on scripting languages, of which, ActionScript 2.0 or ActionScript 3.0 can be used. To open
a new document, choose New from File menu. Alternatively, an option for creating a new document is present in the
welcome panel.

A new document in Flash is titled Untitled-1, by default. Successive new documents are named consecutively. In
addition, a user can work on multiple documents simultaneously. Refer to Figure 1.2.

To create a new document, click the General tab in the New Document dialog box. Set the scripting language to
ActionScript 3.0. The document type can be selected from the list. Then, click OK.

Figure 1.2: New Document dialog box


1.1.3 Setting Document Properties
The overall look and feel of a movie can be set by defining the document properties right in the beginning of the project.
Elements, such as background color, size, and location of stage, animation frame rate, and ruler measurement units can
be defined in the Document Property dialog box or the Property Inspector window. Any change in the default settings
get applied only to the current document.

Select Properties from the Window menu to access the Property Inspector window. Refer to Figure 1.3. The
Properties section in the window contains the following options:
¾¾ FPS: FPS refers to frames per second. This option is used to set the frame rate for the movie. Frame rate
defines the speed of the movie. Enter the number of animation frames to be displayed per second in the Frame
Rate box. Alternatively, drag the field to modify the frame rate.
¾¾ Size: This option is used to define the size of the animation movie. Click Edit to set the animation dimensions.

Figure 1.3: Properties Inspector window

Figure 1.4 displays the Document Settings dialog box. It contains options as shown in Table 1.1.

Figure 1.4: Document Settings dialog box


Options Description
Dimensions The dimensions, namely, height and width of the stage can be set using this option.
Ruler Units Units for height and width measurement are as follows:
¾¾ Inches
¾¾ Inches (decimals)
¾¾ Points
¾¾ Centimeters
¾¾ Millimeters
¾¾ Pixels
Match This option defines the space around the stage. It has the following option buttons:
¾¾ Default: This button is used to set the stage to the default size of 550x400 pixels.
¾¾ Contents: This button is used to assign equal space around the content.
¾¾ Printer: This button is used to set the stage size to maximum available print area.
Background Color This option is used to define the background color of a stage. Double-click the color swatch and
choose the desired color to set it as the background color. Alternatively, use Properties panel
to set the desired background color.
Frame Rate Using this button, the frame rate of the movie can be changed.
Make Default This option is used to set the changed settings as the default settings.
Table 1.1: Options available in the Document Settings dialog box

1.1.4 Opening Existing Documents


Documents can be opened in Flash by using the File menu or through the welcome panel. Extensible Form Language
or XFL is the internal format of a .fla file. The content of the file can be transferred between Flash and other Adobe
programs, such as Adobe InDesign and Adobe After Effects. XFL file can be opened using a method, which is same as
the one used to open a .fla file.

On opening a document in Flash, a tab appears across the top of the document window. Clicking the tab,
displays the document.
1.1.5 Saving a Document
Flash documents are saved with .fla extensions, by default. On clicking Save, a prompt appears to specify the name
of the file and the location where it should be saved. A file not saved, has an asterisk displayed after the name in the
document tab. Older versions of a file can be retained while saving new files, by clicking Save as in File menu. .fla files
can also be saved in the XFL format. This format represents uncompressed version of a Flash document and can be
used in Adobe InDesign and After Effects programs.

To save a document, click Save from the File menu. In the dialog box that appears, give an appropriate name to the file,
specify the location for the file, and then, click Save.

For detailed step-by-step procedure, refer to demo Getting Started from:

eResources 4 Me>> My Varsity>> Web Animation and Interactivity>> Show Me How>> Getting Started>> Saving a
Document

1.2 Flash Workspace


For the purpose of effective creation of movies in Flash, a thorough knowledge of the authoring interface is necessary.
Flash workspace consists of the following elements:
¾¾ Menu bar
¾¾ Stage
¾¾ Timeline
¾¾ Tools panel
¾¾ Property Inspector
¾¾ Library panel

The panels can be opened and closed or docked and undocked as per requirement. Refer to Figure 1.5. Most
applications of Adobe Creative Suite share similar workspaces. This makes it easy to move between applications.

Figure 1.5: Flash workspace

Click here to know more about the Flash workspace.

1.2.1 Working with Panels


The windows through which options and elements of a document can be viewed, organized, and changed are known
as panels. A user can access and work with multiple panels simultaneously. In order to save space, panels can be
collapsed and expanded.
■■ Features of a panel

Each panel in the Flash workspace is equipped with certain features, which are as follows:
¾¾ The tab titles, buttons for minimizing, maximizing, and closing the window, and Options menu are all present
in the header of the panel.
¾¾ There is also a double arrow available, which helps in expanding or collapsing the panel.
¾¾ Commands to group, rename, maximize, and close a panel are present in the Options menu. Additionally, it
also has a Help option.
■■ Opening and closing a panel

Select the name of the required panel from the Window menu to open that panel. Alternatively, choose Other
Panels options from Window menu and then, select the name of the required panel. Clicking Close button on the
panel or the tab that is to be closed closes the panel.
■■ Collapsing and expanding a panel

Double-click the title tab on the header of a panel in order to collapse or expand the panel. To hide or show hidden
panels, choose the respective Hide Panels and Show Panels options in Window menu.
For auto-collapsing icon panels and auto-showing hidden panels, right-click the header tab of the panel and
then, choose Auto-Collapse Iconic Panels and Auto-Show Hidden Panels, respectively.

■■ Collapsing and expanding panel sets

Click Collapse to Icons double arrow, which is present at the top of the panel in order to collapse a panel set.
Click Expand Dock double arrow, which is present at the top of the panel in order to expand a panel set. Choosing
Auto-Collapse Iconic Panels and Auto-Show Hidden panels collapses and hides panels automatically, when the
user clicks at a point away from the panel.
■■ Panel options menu

Panel options menu is present on the right side of the header bar of the panel. The commands present in the menu
are as follows:
¾¾ Help: This command is used to access help for Flash.
¾¾ Close: This command is used to close the tab that is currently displayed in the panel.
¾¾ Close group: This command is used to close all the tabs present in the panel.
■■ Docking and undocking panels

Temporary docking and undocking, attaching and detaching panels or panel groups or panel tabs can be done in
Flash. To dock or undock a panel or panel group, drag the panel(s) around the program window. When a panel
is dragged over a dockable area, an outline can be observed around the target dock. The panel now fits in the
dockable area once the mouse button is released. It remains in the dockable area till it is moved. On the other hand,
appearance of outline is not seen when a panel is moved over an undockable area.

It is not possible to dock document panels on the stage.

■■ Moving panels

While moving panels, blue highlighted areas appear, indicating panel drop zones. For instance, dragging a panel
to the narrow blue drop zone, present above or below another panel moves the panel up or down within a dock.
Dropping a panel in an area, which is not a drop zone makes the panel float freely within the workspace. A panel
can be moved by dragging its tab, whereas, a panel group can be dragged by its title bar.

A drop zone is activated by the position of the mouse, but not the position of the panel. Incase a drop zone is
not visible, it can be seen by dragging the mouse to the area where the drop zone is expected to be.

■■ Grouping and ungrouping panels

Organization and workflow in Flash can be improved greatly by grouping panels. Grouping and ungrouping, and
docking and undocking panel windows can be done by using the panel tab.
¾¾ Click the header bar of a panel set or the tab of an individual panel and drag from one window to another for
grouping panels.
¾¾ Click and drag a panel till the appearance of a blue outline is seen around the panel in order to add panels.
¾¾ Click a panel and drag it till the appearance of a blue line is seen along the side of the panel in order to append
panels.
¾¾ Click a specific window and drag it away from the panels to an empty area of the Flash window in order to
ungroup panels.
■■ Resizing panels

Double-clicking the tab of a panel, a panel group, or a panel stack alters its size. Alternatively, the tab area or the
empty space present next to the tabs can be double-clicked. Dragging the sides of the panel helps in resizing the
panel.
■■ Stack floating panels

A panel, when dragged out of its dock into an area which is not a drop zone, floats freely in the workspace. This type
of floating panel can be placed in any position in the workspace. Several floating panels can be stacked into panel
groups. All these panels move as a single unit on dragging their top-most title bar. Actions that can be performed
with respect to floating panels are as follows:
¾¾ Dragging a panel by its tab and dropping it in a drop zone present at the bottom of another panel helps in
stacking the floating panels.
¾¾ Dragging a panel upward or downward using its tab changes the order of stacking of the panels.
¾¾ Dragging a panel by its tab or title bar from the stack removes it from a panel stack and makes it float by itself
in the workspace.

1.2.2 Creating a Custom Workspace


Flash CS6 offers certain built-in workspaces, which can be used by developers. In addition, self-customized workspaces
can also be created as per the developers’ requirements. After placing all the desired elements in the customized
workspace, the location of various windows, panels, and other elements within the workspace can be saved as a
workspace or a custom panel set. This arrangement can be used in the future by navigating to the Applications bar
from the Workspace menu. Alternatively, you can navigate to the Window menu and select it from the Workspace
sub-menu. The built-in workspaces available in Flash CS6 are as follows:
¾¾ Animator
¾¾ Classic
¾¾ Debug
¾¾ Designer
¾¾ Developer
¾¾ Essentials
¾¾ Small Screen

Customized workspaces can be removed or renamed at any point in time. The


first step in the creation of a workspace is arrangement of panels as per user’s
requirement. Following this, from the Window menu, choose the New Workspace
command. The New Workspace dialog box appears in which, an appropriate
name for the workspace should be typed in the Name text box. Then, click OK.
The new arrangement of panels is not saved as a new workspace. Alternatively, a
new workspace can be created from the Workspace menu. Refer to Figure 1.6.
■■ Displaying a workspace

Customized workspaces can be accessed from the Workspace menu. Figure 1.6: Workspace menu
■■ Deleting a workspace

Navigate to the Workspace menu and choose Manage Workspaces. The Manage Workspaces dialog box
appears in which, the panel set that is to be deleted should be selected. Then, click Delete. In the prompt that
appears, click Yes, followed by OK.

1.2.3 Setting Preferences


It is possible to customize the workspace in the desired manner by modifying the general default settings for ActionScript,
Auto Format, Clipboard, Drawing, Text, Warnings, PSD file Importer, and AI File Importer. To do this, navigate to
the Edit menu and choose Preferences. A Preferences window opens, where the necessary changes in settings can
be done. Refer to Figure 1.7.

1.2.4 Exploring the Tools Panel


The tools in the toolbox are used for creating objects, painting, or modifying them. The view of the stage can also be
modified. By default, the toolbox is present on the left side. However, it can be dragged and placed wherever required.
As shown in Figure 1.8, the toolbox is divided into four sections, which are as follows:
¾¾ Drawing, painting, and selection: The tools in this section are used to draw or modify shapes. Each tool in this
section has pre-defined properties.
¾¾ View: The tools in this section are used for zooming and panning objects on the stage. There are two tools in
this section, namely, Hand tool and Zoom tool.
¾¾ Colors: This section is used to fill or modify colors of an object. It shows the Stroke color tool and Fill color
tool.
¾¾ Options: This sections gives an additional control over the Drawing tool that is selected. The options in this
section change based on the drawing tool that has been selected by the developer.

Each tool in the toolbox has unique properties and performs a unique function. However, some tools are interlinked to
others. To view the available options under the Tools command, select Tools from Window menu.

Figure 1.8: Tools panel

Figure 1.7: Preferences dialog box

Quick Test 1.1


1. Ruler units define the space around the stage.
True False

2. To change the stacking order of the panels, users can drag a panel either upward or downward using its tab.
True False

3. The Tools command can be accessed from the Window menu.


True False

1.3 Drawing and Reshaping Objects


1.3.1 Drawing Modes
Two methods are used in Flash for creation and modification of shapes, namely, merge drawing and object drawing.
Refer to Figure 1.9.
Figure 1.9: Appearance of the object drawing mode and merge drawing mode in the Tools panel
■■ Merge drawing mode

This mode is the default drawing mode in Flash. In this mode, when two shapes are drawn overlapping each other,
their shapes merge automatically. In addition, on moving one merged shape, the other shape also moves. Refer to
Figure 1.10.

Figure 1.10: Merge drawing mode


■■ Object drawing mode

Through this mode, when two separate objects are drawn overlapping each other, they do not merge. Primitive
shapes, such as rectangles and ovals can be drawn through this mode. The corner radii and inner radii can also
be specified for rectangles and ovals respectively, in the Property Inspector window. In addition to the primitive
shapes, curved shapes, such as pie wedges and round off corners can be drawn using this model. Using the Object
Drawing tool from the toolbox, it is possible to draw objects in this model. When an object drawn in this model is
selected, a bounding box appears around it. Then, using a Pointer tool, this shape can be moved on the stage.
Refer to Figure 1.11.

Figure 1.11: Object drawing mode


To convert a Merge Drawing Shape to an Object Drawing Shape, select the shape on the stage, navigate to the
Modify menu, choose Combine Objects, and then, select Union from the sub-menu.

1.3.2 Drawing Basic Shapes


The toolbox or Tools panel of Flash contains a wide range of geometric vector shapes, which can be used easily. By
clicking and dragging these shapes onto the stage, different shapes can be created. The color that has been selected
is applied to the shape that is created, by default.
■■ Drawing straight lines with the Line Segment tool

Straight lines can be drawn using the Line tool from the Tools panel. The steps for drawing a straight line using the
Line tool are as follows:
¾¾ Select the Line tool from the toolbox.
¾¾ Navigate to the Window menu and select Properties. In the Properties panel, changes can be made in the
following fields:
• Thickness can be set between 0-200 pixel range using the Stroke option. Refer to Figures 1.12 and 1.13.
• Styles
• Colors
• Gradient fills
¾¾ In the Options section of the toolbox, click the Object Drawing button. Then, select Merge or Object Drawing
mode.
¾¾ Place the pointer at a place where the line has to start. Click and drag till the line ends. Press Shift and then
drag for constraining the angle of the line to multiples of 45°.

Figure 1.12: Object drawing mode


Figure 1.13: Stroke Style dialog box
■■ Drawing rectangles and ovals

Rectangles and ovals can be created using the Rectangle and Oval tools respectively. Further, strokes, fills, and
rounded corners can be applied to these shapes. These tools also provide the Primitive Object Drawing mode in
addition to Merge and Object Drawing modes.

Click here to know more about Drawing Rectangles and Ovals.


¾¾ Drawing rectangle primitives
Click and hold the Rectangle tool. From the pop-up menu, select the Rectangle Primitive tool. Then, drag the
mouse pointer across the stage to create a rectangle primitive. Select the created rectangle primitive shape
and using the controls present in Property Inspector, modify the shape and apply fill and stroke colors as per
requirements. Refer to Figure 1.14.

Figure 1.14: Properties for a rectangle primitive


Pressing the up arrow key and the down arrow key simultaneously while dragging the Rectangle Primitive tool
changes the corner radius of the rectangle primitive. Once the desired roundness of corners in the shape is
obtained, the keys can be released.

Different radii can be specified to different corners of the rectangle primitive. When the radius controls are in a
locked state, they are restrained such that all corners use the same radius. De-selecting the Lock icon in the
Rectangle Options area in the Property Inspector removes this restrain and different radii can be defined
for different corners. Refer to Figure 1.15. Click Reset in Property Inspector in order to reset the corner radii.
Click here to know more about Drawing Rectangles Primitives.

Figure 1.15: Rectangle Primitive tool


¾¾ Drawing oval primitives
Click and hold the Rectangle tool. From the pop-up menu, select the Oval Primitive tool. Then, drag the
mouse pointer across the stage to create an oval primitive. Press the Shift key and drag simultaneously for
constraining the shape to a circle.
Select the created shape using the controls present in the Property Inspector. Modify the shape and apply the
fill and stroke colors as per requirements. Refer to Figures 1.16 and 1.17.
Click here to know more about Drawing Oval Primitives.

Figure 1.16: Properties for an oval primitive


Figure 1.17: Oval primitive tool
■■ Drawing ovals and rectangles with tools

1. Select the Rectangle or the Oval tool. To do so, click and hold the Rectangle tool and drag it on the stage.

2. For the Rectangle tool, use the Round Rectangle modifier to define the corner radius values for the rectangle.
Then, drag the chosen tool on the stage.

Click here to know more about drawing ovals and rectangles.


■■ Drawing polygons and stars

1. Click and hold the Rectangle tool.

2. From the pop-up menu, select PolyStar.

3. Navigate to the Window menu, point to Properties, and select Fill and Stroke attributes.

4. As shown in Figure 1.18, provide the following settings in the Properties panel:
¾¾ Style: Select the Polygon tool or Star tool.
¾¾ Number of Sides: Enter a number between 3 to 32.
¾¾ Star Point Size: Enter a number, from 0 to 1 for specifying the depth of star points. Deep points are created
when the number is closer to 0. The settings should be retained as they are while drawing a polygon.

5. Once the settings are done, click OK. Then, drag on the stage.

Figure 1.18: Tool Settings dialog box


■■ Join and Miter settings

Join refers to the intersection point of two strokes. In the Join menu, three settings, namely, Miter, Round, and Bevel
are present. These settings are used for the creation of various styles of joins in drawings involving intersection
lines. An additional option for adjustment of angle of joins is provided by the Miter Join style. This is done by
entering a value ranging between 1 and 60 in the Miter field. Refer to Figure 1.19.

Figure 1.19: Join and Miter Settings

1.3.3 Working with Pencil and Pen Tool


■■ Pencil tool

The Pencil tool is used to create freehand drawings. The options offered by Pencil tool are as follows:
¾¾ Straighten: Approximations of lines, triangles, ovals, circles, rectangles, and squares can be snapped into well-
defined shapes through this option.
¾¾ Smooth: Curved lines can be smoothened with this option.
¾¾ Ink: Freehand lines can be drawn without any modifications using this option. Refer to Figure 1.20.
The Pencil tool is present in the toolbox. When this tool is selected, the mouse pointer changes to the shape of a
pencil. The options related to this tool are present at the bottom of the toolbox. The default mode for the Pencil tool
is Straighten.

Figure 1.20: Pencil tool

To use this tool, you can begin by drawing on the stage. Then, release the mouse. A rough preview of the line
appears as you draw. However, in the Straighten mode, the line appears different. In this mode, Flash transforms
the line into a series of straight-line segments and standard curves.
■■ Pen tool

The Pen tool in Flash works similar to that in Illustrator. It is the basic tool used for vector drawings. While using this
tool, anchor points and Bezier handles are used for the creation of lines and different shapes. Functioning of the Pen
tool is same across all applications in the Adobe suite. Anchor points can be added, deleted, or converted by using
different modes of the Pen tool. Using this tool, anchor points and vectors can also be edited and desired drawings
can be created as per requirements. Refer to Figure 1.21.
Figure 1.21: Pen tool

When the Pen tool is selected, various icons appear at the lower right of the cursor. Different functions are performed
on the line by these icons. A small x appears when the cursor is hovered over an empty area of the stage. It gives
an indication that the tool is ready to place the first point on a line. The other icons are as follows:
¾¾ Small link icon: This icon has a square with a line running through it. It gets displayed when the Pen tool is
moved over an endpoint that can be connected to close a path. Clicking this point, closes the path.
¾¾ Slash (/): This is displayed when the Pen tool is moved over an endpoint that will not connect to close a path.
Clicking this point defines it as the starting point for a continuation of the path or as the first point for closing a
path.
¾¾ Carat (^): This is displayed when the Pen tool is moved over a curve point. On clicking at this point, it is
converted into a corner point.
¾¾ Minus (-): This sign is displayed when the Pen tool is moved over a corner point. On clicking, the corner point
is deleted.
¾¾ Plus (+): This sign is displayed when the Pen tool is moved over a path. On clicking, a new point is added to
the path.
¾¾ On keeping the Ctrl key pressed, the Pen tool acts like a Subselection tool. When it is converted to a
Subselection tool, it switches to a hollow arrow icon with a filled black box over lines, or a hollow white box
over points.

On adjusting a path either with the Pen tool or the Subselection tool, the default is a filled circle; whereas, unselected
points appear as hollow squares. The unselected points display a single tangent handle that is bound toward the
selected point. The selected point displays two tangent handles.

Refer to Figure 1.22. To draw and adjust a straight-line segment with the Pen tool, begin by selecting the Pen tool.
Then, click to place the first point of your line on the stage. Select the end point for the line. Continue clicking to
create subsequent points and define individual line segments. Each subsequent click creates a corner point on the line,
indicating the length of individual line segments.

Figure 1.22: Lines created using the Pen tool

You can also draw and adjust a curved line segment using the Pen tool. To do so, click to create the first anchor point.
Then, click to define the next anchor point. Next, without releasing the mouse after defining the second anchor point,
drag the Pen tool in the direction you want the curve to appear. When the preview of the line resembles the output,
release the mouse and move to click and place the next point in the segment. Repeat this process to create subsequent
curve points for the curved segments.

To make changes to the curve, use the Subselection tool. Click and move the cursor over a handle on the line or at the
end of the line. Drag to reposition and reshape the line or curve.

1.3.4 Using the Eraser Tool


This tool is used to erase stray parts of a drawing or an object. Unlike the normal eraser, which you use on paper, the
Eraser tool in Flash can also be used to create new shapes within an object. The Eraser tool also has erase modes, as
shown in Figure 1.23. A description of the erase modes are as follows:
¾¾ Erase Normal: This mode erases fills and strokes.
¾¾ Erase Fills: This mode erases fills and the area outside the stroke but not the stroke.
¾¾ Erase Lines: This mode erases only strokes but not the fill area.
¾¾ Erase Selected Fills: This mode erases the fills but not the strokes in the selected area.
¾¾ Erase Inside: This mode erases the fill inside the stroke. It does not erase the area outside the stroke.

Figure 1.23: Eraser tool

1.3.5 Selecting Objects


Vector graphics in Flash come with a variety of selection tools that can be used to select objects either separately or as
a whole. Refer to Figure 1.24. Each selection tool is used for a different purpose. The tool to be selected depends on
the editing that has to be performed. After selecting an object, you can color it, resize it, reshape it, and also reposition
it. You can also group objects and apply changes to them at the same time.

Figure 1.24: Selection examples


■■ The Selection tool

Using the Selection tool, you can create a selection rectangle for selecting parts of an object or by dragging over a
portion of it. On defining a selection, a dotted pattern appears over it indicating the selection. The properties of the
selection, like the stroke weight and stroke style, fill color, pixel dimensions, and the X and Y coordinates appear in
the Property Inspector window.
¾¾ Drag-select: To select a line or shape, in addition to clicking it, you can also drag a marquee around the line
to select it, keeping the Selection tool active. This action is referred to as drag-select. Refer to Figure 1.24.
¾¾ Selecting multiple objects: You can add additional items to the current selection by keeping the Shift key
pressed as you drag-select. Dragging a group of elements onto the stage with the Shift key pressed, constrains
the movement range of the elements to 45 degrees. This is helpful when you want to move an object up or down
while keeping it on the same axis or baseline.
■■ The Lasso tool

Using this tool, you can select part of an object by drawing freehand over the desired area. This tool comes handy
when you have to select multiple objects or have objects placed close together. To make a selection using this tool,
click the Lasso tool on the Tools panel. Then, draw around the shapes you want to select. Complete the selection
by clicking the point where you started. Refer to Figure 1.25.

Figure 1.25: Selection made using the Lasso tool

On selecting the Lasso tool, the following options appear at the bottom of the Tools panel, to refine your selection:
¾¾ Polygon mode
¾¾ Magic Wand mode
¾¾ Magic Wand properties
Refer to Figure 1.26 and Table 1.2 for a description of each available option.

Figure 1.26: Polygon lasso tool

Lasso tool Description


options
Magic Wand Using this mode you can select values of matching pixels in a particular area with a single click.
Mode
Lasso tool Description
options
Magic Wand This option defines the controls for the Magic Wand mode. For example, using this option you can
Settings define the threshold or the smoothness of the selection.
P o l y g o n This mode is used to define the selected area with a series of straight line segments. To activate this
Mode mode, with the Lasso tool active, click the Polygon mode button to toggle to the Polygon Selection
mode. You can create selection points with a click, such that a straight selection line extends between
mouse clicks. Double-click a selection point to complete the selection. If you want to work in the
Freeform mode, the Polygon option must be in the off position. While in the Freeform mode, you
can invoke the Polygon mode by keeping the Alt key pressed and draw a straight selection line
that extends between mouse clicks. The Polygon mode will be active only as long as the Alt key is
pressed. You can return to the Freeform mode by simply releasing the mouse button.
Table 1.2: Lasso tool options and their description
■■ The Subselection tool

The Subselection tool comes with Tangent Angles and Anchor Points that
help change the shape of any object.

Selecting an object using this tool, makes the outline of the selected object
very prominent and also displays a series of nodes (green squares) on the
outline. The outline of the object, also known as paths, comprises lines and
dots that define it. Refer to Figure 1.27. You can also deselect objects in
either of the following ways:
¾¾ Pressing the Esc key
¾¾ From the Edit menu, select the Deselect All command
¾¾ Press the Ctrl+Shift+A keys
¾¾ Clicking anywhere outside the selected items

1.3.6 Arranging Objects Figure 1.27: Image selected using


the Subselection tool
The objects appear on stage in the order in which you create it. For example, if
you have created a rectangle prior to an oval, the rectangle will be stacked over the oval. You will observe this when you
move the rectangle. Inorder to re-arrange the position of the oval, you will have to change its stacking order. Remember,
only grouped objects can be stacked. For the stacking order, you can bring the selected item either to the front or send
it to the back. You can also bring the object forward or backward. Refer to Table 1.3.

Stacking Order Steps


Top of the stacking order From the Modify menu, select Arrange. From the submenu that appears,
select Bring to Front.
Bottom of the stacking order From the Modify menu, select Arrange. From the submenu that appears,
select Send to Back.
One position up on the stacking order From the Modify menu, select Arrange. From the submenu that appears,
select Bring Forward.
One position down on the stacking From the Modify menu, select Arrange. From the submenu that appears,
order select Send Backward.
Table 1.3: Stacking order

1.3.7 Reshaping Objects


In Flash, you can reshape objects using the Arrow Selection tool. This tool makes it easy to adjust curves or corners
of a shape or line without using any other selection tool or making any other selection. This technique of editing shapes
is very useful while creating shape tweens that involve a lot of movements. Using this simple drag technique, you can
also convert curved line segments into corner points with ease.

Before you can reshape an object, ensure that the object to be worked on is not selected. To reshape an object, you
can either use the Selection tool or the Subselection tool. In either case, ensure that the object is deselected before
the tool is active.

To reshape an object using the Selection tool, click the tool from the Tools panel. Then, click at the end of a shape and
drag the shape to modify it. You can pull the curve to any position. To reshape an object using the Subselection tool,
click and drag the nodes that appear around the selected object. Refer to Figure 1.28.

Figure 1.28: Objects reshaped using the Arrow Selection tool

1.3.8 Transforming Objects


In Flash, you can scale or resize graphics in a number of ways. You can transform graphic objects, group objects, and
create instances either by using the Free Transform tool or by using the Transform command from the Modify menu.
■■ The Transform tool

The Free Transform tool is available under the Selection tool in the Tools panel. Using this tool, you can resize,
rotate, squish, or stretch objects with ease. You can perform most of these tasks using this tool and it is easier to
access and use as compared to the other Transform tools. Refer to Figure 1.29.

Click here to know more about the Transform tool in Flash CS6.

Figure 1.29: Transform tools


All the transformations can be performed together using the Transformation tool. Incase if you want to scale,
rotate, or skew an object individually, you can do so by clicking the Scale and Rotate and Skew buttons
respectively from the Options area in the Tools panel.
■■ The Transform panel

Using the Transform panel, you can enter precise values to transform an object. It includes the following buttons:
¾¾ Copy and apply transform button: This button is used to duplicate the selected item that has all the
transformations. On selecting the button, a duplicate object is created that is placed exactly on top of the
original. To view both the objects separately, click and drag the duplicate to a different position on the document
window.
¾¾ Reset button: This button reverts a transformed symbol to its default settings. This can also be done by clicking
the Transform command from the Modify menu and choosing Remove Transform from the submenu.

The Transform mode and other additional effects are available in the Transform submenu that is housed in the
Modify menu.

1.3.9 Duplicating Objects


Duplicating refers to making a copy of an object without initially placing it on the system clipboard. For example, on
copying, cutting, or pasting an object a copy of the same is first placed in the clipboard. On the contrary, on duplicating
an object, a copy of the same is created without being placed on the clipboard. In addition to the shortcut keys, Ctrl+D,
you can also duplicate an object by selecting it first, and then dragging it on stage while keeping the Alt key pressed.

For detailed step-by-step procedure, refer to demo Creating and Reshaping Objects from:

eResources 4 Me>> My Varsity>> Web Animation and Interactivity>> Show Me How>> Drawing and Reshaping
Objects>> Duplicating Objects

Quick Test 1.2

1. In the object drawing mode, when two shapes are drawn overlapping each other, they merge automatically.

True False
2. I nspite of the radius controls being in the locked state, different radii can be specified to different corners of the
rectangle primitive.
True False

3. The Selection tool is used to select part of an object by drawing freehand over the desired area.
True False

1.4 Working with Layers


In Flash, layers are like transparent sheets of acetate stacked on top of each other. Layers assist you in making quick
changes by enabling you to organize your content in a document. For example, you can create and edit objects on one
layer without affecting objects on another layer.
Every document created in Flash contains at least one layer. Whatever you create gets placed in the default layer
automatically. If two shapes are placed on the same layer overlapping each other, they will merge. So it is advisable to
place each object on a different layer. Layers are very useful for animations.
The object in the bottommost layer is placed backward, while the object in the topmost layer is placed in the front. You
can also create layer folders and place layers in them, which will help you to organize and manage layers. You can add
or delete a layer, and use special guide layers and special mask layers. Refer to Figure 1.30.
Figure 1.30: Layers

1.4.1 Creating and Naming Layers


To create a layer, click the New Layer button from the Timeline. Alternatively, you can select the Timeline command
from the Insert menu. From the submenu that appears, click Layer. A new layer that is created always has a single
blank frame on which the content can be placed. By default, the new layers are named by the order in which they are
created. For example, Layer 1, Layer 2, and so on. Refer to Figure 1.31.

Figure 1.31: A newly created layer

In Flash, it is easy to rename layers in the Timeline. You can easily rename a layer by typing new labels directly on the
layer name list. To rename a layer, double-click the name of the layer. Then, type a new name in the space provided
and press the Enter key.

1.4.2 Layer Features


On the right of the layer name are icons that either explain more about the layer or allow you to manipulate the layer.
The icons that appear are as follows:
¾¾ Pencil
¾¾ Couple of circles
¾¾ Box with color in it
These icons can be used to hide or lock layers, or hide the fills within a layer.
■■ Pencil icon

On selecting a layer in the Timeline, a Pencil icon appears beside the name of the layer. This icon indicates that the
layer can be edited; in other words, you can draw or make other changes to the layer. Refer to Figure 1.32.
Figure 1.32: Layers - Pencil Icon
■■ Hide Layer button

You can hide the contents of a layer by clicking the Hide Layer button. It appears like a small dot to the right of
the Pencil icon and below the Eye icon. On selecting the Hide Layer button, the dot turns to a red x and a red line
appears through the Pencil icon indicating that the layer is hidden and cannot be edited. You can unhide the layer
by clicking the red x. Refer to Figure 1.33.

Figure 1.33: Layers - Hide icon


■■ Lock Layer button

The Lock Layer button is used to lock the selected layer. This button appears like a dot to the left of the colored box
and below the Lock icon. Clicking this button locks the layer to prevent any changes. On clicking the Lock Layer
button, the dot turns into a little lock icon and a line appears through the pencil. Locking layers is a very important
feature in Flash. It prevents accidental moving or deletion of objects on a layer. Clicking the Lock icon, unlocks the
layer. Refer to Figure 1.34.
Figure 1.34: Layers - Lock icon
■■ Outline icon

The colored box to the right of the Lock icon is used to display contents of a layer in an outline. On clicking the
colored box, the fills in the layers are displayed as outlines. This option proves useful when there are more than one
objects placed on a layer and the contents of layer underneath have to be displayed. Refer to Figure 1.35.

Figure 1.35: Outline icon


■■ Available icons

On the top of the Layers area are three icons, namely, an Eye, a Lock, and an outline of a Square. Refer to Figure
1.36. Each of these icon performs a specific function. The Eye icon hides all layers on the stage. Clicking this icon
again unhides all the layers. The Lock icon is used to lock all the layers on stage. Clicking this icon again unlocks
the layers. The Square icon is used to hide the fills of the objects on stage. Clicking this icon again redisplays the
fills.
Figure 1.36: Icons above the Layers area

1.4.3 Organizing Layers in Folders


Organizing layers includes putting them into folders, changing the order of the layers or folders, and moving layers from
one folder to another. You can organize the workflow by arranging the folders and layers in a tree structure. You can view
the layers in each folder by clicking the triangular button to expand it. A layer folder can have subfolders. The changes
made to a layer folder will affect all the layers within the folder. For example, when you lock a layer folder, all layers within
that folder gets locked. To change the order of the layers or layer folders, click and drag the layers or layer folders to the
desired position. Refer to Figure 1.37.

Figure 1.37: Layer folders

Clicking the New Folder button below the timeline, creates a new folder. Folders that are newly created are named in a
sequence. This happens by default. To rename a folder, double-click the folder name and type a new name. To remove
a layer from a folder, click the layer and drag it from within the folder to the desired location anywhere outside the folder.

1.4.4 Deleting Layers


If you no longer require a layer, it can be deleted from the timeline by clicking the Delete icon that is represented using a
Trash symbol. To delete multiple layers, select the layers while keeping the Ctrl key pressed and then, click the Delete
icon. On clicking this icon, the currently selected layer and the objects within are deleted. Refer to Figure 1.38.

Figure 1.38: Delete Layer icon

1.4.5 Layer Properties


To open the Layer Properties window, right-click the layer and then, choose Properties. You can use this window
to change the layer’s properties, such as its name, the locking option to prevent it from being edited, the layer type
and color, and the layer height. Using layer properties, you can display all objects on a layer as colored outlines. This
helps you determine the location of the object. You can also change the height of the layers in the timeline, in order to
accommodate more information (such as sound waveforms) in the timeline. Refer to Figure 1.39.

Figure 1.39: Layer Properties dialog box

For detailed step-by-step procedure, refer to demo Working with Layers from:

eResources 4 Me>> My Varsity>> Web Animation and Interactivity>> Show Me How>> Working with Layers>> Layer
Properties

1.5 Summary
In this session, Working with Flash CS6, you learned that:
¾¾ A file in Flash is referred to as a document that has the .fla extension. Flash documents are not movie files. To
publish it as a movie file, Flash documents should be saved with the .swf extension.
¾¾ Setting the document properties at the beginning of the project helps in deciding on the look and feel of the
project.
¾¾ The Flash workspace comprises various elements that can be moved on the stage.
¾¾ Panels are windows that allow you view, organize, and change related options and elements in a document.
¾¾ Grouping panels improves the organization and workflow. Using the Panel tab, you can either group or ungroup,
or dock or undock panel windows.
¾¾ It is possible to customize the manner in which you want to work in Flash by changing the general default
settings as well as the settings for ActionScript, Auto Format, Clipboard, Drawing, Text, Warnings, PSD file
Importer, and AI File Importer.
¾¾ Merge drawing and object drawing are the two modes used to create shapes. The Tools panel in Flash includes
a variety of easy to use geometric vector shapes.
¾¾ The Tools panel in Flash includes a variety of simple geometric vector shapes that are easy to use. These tools
can be clicked and dragged on the stage to create shapes.
¾¾ The intersection point of two strokes is referred to as a Join. Miter, Round, and Bevel are the three settings
available in the Join menu. These settings can be used to create different join styles on drawings or shapes that
have intersecting lines.
¾¾ The Selection tool is used to select parts of an object by dragging over a portion of it.
¾¾ Layers are like transparent sheets of acetate stacked on top of each other. Layers assist you in making quick
changes by enabling you to organize your content in a document.
¾¾ Every document created in Flash contains at least one layer. Whatever you create gets placed in the default
layer automatically.
¾¾ A new layer that is created always has a single blank frame on which the content can be placed. By default, new
layers are named by the order in which they are created.
¾¾ Organizing layers includes putting them into folders, changing the order of the layers or folders, and moving
them from one folder to the other. You can organize the workflow by arranging folders and layers in a tree
structure.

1.6 Exercise
1. It is possible to revert to the default settings in Flash using the __________ option.

Make default

Frame rate

Match

Ruler units

2. The Hide Panel command is available under the _________ menu.

Options

Window

Tools

Edit

3. Intersection of two strokes is referred to as ______________.

Symbol

Join
Miter

Snapping

4. Objects that allow users to make changes to the properties of a shape at any point in time are referred to as
____________.

Primitive objects

Timelines

Tools panel

Join and Miter settings

5. What does the pencil icon beside the layer name signify?

The layer is locked

The layer is locked; however, it can be edited

The layer can be edited

The layer is visible


S e s s io n 2
Working with Colors and Images
Learning Outcomes
In this session, you will learn to:
¾¾ Work with various coloring tools in the Flash CS6 interface
¾¾ Import images in Flash CS6

2.1 Working with Fills


Colors play an important role in any aspect of animation. It throws light on the emotions and
messages of an animation.

Users can modify the existing fills or strokes in Flash, using any of the following methods:
¾¾ By applying new attributes using either the Paint Bucket tool for fills or Ink Bottle tool
for strokes
¾¾ By selecting the fill or stroke on the stage and choosing new attributes from the appropriate
panel

In addition to the listed methods, fills or strokes that contain a gradient can be modified by using
the Gradient Transform tool.

2.1.1 Selecting Colors


There are a variety of ways in which you can select colors for your projects in Flash. On selecting
a color, it becomes the default color, until another color selection is made.
■■ Selecting colors using the Tools panel

The Tools panel comprises a Colors section that can be used to apply colors to fills and
strokes. The color section has two color buttons, namely, the Stroke color button and the Fill Figure 2.1:
color button. A color palette appears on clicking either of the buttons. In addition to the color Tools panel
showing two
palette, users can also use the Color dialog box for more color options. Refer to Figures 2.1
color buttons
and 2.2.

Figure 2.2: Color panel


Steps to select a fill or outline color from the Tools panel are as follows:
¾¾ Click the Fill color button or Stroke color button to select the fill color or stroke color respectively.
¾¾ To open the Color dialog box, click the Color Wheel at the top-right corner of the swatches.
¾¾ On the right side of the dialog box appears a tiny square with many different shades of colors. Click the desired
hue.
¾¾ A cross hair appears against your selection indicating that the swatch is selected. The selected swatch will
appear at the bottom of the dialog box.
¾¾ On the far right side of the dialog box appears a thin strip of color with a black triangle beside it. Click and drag
the black triangle to adjust the brightness of the color. Once done, click OK to load the specific color.
■■ Using the Eyedropper tool

The Eyedropper tool allows you to select colors from any object on the stage. For example, if you want to select a
color from a photograph that you have imported, the Eyedropper tool is a good option for choosing colors that can
be used on another object as a fill.

From the Tools panel, select the Eyedropper tool. The pointer changes to an eyedropper. Position the pointer over
the stroke or fill of a shape to select a color. On selecting a color, the icon changes to that of a Paint Bucket tool or
the Ink Bottle tool so that the selected color can be applied on the desired object. On clicking the Eyedropper tool
over a stroke, it changes to an Ink Bottle. On clicking the Eyedropper tool over a fill, the tool changes to a Paint
Bucket. Refer to Figure 2.3.

Figure 2.3: Tools panel showing the Eyedropper tool, Paint Bucket tool, and the Ink Bottle tool

The following buttons are available at the bottom of the Colors section of the Tools panel. These buttons can be
used to set colors.

¾¾ Black and white : This button is used to set the fill color to white and stroke color to black.

¾¾ No color : This button is used to remove the color from the selected object.

¾¾ Swap colors : This button is used to swap (exchange) the fill and stroke colors.
2.1.2 Applying Colors
Following are the various ways of applying colors in Flash:
¾¾ Using the Colors section of the Tools panel
¾¾ Using the Paint Bucket tool to apply Fill colors
¾¾ Using the Ink Bottle tool to apply Outline/Stroke colors
¾¾ Using the Properties panel to apply colors
■■ Using the Colors section of the Tools panel

The Fill Color button or Stroke Color button can be used to apply the selected fill or stroke color on the chosen
object.
■■ Using the Paint Bucket tool to apply fill colors

The Paint Bucket tool stores the fill color that has been set in the Property Inspector window or in the Tools panel.
It is used to apply a fill to objects with a closed stroke. Clicking a shape with the Paint Bucket tool, changes the fill
of the specific object. The following options are available in the Option toolbar of the Paint Bucket tool.
¾¾ Gap size - This option is primarily used to fill shapes with gaps. Choosing any of the close options fills a shape
that has gaps. Incase if gaps have to be filled manually before filling the shape, it can be done by clicking the
Don’t Close Gaps option.
¾¾ Lock fill - This option is used to lock a gradient or bitmap fill such that it appears as if the gradient extends over
the entire stage through discrete objects. Objects painted with the fill appear as masks that reveal the underlying
gradient or bitmap. To apply color using the Paint Bucket tool, begin by selecting the color from the Fill Color
button on the Tools panel. Then, click the Paint Bucket tool on the Tools panel. The pointer changes to a small
Paint Bucket. Click inside a shape on the stage. As you click, you will notice that the new fill color is applied.
■■ Using the Ink Bottle tool to apply Outline/Stroke colors

The working of the Ink Bottle tool is very similar to that of the Paint Bucket tool. The difference being, the Ink
Bottle tool is used to apply stroke colors; whereas, the Paint Bucket tool is used to apply fill colors. To use this
tool, select the desired color and then click the object whose stroke color has to be changed. You need not click the
outline, you can click anywhere on the object to change the stroke color.
■■ Using the Properties panel to apply colors

Using the Properties panel, it is possible to change the color of the outline, fill, and other properties of the object. On
selecting a color from the color palette, the selected color will reflect on the selection. It is also possible to change
the style and thickness of the outline of the selected objects. Refer to Figure 2.4.

Figure 2.4: Fill and stroke colors in the Properties panel


2.1.3 Creating Custom Colors
Each Flash document comes with its own color palette that is displayed as swatches when you access a color box or
panel. The Web-safe palette of 216 colors is by default the color palette. Using the Color panel it is possible to edit and
create new colors for strokes and fills in a variety of ways. It is also possible to alter the RGB, HSB, and Alpha values by
dragging the sliders in the color space or by entering numeric values that correspond to a specific color. In each case,
the color that is created can be saved onto the color palette for easy access.

To create custom colors, from the Window menu, open the Color panel. Select the RGB or HSB option. Set values
between 0 and 255 for the RGB option and percentage between 0 and 100 for the HSB options. Enter an Alpha value
between 0 and 100. When done, click the Options button and then click Add Swatch.

2.1.4 Creating Gradients


Gradients are multi-colored fills. They create an illusion of lighting such that objects look more realistic. Radial fills and
Linear fills are the two types of Gradient fills. The primary difference between these two types of fills is that radial fills
are applied in a circular fashion; whereas, linear fills are applied in a straight line.

In Flash, users also have the option of changing the number of colors and direction of the Gradient fill.

Overflow modes are additional features available in Flash CS6. These features provide additional controls over the
linear and radial gradients when used with the Flash player.

Like the fills, gradients can also be applied to strokes. This can be done by selecting the stroke before applying
the gradient.

■■ Applying a gradient fill

It is possible to apply gradients from the available gradient fills (presets). To apply a gradient, begin by selecting the
object and then click the Fill Color button. A palette of color swatches appear with a list of preset gradient options
at the bottom of the palette. Refer to Figure 2.5.

Figure 2.5: Gradient presets

You can add up to 15 colors to a gradient, control the location of the gradient focal point, and also apply other
parameters. A gradient works very similar to a fill or a stroke. It can be saved as a swatch using the Color panel
Options button and added to other shapes with the Paint Bucket tool.
■■ Changing gradient types

Using the Color panel, the type of gradient can be changed as shown in Figure 2.6. To do so, in the Color panel,
click the Color Type drop-down arrow. Then, as per the requirement, click Linear Gradient or Radial Gradient. You
can select the gradient display style from any of the Flow buttons. The styles available are as follows:
¾¾ Extend color
¾¾ Reflect color
¾¾ Repeat color

Figure 2.6: Difference between Linear gradient fill and Radial gradient fill
■■ Creating gradients

To create gradients, begin by selecting the fill or stroke of the desired shape on stage. Then, click the Color Type
drop-down list in the Color panel to select the fill style. After selecting the fill style, select the gradient display style.
To do so, click any of the Flow buttons. Click in the Gradient bar to create a color proxy. The color proxy is indicated
by a little box with a triangle on the top. Now, to add color to a gradient, click one of the color proxy indicators to
select it. Then, click a new color from the Color Picker box. On placing the mouse pointer above the Color Picker
box, you will observe that the mouse pointer changes to a circle. Finally, drag the color proxy indicator along the
Gradient bar to adjust the color placement.

You can remove a color proxy indicator by dragging it down.

■■ The Gradient Transform tool

The Gradient Transform tool is available under the Free Transform tool. It is used to modify the gradient applied to
an object. With the help of the tool you can move, rotate, or scale the gradient and change the position of the focal
point. Refer to Figure 2.7.

You can use the tool for gradient fills as well as bitmap fills. You will see a bounding box around the object. On the
bounding box you will observe various handles to edit the gradient. The use of the handles is explained as follows:
¾¾ Center Point: This handle appears like a four-way arrow that is used to move across the different colors of the
gradient.
¾¾ Focal Point: This handle appears with the Radial gradient. It appears like a small triangle and is used to move
the focal point of the gradient.
¾¾ Width: This handle is used to increase or decrease the width of the gradient. A square with a double-headed
arrow represents this handle.
¾¾ Size: This handle is used to increase or decrease the size of the gradient. The rollover icon for this handle is a
circle with an arrow inside it.
¾¾ Rotation: This handle is used to rotate the gradient. The rollover icon for this handle are four arrows in the
shape of a circle.
Figure 2.7: Gradient transform tool
■■ Fill Lock

As the number of shapes increases in your movie, it can become tedious to manage each object separately. On
applying gradient fills on several objects, users can choose to span a gradient across these objects. They can also
apply a separate gradient on each object. The Fill Lock feature controls the application of the fill. This feature locks
the position of the fill in relation to the position of the shapes. On applying the same gradient on multiple shapes with
the Fill Lock feature turned off, the fill is applied to each shape independently. Refer to Figure 2.8.

Figure 2.8: Fill Lock

It is also possible to lock gradients. To do so, select the objects you want to fill. Then, select a gradient. Click the Paint
Bucket tool and then, click the selected shapes. During the process, ensure that the Fill Lock is not selected.

2.2 Using the Kuler Panel


The Kuler panel is an extension to Flash. It enables grouping of colors or themes in your projects. You can access the
panel from the Extensions submenu on the Window menu.
The panel is not only used to browse thousands of color themes but also used to create colors as per your discretion by
making use of the complementary harmony rules. These customized colors can be shared with the Kuler community. It
is also possible to add new colors to the Swatches panel and use it in the projects. You can also browse for themes on
the Internet using the Browse tab in the Kuler panel. Refer to Figure 2.9.

Figure 2.9: Kuler panel


■■ Browse themes and add to the swatches panel

From the Window menu, click Extensions. From the submenu that appears, click Kuler. To browse for themes,
click the Browse tab. In the Search box, enter the name of a theme, a tag, or a creator, and then press Enter. A
browse list appears. To narrow down the list, click the pop-ups, and then select the filter options of your choice based
on the ratings. To browse the desired theme, click the View previous set of themes or View next set of themes
button. From the list that appears, select a theme in the panel.

After deciding on a theme, the next step is to add it to the Swatches panel. To add the selected theme, click the Add
Selected Theme To Swatches button.
■■ Create panel tools

There are several options available under the Create tab of the Kuler panel. Begin by clicking the Create tab and
then click the Select Rule list arrow. Then, select a harmony rule or choose Custom. On choosing the harmony
rule, you can create a theme with complimentary colors. This is because the harmony rule uses base colors as the
basis for generating the colors in the color group. On the contrary, selecting Custom creates a theme that uses
free-form adjustments.

After selecting the rule, you can manipulate colors in the color wheel. As you adjust the colors, you will observe that
the selected rule is applied to the color group. You can also adjust the color brightness by dragging the slider beside
the color wheel.

To define a base color, drag the base color marker (the double-ringed color marker that appears largest) around the
wheel. You can also set the base color by adjusting the color sliders at the bottom of the dialog box. Select any of
the four colors in the color group as the base color. Then, select the color’s swatch and click the bull’s-eye button
below the color group. Set the host application’s foreground/background color or stroke/fill color as the base color.
Then, click one of the first two buttons below the color group.

Incase if you want to remove a color, you can do so by selecting the desired color swatch and clicking the Remove
Color button. This button appears below the color group. To add a new color, select an empty color swatch and click
the Add Color button. Double-click the desired swatch to set it as the active color. Refer to Figure 2.10.
Figure 2.10: Kuler panel - Create tab
■■ Creating or editing a theme

In Flash, it is possible to create your own theme or edit an existing theme. To create a theme, click the Create tab.
The Create panel appears.

To edit a theme, click the Browse tab. Then, select the theme that you want to edit. Click Edit Theme in the Create
Panel button at the bottom of the panel. This opens the Create panel where you can edit themes.

After editing themes, you can either save the themes, or add it to the Swatches panel. Alternatively, you can also
upload it to Kuler. To save a theme, click Save Theme. Enter a name for the theme in the space provided. Then,
click Save. To add themes to the Swatches panel, click the Add This Theme to Swatches button. To upload a
theme to the Kuler panel, click the Upload Theme to Kuler button.

For detailed step-by-step procedure, refer to demo Kuler Panel from:

eResources 4 Me>> My Varsity>> Web Animation and Interactivity>> Show Me How>> Using the Kuler Panel>>
Creating or editing a theme

Quick Test 2.1


1. The Swap color option is used to swap between the black and white colors.
True False

2. The Free Transform tool is available under the Gradient Transform tool.
True False

3. The ____________ feature controls the application of the fill.

Fill Lock Snapping Punch Crop

2.3 Paint Using the Brush Tool


This tool is used to draw brush-like strokes. Once you select the Brush tool, it gives you the choice of five modifiers,
plus the option to choose the brush size and shape. The five brush tool modifiers are as follows:
¾¾ Paint Normal: Paints fills and strokes.
¾¾ Paint Fills: Paints fills and the area outside the stroke but not the stroke.
¾¾ Paint Behind: Paints behind the object on the same layer.
¾¾ Paint Selection: Paints the selected area only by replacing the original color.
¾¾ Paint Inside: Paints the fill inside the stroke. When the painting is started from an empty area, it paints only the
empty area leaving the fills.

Refer to Figure 2.11.

Figure 2.11: Brush tool modifiers

2.4 Organizing Objects


Vector objects are editable. Hence, it is best to organize them so that it is not changed unintentionally.

2.4.1 Grouping and Ungrouping Objects


In Flash, it is possible to group two or more elements in an object, or even multiple objects. Inorder to group objects,
begin by selecting the objects using the Selection tool. Then, from the Modify menu, select Group. Alternatively, you
can press Ctrl+G keys.

To ungroup objects, begin by selecting objects that have to be ungrouped. Then, from the Modify menu, click Ungroup.
Alternatively, you can press the Ctrl+Shift+G keys on the keyboard. Incase if you wish to edit objects without ungrouping
them, you can do so by double-clicking the individual objects.

On selecting an object within a group, it is highlighted with a dotted pattern; whereas, on selecting a group it
is highlighted with bounding boxes.

2.4.2 Aligning Objects


Following are the ways in which you can align objects:
¾¾ Horizontally or vertically by their edges
¾¾ Horizontally or vertically by their center
¾¾ With other objects
¾¾ With the edges of the stage

It is also possible to control the amount of space between objects.

To align objects, begin by selecting the objects. Then, from the Modify menu, click Align. Alternatively, you can press
the Ctrl+K keys. In the Align panel that appears, click an alignment option. You will observe that objects are aligned.

2.4.3 Combining Objects


To create new shapes by combining or altering existing objects, you can use the Combine Objects command from the
Modify menu. At times, the stacking order of selected objects determine how the operation works. Refer to Figure 2.12.
Figure 2.12: Result of combine options

Following are some of the options under the Combine Objects submenu:
¾¾ Union: This option combines the selected objects, converting them into a single object.
¾¾ Intersect: This option retains the common portion of the selected objects, removing the remaining part.
¾¾ Punch: One object removes the portion of the underlying overlapping object. The punching depends on the
order of the objects.
¾¾ Crop: The top object crops the portion of the underlying object.
2.4.4 Using Rulers
Rulers are used to measure the width and height of Flash elements. They also help you decide the placement of objects
on the stage by placing guides on screen.

Rulers are placed at the top and left side of the work area. You can view rulers by selecting the Ruler command from
the View menu. Alternatively, you can press the Ctrl+Alt+Shift+R keys.

The rulers can display various units of measurement like inches, millimeters, centimeters, or points. By default, the units
are measured in pixels. At any point in time, it is possible to change the unit of measurement. To do so, from the Modify
menu, click Document. Then, from the Ruler Units list arrow, select a unit of measure. Click OK.

Guides and grids are visible only in the Flash development environment. They are not exported in a Flash
movie.

2.4.5 Guides and Grids


Guides, grids, and rulers in Flash, help you lay artwork and objects with precision. Grids and guides are useful for
aligning text and graphics to interface elements. Their usage depends on the type of document you are working on.
Guides and grids are an invaluable tool. They are used for creating a well composed and proportioned layout.

The display, behavior, and characteristics of guides and grids can be altered to fit your needs.
■■ Grids

Grids are a series of crisscrossed lines that aid in aligning objects to each other on the stage.

To show or hide the grid, from the View menu, select the Grid command. Then, select Show Grid. Alternatively,
you can press the Ctrl+’ keys. To change the settings, from the View menu, select the Grid command. Then, select
Edit Grid. Alternatively, press the Ctrl+Alt+G keys. Using the Color box, you can select the color for the grid lines.
Refer to Figure 2.13.

Figure 2.13: Grid dialog box


¾¾ To show or hide the grid, select or clear the Show Grid check box.
¾¾ To show or hide the grid over objects, select or clear the Show Over Objects check box.
¾¾ To enable or disable snapping, select or clear the Snap To Grid check box. Then, enter values for horizontal and
vertical dimensions for the grid lines. Click the Snap Accuracy list arrow, and then select a level of sensitivity for
snapping to the grid. Select from Must Be Close, Normal, Can Be Distant, and Always Snap.
¾¾ To make the current grid settings the default for new Flash files, click the Save Default button.
■■ Guides

Guides are dragged from the ruler. You can drag horizontal and vertical guides from the horizontal and vertical rulers
respectively. Once you drag the guides, you can either hide or show them as per your requirement. To show or hide
the guides, from the View menu, select Guides. Then, select Show Guides. Alternatively, you can press the Ctrl+;
keys.

At any point in time, you can lock guides at a specific position. To do so, from the View menu, select Guides. Then,
click Lock Guides. Alternatively, you can press the Ctrl+Alt+; keys.

It is also possible to change the color of the guides. To do so, from the View menu, select Guides. Then, click Edit
Guides. Alternatively, you can press the Ctrl+Alt+Shift+G keys. Refer to Figure 2.14.

Figure 2.14: Guides dialog box

In the Guides dialog box, you can select a guide color from the Color list.
¾¾ To show or hide guides, select or deselect the Show Guides check box.
¾¾ To enable or disable snapping, select or deselect the Snap To Guides check box.
¾¾ To enable or disable the movement of guides, select or deselect the Lock Guides check box.
¾¾ To define a level of sensitivity for the guides, click the Snap Accuracy list arrow. You can select from Must Be
Close, Normal, and Can Be Distant.
¾¾ Selecting Clear All removes all the guides from the scene.
¾¾ Clicking Save Default sets the current guides as the default guides.
2.4.6 Snapping
Snapping is a feature that guides the movements of the objects on stage. It helps in aligning elements accurately and
in relation with each other. The snapping controls can be turned on or off from the Snapping submenu from the View
menu or from the Edit Snapping dialog box. To access the Edit Snapping dialog box, from the View menu choose
Snapping. Then, choose Edit Snapping.

The snapping settings can be controlled in the Edit Snapping dialog box, either in the Basic view or in the Advanced
view. The Basic view, displays only the top five check boxes; whereas, the Advanced view, expands the dialog box to
include additional snap align settings, as depicted in Figure 2.15.

Figure 2.15: Edit Snapping dialog box

Description of the options available in the Edit Snapping dialog box are as follows:
¾¾ Snap align settings: It is possible to enter a value for the distance an object that has to be before it snaps to
boundaries of the stage movie (in pixels).
¾¾ Object spacing: You can enter a value for the horizontal and vertical edge tolerance (in pixels).
¾¾ Center alignment: You can align the objects, either by using the Horizontal center alignment or Vertical center
alignment.
¾¾ Save Default: This option makes the snap align setting as default for future use.
The available snapping modes are as follows:
¾¾ Snap Align
¾¾ Snap to Objects
¾¾ Snap to Grid
¾¾ Snap to Guides
¾¾ Snap to Pixels
Refer to Figure 2.16.

Click here to know more about snapping modes.

2.5 Getting Images in Flash


Copying images from another source and pasting them in
Flash can lead to various image related issues, like layers
being flattened or loss of information on transparency and
gradients. The best way to avoid such issues is by importing
images in Flash using the various import options that are
available. Importing images also gives accurate results.

2.5.1 Importing Bitmaps


Bitmaps of several file types can be imported into Flash and Figure 2.16: Snap to Objects
can be used in your Flash movie. Although you can edit and resize bitmaps in Flash, the original bitmap will always be
embedded in the exported Flash file.

A large file size can be an issue; hence, it is best to reduce the size of your bitmap file before you can import it in Flash.
For example, if the size of the image in your final movie is defined as 160 x 160 pixels, then it is best to resize the image
to the desired size and then import it in Flash. This will help in deriving at higher quality images with smaller files.

Following are the two methods in which you can import files in Flash:
¾¾ Import to stage: In this method, the bitmap is stored in the Library and a copy of the same is placed on the
stage.
¾¾ Import to library: In this method, the bitmap is stored in the Library.
To import a bitmap on stage, from the File menu, select Import. From the submenu that appears, click Import to Stage.
In the dialog box that appears, select the desired file from the respective folder. Then, click Import. Refer to Figure 2.17.

Figure 2.17: Importing bitmap

2.5.2 Updating Imported Bitmaps


You can modify the already imported files in Flash, without re-importing them. On updating an imported file, the existing
contents are replaced with the modified contents of the external file.

When you edit a bitmap in its native program and re-save or update it to the hard drive, Flash automatically updates
the bitmap. You can also update an image automatically, if the location of the image has been changed. In addition to
replacing or updating the changes, you can also import another image to replace the bitmap in the Library.

Using the Bitmap Properties dialog box, you can manually update or replace an image. To access this dialog box,
from the Library panel, right-click the bitmap that you want to update or replace and then click Properties. The Bitmap
Properties dialog appears as shown in
Figure 2.18.

Using this dialog box, you can manually


update the bitmaps or import it using the
Update and Import buttons respectively.
In addition to this, you can anti-alias the
edges of the imported bitmap by selecting
the Allow Smoothing check box. You can
also select the appropriate compression
options to reduce the bitmap file size and
the file format. For example, selecting the
JPEG option, reduces the file size and is
best suited for photographs.

For detailed step-by-step procedure, refer to Figure 2.18: Bitmap Properties dialog box
demo Importing Bitmap from:

eResources 4 Me>> My Varsity>> Web Animation and Interactivity>> Show Me How>> Getting Images in Flash>>
Updating Imported Bitmaps

2.5.3 Retaining Layers of Photoshop Files


When importing Photoshop files, you can choose options for each layer or even choose not to import the layer. When
importing a text layer, you can import it as editable text, vector outlines, or a bitmap image. You can choose to import
a bitmap as a flattened layer or as a bitmap image with editable layer styles. In both cases, whether importing a text or
bitmap layer, a simple check box click will convert the imported layer to a movie clip that you can name right there in the
import dialog box. When importing PSD files, you can select the option to set the stage to the same dimensions as the
file being imported, and to place the imported layers at their original positions. You can also choose to merge the layers
before importing. Refer to Figure 2.19.

Figure 2.19: Retaining layers in a Photoshop file

Click here to know more about retaining layers of Photoshop files.


■■ Photoshop import preferences

The default preferences of the PSD file that is imported can be modified. To do so, from the Edit menu, select
Preferences. In the Preferences panel that appears, select the PSD File Importer on the left side. The associated
options appear on the right side. Refer to Figure 2.20.

Figure 2.20: Photoshop preferences

2.5.4 Importing Illustrator Artwork


Flash CS6 makes it very easy to import Illustrator files. Flash now has the ability to import AI layers, sublayers, and
unused objects. It imports them on their own layers, in their own movie clips, and as flattened bitmaps. Refer to Figure
2.21.

Figure 2.21: Illustrator artwork

On importing an Illustrator artwork as an AI, EPS, or PDF file, Flash preserves the same attributes as for the Illustrator
artwork. In addition, if Illustrator files contain layers, they can be imported using any of the following ways:
¾¾ Convert Illustrator layers to Flash layers
¾¾ Convert Illustrator layers to Flash frames
¾¾ Convert all Illustrator layers to a single Flash layer
Illustrator and Flash support pasted artwork in either of the following ways:
¾¾ On selecting all the top-level layers in the Illustrator artwork and pasting them into Flash, the layer properties
are preserved.
¾¾ Non-RGB Illustrator colors (CMYK, grayscale, and custom) convert to RGB in Flash. RGB colors paste as
expected.
¾¾ When you import or paste Illustrator artwork, you can use various options to preserve effects (such as drop
shadow on text) as Flash filters.
¾¾ Flash preserves Illustrator masks.

Quick Test 2.2


1. The _____________ brush tool modifier paints behind the object on the same layer.

Paint Normal Paint Behind Paint Fills Paint Selection


2. It is not possible to align objects with the edges of the stage.
True False

3. On importing an AI file in Illustrator, it is not possible to change its default preferences.

True False

The Library panel arranges the contents of the imported AI file in an alphabetical order. This happens
automatically without affecting the hierarchical grouping and folder structure.

■■ Illustrator import preferences

You can change the default preferences of an AI file. To do so, from the Edit menu, select Preferences. Then, select
AI File Importer located on the left side. The associated options appear on the right side. Refer to Figure 2.22.

Figure 2.22: Illustrator preferences

For a detailed step-by-step procedure, refer to demo Importing Illustrator Artwork from:

eResources 4 Me>> My Varsity>> Web Animation and Interactivity>> Show Me How>> Getting Images in Flash>>
Importing Illustrator Artwork
2.5.5 Tracing Bitmap
The Trace Bitmap command converts a bitmap into a vector graphic with editable, discrete areas of color. You manipulate
the image as a vector graphic. This helps in reducing the file size. When you convert a bitmap to a vector graphic, the
vector graphic is no longer linked to the bitmap symbol in the Library panel. If the imported bitmap contains complex
shapes and many colors, the converted vector graphic might have a larger file size than the original bitmap. To find a
balance between the file size and image quality, try a variety of settings in the Trace Bitmap dialog box. Refer to Figure
2.23.

Figure 2.23: Trace Bitmap dialog box

The options available in the dialog box are as follows:


¾¾ Color threshold: The number of colors converted from the bitmap depends on the color threshold value you
enter. A high threshold value decreases the number of converted colors.
¾¾ Minimum area: This option determines the number of pixels in the surrounding area to be considered while
assigning a color.
¾¾ Curve fit: This option determines the smoothness of the outline.
¾¾ Corner threshold: This option checks whether to keep sharp or smooth edges.

2.6 Summary
In this session, Working with Colors and Images, you learned that:
¾¾ Colors help in bringing out the important aspects of an animation.
¾¾ Colors can be selected either by using the Tools panel or by using the Eyedropper tool.
¾¾ Colors can be applied either by using the Colors section of the Tools panel or by using the Paint Bucket tool.
They can also be applied using the Ink Bottle or the Properties panel.
¾¾ Gradients are multicolored fills that help create an illusion of lighting, in turn making your objects look more
realistic.
¾¾ Radial and linear are the two types of gradients. It is also possible to customize gradients in Flash.
¾¾ The Kuler panel is an extension to Flash with a lot of additional features that proves handy while creating colors
and themes that match your requirements.
¾¾ Organizing objects save the file from unintentional changes.
¾¾ Rulers help you measure the width and height of Flash elements. Guides and grids help in aligning the elements.
¾¾ While importing images, it is possible to retain the layers of Photoshop files. The images can be imported either
as a flattened layer or with editable layer styles.
2.7 Exercise
1. Radial fills are applied in a straight line; whereas linear fills are applied in a circular fashion.

True

False

2. A cross hair appears against your selection indicating that the ___________.

The color swatch is selected

The color swatch is deleted

The color swatch is hidden

The color swatch is locked

3. _________________ specify how colors are applied beyond the gradient.

Fill command

Overflow modes

Gradient panel

None of the above

4. It is possible to rotate a gradient when the rollover icon changes to __________.

Four-way arrow

Double-ended arrow

A circle with an arrow within

Four arrows in the shape of a circle

5. On importing Illustrator files in Flash, the masks associated with the imported files are preserved.

True

False
S e s s io n 3
Working with Text
Learning Outcomes
In this session, you will learn to:
¾¾ Work with different types of text in Flash

3.1 Overview
Following two types of text can be created in Flash:
¾¾ Classic: This text format provides standard capabilities that are available in the previous versions of Flash.
¾¾ Text Layout Framework (TLF): This text format comes with advanced text capabilities that can be used in
Flash Player 10 and ActionScript 3.0 or later.

3.1.1 Creating Classic Text


Three types of classic text available in Flash are as follows:
¾¾ Static: In this type, text does not change, it remains as is.
¾¾ Dynamic: In this type, the text is continuously updated. Stock quotes and weather updates are examples of this
type of text.
¾¾ Input: This text refers to text entered by users in forms or surveys.
On clicking anywhere on the stage with the Text tool selected, a text box is created. Text entered here appears in a single
line, unless the Enter key is pressed. Using the Text tool, you can also create a text box with predefined dimensions and
formatting. On entering text in the text box, it wraps automatically in relation to the boundaries of the box and also on the
formatting that have been applied. You can edit text within the text box by double-clicking it.

To create classic static text, from the Tools panel, select the Text tool. In the Properties panel, select Classic Text from
the Text Engine drop-down list. From the Text Type drop-down list, select any one type of classic text, namely Static,
Dynamic, or Input. Then, click on the stage to create a text box. You can either click on stage to create a single line text
box or drag the cursor on stage to create a text box of the desired dimension. You can now enter text in the defined text
box. Refer to Figure 3.1.

Figure 3.1: Creating static text

It is possible to create horizontal text with a left-to-right flow or static vertical text with either a right-to-left or left-to-right
flow.

When creating classic text, users can place text on a single line that expands as you type, or in a fixed-width field (for
horizontal text), or fixed-height field (for vertical text) that expands and wraps words automatically. All classic text fields
support Unicode.
Click here to know more about creating Classic text.

3.1.2 Creating TLF Text


TLF text comes with advanced text capabilities in Flash documents. These features are targeted for Flash Player 10
and ActionScript 3.0 or later. Using TLF text, you can create columns, rotate text, indent text, and change text direction
and orientation. You can also change text case, adjust the text baseline, and apply text blending and color effects in the
Property Inspector.

To create TLF text, click the Text tool from the Tools panel. From the Properties panel, click the Text Engine drop-
down list and select TLF Text. Then, select the type of text from the Text Type drop-down list. Read only, Selectable,
or Editable are the three types of TLF text available for use. Click on the stage to create a text box and begin entering
text. Refer to Figure 3.2.

Figure 3.2: Creating TLF text

On selecting the TLF text box, a black bounding box with square handles appears around it. You can resize the text box
by clicking and dragging the handles to the desired shape. On resizing the text box, you will observe that the text within
the box wraps to accommodate itself to its new size.

Click here to know more about TLF text.

3.1.3 Converting between Classic and TLF Text


On converting a text object from one text engine to the other, most of the formatting is preserved by Flash. However,
there are possibilities that the formatting may differ. This is because text engines are different in their capabilities. Hence
while converting text, it is necessary to inspect text carefully and reapply the changed or lost settings.

While converting text from Classic to TLF or vice versa, avoid converting it back and forth more than once. This
will lead to less discrepancies in the settings.

While converting between TLF and Classic text, Flash converts text types as follows:
¾¾ TLF Read Only is converted to Classic Static
¾¾ TLF Selectable is converted to Classic Static
¾¾ TLF Editable is converted to Classic Input

3.2 Formatting Text


Flash includes a number of text properties that help modify the type, style, size, and color of the text. You can set these
properties either before you create a text box or after you enter text in a text box. To make changes to the entire text in a
text box, select the text box with the Selection tool to make it active. In order to change only a portion of the text, select
the text to be changed and apply the desired properties from the Property Inspector. The Property Inspector displays
all the available attributes when the text box or the Text tool is selected.

3.2.1 Changing Character Attributes


Character styles are attributes that apply to a single character or a set of characters. Font type, style, size, and color are
some of the character attributes. Refer to Figure 3.3 to view the different character attributes for the Classic and TLF
text.

Figure 3.3: Character attributes for Classic and TLF text


¾¾ Family: This option lets you select the font.
¾¾ Style: This option defines the font style. You can choose from Regular, Italic, Bold, or Bold Italic.
¾¾ Size: This option helps you define the size.
¾¾ Letter Spacing (Classic Text Only): This option
lets you control the space between characters.
Refer to Figure 3.4.
¾¾ Leading (TLF text only): This option lets you
control the space between the lines. Refer to
Figure 3.5. Figure 3.4: Letter spacing

¾¾ Color: This option lets you set a color for the text by
clicking the Color box.
¾¾ Tracking (TLF text only): This option lets you set the
space between characters and words on a single line.
Changes made using this option affect the entire line.
¾¾ Auto Kern: This option applies kerning information to the
built-in fonts of Latin characters. For Asian characters,
this option can be applied to characters that have kerning Figure 3.5: Leading
information built into them.
¾¾ Highlight (TLF text only): This option lets you highlight text.
¾¾ Anti-Alias: This option adjusts the pixels at the edge of a shape by helping them blend with the background.
This feature makes text appear smoother and integrated. Flash includes Flash Type, a text rendering feature
that improves anti-aliasing and readability of fonts. This feature is enabled whenever Flash Player7 or higher is
the selected player and anti-aliasing is set to custom or readability. Refer to Figure 3.6.
Figure 3.6: Anti-alias

The available anti-alias options are as follows:


¾¾ Use Device Fonts: Specifies that the SWF file uses the fonts installed on the local computer to display the
fonts. Typically, device fonts are legible at most font sizes. This option does not increase the size of the SWF file.
However, it forces you to rely on the fonts installed on the user’s computer for font display. When using device
fonts, choose only commonly installed font families.
¾¾ Readability: Allows for improved legibility of fonts, particularly at small sizes. To use this option for a given text
block, embed the font used by the text object. (Do not use this option if you intend to animate text; instead, use
the Animation mode.)
¾¾ Animation: Creates a smoother animation by ignoring alignment and kerning information. To use this option
for a given text block, embed the font used by the text block. For legibility, use 10-point or larger type when
specifying this option.

Rotation (TLF Text Only): This option helps rotate individual characters. The following values are available for rotation:
¾¾ 0o: This value forces all characters to have no rotation.
¾¾ 270o: This value is available only for Roman text and Vertical orientation.
¾¾ Auto: This value specifies a 90 degrees counter clockwise rotation for full width and wide characters only.
¾¾ Superscript: Reduces the size of the characters and moves it slightly above the normal line of type.
¾¾ Subscript: Reduces the size of the characters and moves it slightly below the normal line of type.
¾¾ Underline (TLF Text only): Places a horizontal line below the characters.
¾¾ Strikethrough (TLF Text only): Places a horizontal line through the center of the characters.
¾¾ Selectable (Classic text only): This option enables selection of static text, either horizontal or dynamic, by
viewers using the application.
¾¾ Render Text as HTML (Classic text
only): This option preserves rich text
formatting that includes fonts and
hyperlinks.
¾¾ Show border around text (Classic
text only): On selecting this option a
black border and a white background
appears around the text field.

3.2.2 Working with Paragraph


Styles
Using Flash, it is possible to change the
various paragraph attributes that include
alignments, margins, indents, and spacings.
Refer to Figure 3.7. Figure 3.7: Paragraph attributes
You can align TLF text and format classic text. The following attributes align the position of the text in a Text box:
¾¾ Align left (Classic text): Aligns text to the left margin
¾¾ Align center: Aligns text to the center of the text box.
¾¾ Align right: Aligns text to the right of the text box.
¾¾ Justify: Aligns each line of text to the width of the text box boundary, except the last line, which is aligned to
the left.
¾¾ Justify center (TLF): Justifies text with the last line aligned to the center.
¾¾ Justify right (TLF): Justifies with the last line aligned to the right.
¾¾ Justify all (TLF): Justifies all the lines.
¾¾ Text Justify (TLF): Distributes justification between letters or words. To justify text, click the Text Justify list
arrow and then click Word Spacing or Letter Spacing.
¾¾ Letter Spacing: Distributes spaces between letters.
¾¾ Word Spacing: This is the default setting that distributes spaces between words.
¾¾ Behavior (Classic text only): Specifies the line type as single, multiline, or multiline no wrap.
3.2.3 Linking Text
Many a times a tiny red plus sign in a square appears at the bottom of the text box. This plus sign is referred to as the
Overload icon. This icon indicates that there is excess text within the text box. You not only can accommodate text by
clicking the icon and dragging it to the desired shape but also create a thread link to link this text box to another existing
text box.

Although the text boxes are linked, each text box retains its own properties. You can unthread a text box at any point in
time.

To link text, create a TLF text box and begin typing in the box that appears. Alternatively, you can paste text from the
Clipboard until it fills the entire text box. Click the Overflow icon on the selected text box. The pointer changes to the
Loaded Text cursor. To create a new text box for the overflow text, click a blank area or drag to create a text box. You
will notice that the overflow text from the first text box threads to the second text box. Refer to Figure 3.8.

Figure 3.8: Linking text

You can unlink text by double-clicking the In-port or the Out-port icon. Alternatively, you can delete either of the text
boxes. On deleting the text, you will observe that the text in the deleted text box is moved back to the remaining text
box thread.
Quick Test 3.1
1. Classic, Static, and Dynamic are the three text types available in Flash.

True False
2. The anti-alias option applies kerning information to built-in fonts of Latin characters.

True False
3. The Overload icon resembles appears as a red minus sign at the bottom of the text box.

True False

3.3 Creating Text Columns


Using the TLF text box, you can create columns similar to the ones seen in newspapers using the Property panel of the
TLF text box. Using the Container and Flow sections in the panel, users can:
¾¾ Specify the number of columns
¾¾ Specify the gutter size between the columns
¾¾ Specify the padding size between the text and border edge
¾¾ Specify the maximum number of characters
¾¾ Specify the alignment of the text
¾¾ Specify the border and fill colors

Refer to Figure 3.9.

Figure 3.9: Columns

3.3.1 Working with Container and Flow Properties


The Container and Flow sections of the TLF Text Property Inspector have the following options:
■■ Behavior

This option defines the behavior of the text box in response to the exceeding text within a text box. Single line,
Multiline, Multiline no wrap, and Password are the options available in the Behavior option. On choosing the
Password option, characters appear as dots instead of letters. This is for security sake. Moreover, this option is
available only for editable text; it does not work with Read Only or Selectable type of text.
■■ Max Chars

Defines the maximum number of characters in a text box.


■■ Alignment

Specifies the alignment of text within a text box. Alignment settings include:
¾¾ Align top: Aligns text down from the top of the container.
¾¾ Align center: Aligns text to the center of the container.
¾¾ Align bottom: Vertically aligns lines of text up from the bottom of the container.
¾¾ Justify: Evenly distributes lines of text vertically between the top and bottom of the container.
¾¾ Column Count: Defines the number of columns of text that can be placed within area text containers. The
default value for this setting is 1 and the maximum value that can be set is 50.
¾¾ Column Gutters: Specifies the gutter or spacing between each column in the selected container. Here, the
default value is 20 and the maximum value is 1000.
¾¾ Padding: Specifies the width of all the four margins of the container.
¾¾ Border Color: Defines the stroke color of the sides of the container. By default, the stroke is defined as no
border.
¾¾ Border Width: Specifies the width of the stroke applied to the sides of the container. This is enabled only when
a border color is chosen. The maximum value of the width is 200.
¾¾ Background Color: Specifies the color of the background behind the text. By default, no color is applied to the
background.
¾¾ 1st Line Offset: Specifies the alignment of the first line of text with the top of the text container. For example,
you can define the placement of the first line of text in relation to the top of the container. The 1st Line Offset
has the following options:

●● pt: Specifies the distance in points between the baseline of the first line of text and the top inset of the frame.
It enables a field for specifying the point distance.

●● Auto: Aligns the top of the line, based on the tallest glyph, with the top of the container.

●● Ascent: The distance between the top inset of the text container and the baseline of the first line of text is
the height of the tallest glyph in the font (typically the “d” character in Roman fonts).

●● Line Height: Line height or leading is the distance between the top inset of the text container and the
baseline of the first line of text.

●● Direction: Specifies the direction of text within a container, left-to-right or right-to-left. On applying this
option at the paragraph level, direction controls the left-to-right or right-to-left text; indents and punctuations
are used by the paragraph. On applying this option at the container level, it controls the column direction.

●● Locale: Sets the Locale property at the flow level. The Direction and Locale options are available when the
Show Right-to-Left option is selected from the Options menu of the Properties panel.

Refer to Figure 3.10.

Figure 3.10: Properties Option menu


The left-to-right direction of text is used for most languages; whereas, the right-to-left direction is used in
languages based on Arabic script like Farsi, Hebrew, or Urdu.

3.3.2 Flowing Text across Multiple Containers


Threading, also referred to as linking, is a feature specific to TLF. Text containers can be linked between frames. The
symbols within these containers can also be linked, provided the linked containers are within the same timeline.

To link containers:

1. Begin by selecting the Selection tool or the Text tool.

2. Click the In port or the Out port of the selected text container. The pointer changes to a loaded text icon indicating
that the containers can be linked.

3. To link to an existing text container, click the target text container to link it.

4. To link to a new text container, click on the stage. A new container with same size and shape of the original container
is created. The containers are now linked and text can flow between them.

5. Alternatively, to create a container with different dimensions, drag the mouse cursor on the stage. It is also possible
to add a new container between two linked containers.

To unlink containers:

1. Place the container in the Edit mode.

2. Double-click the In-port or Out-port that has to be unlinked. The text reflows in the first of the two containers.

3. Delete one of the linked text containers.

The In-port and Out-port positions on the text container depends on the direction of the flow of the container.
It also depends on the vertical or horizontal settings of the container. For example, the In port is on the upper
left and the Out port is on the lower right if the text flow is Left-to-Right and horizontal. On the contrary, the In
port is on the upper left and the Out port is on the lower right.

On linking two text containers, the second text container acquires the direction of flow and locale of the first
container. Inspite of unlinking, these settings exist in the second container.

3.3.3 Making Text Scrollable


Adding a UIScrollBar component to the text container makes the container scrollable. In addition, the text container
should have the following settings:
¾¾ Text type should be set to Editable or Selectable.
¾¾ The Container and Flow Behavior must be set to Multiline or Multiline No Wrap.
To make a TLF text container scrollable, drag an instance of the UIScrollBar component from the Components panel
onto the text container, closest to the side of the container where you want to attach it. The UIScrollBar component
snaps to the side of the text container.

Perform the following steps to make a text container scroll horizontally:

1. Select the UIScrollBar component instance on the stage.

2. Set the Direction of the UIScrollBar component to Horizontal in the Component Parameters section of the Property
Inspector.

3. Drag the UIScrollBar component instance to the top or bottom of the text container.

The UIScrollBar component snaps to the top or bottom of the text container.
3.4 Changing Advanced Character Options
Advanced options for TLF text are available in the Properties panel. You can change the case of the text, specify a
baseline for multi-language text or baseline shift (such as superscript or subscript), apply line breaks, and select the
users’ language and region. Similar to a feature in Adobe Photoshop, you can apply blending modes and color effects
to a text box in front of another element, such as a graphic, to create a new look from the mix of color pixels. Refer to
Table 3.1 to view the options available in the Advanced Character section of the Properties panel.

Options Description
Link This option is used to create a text hyperlink.
Target This is used with the Link option to specify the window
into which the URL loads into. The following values are
associated with this option:
¾¾ Self: Specifies the current frame in the current
window.
¾¾ Blank: Specifies a new window.
¾¾ Parent: Specifies the parent of the current frame.
¾¾ Top: Specifies the top-level frame in the current
window.
¾¾ Custom: Specifies a value for the browser
window or frame that will be open when the SWF
file is playing.
Case Used to change the case of the text - uppercase or
lowercase.
Digit Case Adopts the settings specified by the font designer.
Digit Width Alters the text to proportional or tabular widths.
Dominant Baseline Alters the multi-language text to a common baseline.
Alignment Baseline Alters the baseline alignment for multiple language text.
Ligatures Alters the running together of letters. For example, Th.
Break Defines the use of line breaks.
Baseline Shift Specifies the shift in baseline in points or percentages.
Superscript or Subscript can be chosen for standard shifts.
Locale Defines the language and region of the user.
Table 3.1: Options available in the Advanced Character section of the Properties panel

3.4.1 Changing Text Orientation


You can change the orientation of text to display it in the
format that it is supposed to appear. This can be done by
using the Orientation option in the Properties panel for TLF
text. If you need the text to rotate and follow the orientation
of the line, you can set it to rotate automatically. To change
the orientation of the text, click the Orientation button, and
then click Horizontal or Vertical as the case may be. Refer
to Figure 3.11.

While working with Asian text, you can use the Advanced
Paragraph section to select options for Mojikumi, Kinsoku
Shori Type, and Leading model. Refer to Figure 3.12.

Figure 3.11: Changing text orientation


Figure 3.12: Advanced paragraph options
¾¾ Mojikumi
This option determines how paragraph justification is applied. It is also referred to as the justification rule. The
following values are available in this model:

●● Auto: Justification is applied based on the locale selected in the Character and Flow section of the Text
Property inspector. This is the default setting.

●● Space: This option uses the Roman justification rules.

●● East Asian: This option uses the East Asian justification rules.
¾¾ Kinsoku Shori type
This model is used to specify values for handling Japanese kinsoku characters that appears in the middle of a
line and not at the beginning or end of a line. The following values are available in the Kinsoku Shori type:

●● Auto: This is the default setting and can be resolved based on the locale selected in the container and flow
section of the Text Property inspector.

●● Prioritize Least Adjustment: Bases justification on either expanding or compressing the line, whichever
gives a result closest to the desired width.

●● Push In Kinsoku: Bases justification on compressing kinsoku at the end of the line. Kinsoku expands if no
kinsoku occurs or if that end-of-line space is insufficient.

●● Push Out Only: Bases justification on expanding the line.


¾¾ Leading Model
A paragraph model comprising a combination of Leading Basis and Leading Direction. Leading Basis determines
the baselines of two consecutive lines that are intended to be at a specific distance from each other. This
distance is determined by the line height. Leading Direction determines the direction in which line height is
measured. The following values are available in the Leading model:

●● Roman Up

●● Ideographic Top Up

●● Ideographic Center Up

●● Ideographic Top Down


●● Ideographic Center Down

●● Auto

Click here to know more about the values available in the Leading Model.

In addition to the mentioned points, you can change the orientation of Classic text to display it horizontally, vertically, or
horizontally left-to-right as shown in Figure 3.13.

Figure 3.13: Classic text orientation

Another way of orienting text is by using the Rotate button in the Character section of the Properties panel. This button
can be used to rotate text inside vertical text boxes. Refer to Figure 3.14.

Figure 3.14: Classic text orientation

For detailed step-by-step procedure, refer to demo Text Orientation Classic from:

eResources 4 Me>> My Varsity>> Module Name>> Show Me How>> Changing Advanced Character Options>>
Changing Text Orientation

3.4.2 Using Break Apart


When a line of text is created in Flash, it appears in a bounding box that can be edited. At times, you may have to adjust
the characters individually or modify the shape of the characters themselves to create new character styles. All this and
more can be done by selecting the Break Apart command from the Modify menu. You can apply breaks to text at two
levels. At the first break, the text box separates into singular, editable characters. This is useful if you want to reposition
or align the letters of a word independently. At the second break, the test is separated from its font reference. In other
words, it becomes a shape that can be edited with any of the drawing tools or pen modifiers. Refer to Figure 3.15.
Figure 3.15: Break apart

eResources 4 Me>> My Varsity>> Module Name>> Show Me How>> Changing Advanced Character Options>> Using
Break Apart

Quick Test 3.2


1. Text containers can be linked only in Classic text boxes.

True False
2. The Break Apart command is available under the Modify menu.

True False

3.5 Multilanguage Text


You can configure a FLA file to display text in different languages depending on the language of the operating system
that plays the Flash Professional content.

3.5.1 Workflow for Authoring Multilanguage Text with the Strings Panel
Using the Strings panel, users can create and update multilingual content and specify content for text fields that span
multiple languages. It is also possible to have Flash Professional automatically determine the content that should
appear in a certain language based on the language of the computer running Flash Player.

The following steps describe the general workflow:

1. Any text to enter in another language must be in a dynamic or input text field.

2. A column for the language is added to the Strings panel. When you save, test, or publish the application, a folder
with an XML file is created for each language.

3. In the Strings panel, encode each text string with an ID.

4. A folder is created for each language you select, and within each language folder is an XML file for that language.

5. Author in your native language and let the translators make the translation. They can use translation software
directly in the XML files or in the FLA file.

6. When you receive the translations from your translators, import the translated XML files back into the FLA file.

3.5.2 Select and Remove Languages for Translation


For translation purposes, upto 100 languages can appear on the stage and in the Strings panel. Each selected language
becomes a column in the Strings panel. To display text on the stage in any of the chosen languages, users have to
change the stage language. The selected language appears on publishing or testing the file.

It is best to select languages that are available in the menu or from any other Unicode-supported language.

Perform the following steps for selecting a language:

1. From the Window menu, click Other Panels. From the submenu that appears, click Strings and then click Settings.

2. In the Languages box, select the desired language and then click Add. Incase if the languages are not displayed
in the Languages box, type a language code in the format, xx and click Add. The language code is from ISO 639-1.

3. Repeat the steps to add all the necessary languages.

4. Select a default language from the default runtime language menu. This language appears on systems that do not
have one of the active languages you selected.

5. T
o load an XML file for the languages from a different URL at runtime, type the URL in the URL text field and click
OK. A column for each selected language appears in the Strings panel. The columns appear in alphabetical order.

6. S
ave the FLA file. Notice that a folder for each chosen language has been created in the same folder indicated in the
SWF publish path. If no SWF publish path has been selected, it is created in the folder where the FLA file resides.
Within each language file an XML file is created that is used to load translated text.

Steps to remove a language are as follows:

1. From the Window menu, select Other Panels, and then click Strings. From the sub menu that appears, click
Settings.

2. From the Active Languages field, select the language to be removed and click Remove.

3. Repeat the steps to remove the unwanted languages. Once done, click OK. Notice, the column for each removed
language no longer appears in the Strings panel.

When you remove a language from the Strings panel, the language XML file is not deleted from the local file
system. This lets you add the language back into the Strings panel by using the previous XML file, and prevents
accidental deletion. To completely remove the language, you must delete or replace the language XML file.

3.5.3 Add Strings to the Strings Panel


Text strings can be assigned to the Strings panel in any of the following ways:
¾¾ By assigning a string ID to a dynamic or input text field
¾¾ By adding a string to the Strings panel without assigning it to a text field
¾¾ By assigning an existing string ID to an existing dynamic or input text field
Steps to assign a string ID to a text field are as follows:

1. From the Window menu, click Other Panels, and then click Strings.

2. Click the Text tool to select it. Create an input or dynamic text field.

3. Keeping the Text tool selected, type a unique ID in the ID field of the Strings panel.

4. Click the Settings button and select a language or languages from the list in the Settings dialog box. The selected
languages should include the default language in which you plan to publish your work.

5. Click Apply.

If a static text field is selected on the Stage, the Stage text selection section on the Strings panel displays the
message “Static text cannot have an ID associated with it.” If a non-text item is selected or multiple items are
selected, the message “Current selection cannot have an ID associated with it” appears.
Steps to add a string ID to a Strings panel without assigning it to a text field are as follows:

1. From the Window menu, click Other Panels, and then click Strings.

2. Click the Settings button and select a language or languages from the list in the Settings dialog box. The selected
languages should include the default language in which you plan to publish your work.

3. Type a new string ID in the Strings panel and click Apply.

Steps to assign an existing ID to a text field.

1. Select the Text tool and create an input or dynamic text field.

2. Type the name of an existing ID in the ID section of the Strings panel. Then click Apply.

Press Shift+Enter to apply the ID to the text field, or Enter if the focus is on the ID field.

3.5.4 Editing Strings in the Strings Panel


After entering text strings in the Strings panel, use one of the following methods to edit the text strings:
¾¾ Directly in the Strings panel cells.
¾¾ Use features such as find and replace on the stage in the selected stage language. Changes applied to the text
using these features is applied on the stage and in the Strings panel.
¾¾ Edit the XML file directly.
3.5.5 Change the Language Displayed on the Stage
It is also possible to change the language displayed on the stage. To do so, from the Window menu, click Other Panels,
and then click Strings. In the Stage Language menu, select the language to use for the stage language. This must be
a language you added as an available language.

On changing the language on the stage, any new text typed or previously entered text strings also appear in the
changed language.

3.5.6 Enter Asian Characters on a Western Keyboard


Flash provides the option of using Input Method Editors (IMEs) and standard Western keyboards to enter Asian
characters on the stage. With Flash Professional, it is possible to use more than 24 IMEs.
For example, to create a Website that reaches a broad range of Asian viewers, users can make use of a standard
Western (QWERTY) keyboard and change the IME to create text in Chinese, Japanese, and Korean.

This feature affects only text input on the stage, not text entered in the Actions panel. This feature is available
for all supported Windows operating systems and Mac OS X.

3.6 Summary
In this session, Working with Text, you learned that:
¾¾ Classic text and Text Layout Framework (TLF) are the two types of text available in Flash.
¾¾ Classic text is further divided into static, dynamic, and input.
¾¾ Flash gives the option of converting classic text into TLF format and vice versa without losing out on the details.
¾¾ Using the Property Inspector, it is possible to format text in Flash.
¾¾ In addition to text formatting, it is also possible to format paragraphs for their alignments, margins, indents, and
spacing.
¾¾ Excess text within a text box is denoted using the Overload icon that is accomodated by creating a text thread
link to new text box or an existing text box. The In-port and Out-port icons are used to unlink the text, if required.
¾¾ The Container and Flow sections available in the Property panel of the TLF text box can be used to create text
columns similar to those seen in newspapers. Using this feature, users can specify the number of columns, the
gutter and padding size between columns, maximum number of characters, alignment of text, and the border
and fill colors of the columns.
¾¾ Text linking feature is available only for TLF text and does not apply to Classic text blocks. Text containers can
be threaded from frame to frame, and inside symbols, as long as the threaded containers are all within the same
timeline.
¾¾ The UIScrollBar component is used to make a TLF text container scrollable.
¾¾ A paragraph model comprises a combination of Leading Basis and Leading Direction. Leading Basis determines
the baselines of two consecutive lines that are intended to be at a specific distance from each other. On the
contrary, Leading Direction determines the direction in which the line height is measured.
¾¾ The Strings panel in Flash helps users create and update multilingual content. Upto 100 languages can appear
on the stage and in the Strings panel for translation.

3.7 Exercise
1. The three types of TLF text available for use are Font style, Selectable, and Editable.

True

False

2. TLF Editable text type is converted into ___________ text type.

TLF Selectable

Classic input

Classic Static

TLF Read only

3. The ____________ option lets users control the space between characters.
Leading

Letter spacing

Auto-Kern

Tracking

4. On clicking the Overflow icon, the pointer changes to a Loaded Text cursor.

True

False

5. With Flash Professional, users can use ____________ and standard Western keyboards to enter Asian characters
on the stage.

Output method editors

Input multilingual editors

Input editor methods

Input method editors


S e s s io n 4
Symbols and Effects
Learning Outcomes
In this session, you will learn to:
¾¾ Work with symbols and instances
¾¾ Create patterns using the Spray Brush and Deco tools
¾¾ Work with 3D spaces

4.1 Understanding Symbols and Instances


Using Flash, it is possible store characters as symbols and use it over and over again. It is also possible to create a
whole new Library of reusable symbols in Flash.

In Flash, a symbol is a reusable element that can be stored in the Flash Library and an instance is a copy of that symbol.
These symbols can be repeatedly used in any movie by inserting an instance of the symbol in the frame in which the
user wants it to appear.

A symbol can be an object you draw with Flash drawing tools, or a movie clip. Inserting a copy of the symbol in a project
indicates that an instance has been inserted. Since the instance references the original symbol, it does not affect the
size of the file.

4.1.1 Types of Symbols


There are three types of symbols in Flash, which are as follows:
¾¾ Graphics
¾¾ Buttons
¾¾ Movie clips
Each symbol type has its own timeline, stage, and layers.
¾¾ Graphic symbols
Graphic symbols are the most basic type of symbols. These symbols can be used for both static objects, like
backgrounds and animations.
Graphic symbols help reduce the file size and make it easier to add multiple copies of a graphic to a movie.
Symbols are stored in the Library and are available across all movies. Therefore, symbols are the best way in
which users can store graphic images that can be used in Flash movies.
Elements like sounds and actions present inside graphic symbols are ignored by Flash. Actions play a major
role while creating interactive movies. It is for this reason that when an animation is simple, it is converted into
a graphic symbol. Graphic symbols are always placed on the main timeline of the movie.
¾¾ Movie clip symbols
A movie clip can be compared to a movie within a movie that can be manipulated by using interactive controls.
These controls are commonly referred to as actions that are created using ActionScript. Movie clips are crucial
for complex and interactive animations. A movie clip has its own timeline. For example, users can play a movie
clip at any time, and then return to where they had left on the timeline. It is also possible to attach movie clips
to buttons.
¾¾ Button symbols
These symbols, as the name suggests, is used for creating buttons. Buttons are clickable graphics in Websites
that are linked to other places in the site or the Internet. In Flash, it is possible to create buttons that work in a
similar fashion. Users can create buttons that help in taking decisions about viewing a movie or better still you
can use advanced scripting techniques to create buttons that can be used for interactive games and other such
activities. You can also add movie clips and interactive controls to buttons.
4.1.2 Creating Symbols
Symbols are an efficient way to add artwork or elements to your Flash movie. These symbols are easily accessible and
can be reused as instances in the timeline. You can either convert your animations or movie clips into symbols or create
a new one entirely.
■■ Creating a new symbol

To create a new symbol, select the New Symbol command from the Insert menu. Enter a name for the symbol.
Select a symbol type from the Type drop-down list and click OK. Refer to Figure 4.1.

Figure 4.1: Create New Symbol dialog box

After giving a name to the symbol, Flash switches to the symbol edit mode, where you can use the drawing tools to
create a new symbol. Refer to Figure 4.2.

Figure 4.2: Symbol edit mode

The name of the symbol appears above the stage area. You can save the symbol and exit the symbol edit mode by
clicking the Scene Name link that appears to the left of the name of the symbol.
■■ Creating an existing object to a symbol

To convert an object into a symbol, begin by selecting the object on the stage. Then, from the Modify menu, click
Convert to Symbol. Type a name for the symbol in the space provided. Then, select a symbol type from the Type
drop-down list and click OK.

For detailed step-by-step procedure, refer to demo Creating Symbols from:


eResources 4 Me>> My Varsity>> Web Animation and Interactivity>> Show Me How>> Understanding Symbols and
Instances>> Creating Symbols

4.2 Working with Instances


So far you are aware that an instance is a copy of a symbol. Using a symbol in the timeline indicates that you are
using an instance of that symbol. Making changes to an instance does not affect the original symbol in the Library. This
helps in maintaining a lower file size. There could be
situation wherein changes have to be made to more
than one symbol. In such situations, you can make
changes to the master symbol. The result is that, all
instances of the symbol are updated with the change.
■■ Inserting an instance

You can insert an instance of a symbol on the


stage from the Library panel. To do so, select the
symbol from the list of assets and drag it on the
stage. Refer to Figure 4.3.
■■ Modifying an instance

You can change the appearance of the instance on


the stage without making changes to the original
symbol using the Properties panel. Changes that
can be made to an instance include change in tint,
transparency, looping of an animation inside the
symbol, and blend modes. Blend modes come Figure 4.3: Inserting an instance
with a range of visual effects that can be
applied on symbol instances. Refer to
Figure 4.4.
■■ Applying color effects to symbol
instances

A variety of color effects can be applied


to each symbol instance. Brightness,
tint, and alpha (transparency) are the
basic color effects. You can create some
special effects by combining the tint and
alpha values.

To apply color effects to an instance,


begin by selecting the instance. Then,
from the Color Effect section of the
Properties panel, click the Style drop-
down list. Select a style from the list of
styles that appear.

The options available under the Color


Effect Style menu are as follows:
¾¾ None
¾¾ Brightness Figure 4.4: Modifying an instance using the Properties panel
¾¾ Tint
¾¾ Alpha
¾¾ Advanced

Click here to know more about Color Effect Style options.

The Properties panel also has the looping section that helps control the graphic/movie clip playback. The options
available in this section are as follows:
¾¾ Loop: This is the default setting for graphic symbols. If the graphic symbol extends beyond its original length
along a timeline, then the symbol restarts. Graphic symbol looping is dependent on the main timeline. You have
to match the number of frames on the main timeline with the number of frames that you want to play in the
graphic symbol timeline.
¾¾ Play once: This option does not play the graphic symbol more than once.
¾¾ Single frame: This option holds the graphic symbol on one frame such that it behaves like a static graphic. A
specific frame can be selected within the graphic symbol timeline to display as the static graphic. However, the
appearance of the graphic symbol is the same regardless of how far it extends along a timeline.
¾¾ Applying blend modes to movie clips: Flash Pro blend modes are used to create composite images.
Compositing is the process of varying the transparency or color interaction of two or more overlapping images.
Using blend modes it is possible to add a dimension of control to the opacity of objects and images. Users
can create highlights or shadows that bring out the details from an underlying image. They can also colorize a
desaturated image.
The Blend panel is available in the Properties panel and can be applied to a movie clip or button symbol
instances. Blends are rendering tools that blend an image with underlying base images to create an image that
is a mix of the two. The blended image will interact with any underlying images that it overlaps - even if they are
not on the same layer. Refer to Figure 4.5.

Figure 4.5: Blend modes


Refer to Table 4.1 to view a description of the various blend modes.

Blend Modes Description


Normal This blend mode creates no effect.
Layer This mode stacks clips on each other.
Darken This mode replaces lighter areas without affecting the darker ones.
Multiply This mode multiplies colors resulting in dark colors.
Screen This mode inverts the blend colors.
Overlay This mode multiplies the base color.
Hard light This mode multiplies the blend color.
Add This mode lightens the final color by dissolving the base color and the blend color.
Subtract This mode darkens the final color by dissolving the base color and the blend color.
Difference This mode subtracts the blend color from the base color or vice-versa.
Invert This mode inverts the base color.
Alpha This mode applies an alpha mask.
Erase This mode removes the base color.
Table 4.1: Description of the available blend modes
Quick Test 4.1

1. It is possible to attach movie clips to buttons.


True False

2. Loop is the default setting for graphic symbols that does not play more than once.

True False

4.3 Editing Symbols


In Flash, you have the option of editing symbols that are placed in the Library using the symbol editing mode. On editing
a symbol, all instances of that symbol are automatically edited. This helps in saving a lot of time and effort.

To make changes to a symbol, you need to first enter into the symbol editing mode. This way you can view and make
changes to the symbol’s timeline. Symbols can be edited in either of the following ways:
¾¾ Using the Edit in Place command: This option can be exercised using the Edit in Place command from the
Edit menu. On selecting this option, the object that has to be edited is prominent and the space around it, along
with the other objects is dimmed out. This distinguishes the object to be edited from the others. Moreover, the
name of the symbol appears at the top left, beside the name of the scene, on the Information bar. Refer to
Figure 4.6.

Figure 4.6: Edit in place command


¾¾ Using the Edit in New Window command: This method is useful while working with multiple windows. It helps
in editing objects while keeping a view of the main timeline that is available. It is also possible to switch between
windows from the Window menu. To edit a symbol in a new window, select an instance on the stage and right-
click. Then, select Edit In New Window from the contextual menu. Refer to Figure 4.7.
Figure 4.7: Edit in new window command
¾¾ Using the symbol editing mode: In this mode, the window changes from the stage view to the symbol view.
The name of the symbol that is being edited appears at the top, on the left of the scene name, in the Information
bar. In the symbol editing mode, only the symbol can be viewed. Refer to Figure 4.8.

Figure 4.8: Symbol editing mode

4.4 Swapping Symbols


Consider a situation when you want to edit parent symbols without affecting the effects applied to its instances. The
Swap Symbol feature in Flash helps you swap symbols with ease. On using this feature to swap symbols, all the effects
are preserved and are applied and referenced to the new chosen symbol. Alternately, you can also change the content
of the master symbol, of one of the instances that you are working on, without affecting the other instances. This can
be done by duplicating and swapping that symbol in the Swap dialog box. Essentially, you create a new master symbol
linked to your instance that is no longer related to the original master symbol and all its instances. To swap symbols,
select an instance on stage and from the Properties panel, click the Swap button. In the Swap Symbol dialog box that
appears, select the desired symbol and click OK. Refer to Figure 4.9.
Figure 4.9: Symbol editing mode

For detailed step-by-step procedure, refer to demo Editing Symbols and Swapping from:

eResources 4 Me>> My Varsity>> Web Animation and Interactivity>> Show Me How>> Swapping Symbols

4.5 Working with Filters


Text, buttons, and movie clips can be made more interesting by adding
visual effects using filters. Filters can be applied only to text, button, and
movie clip objects. Flash Pro has this unique feature of animating filters
using motion tweens.

Filter presets are available in the Filters section of the Property Inspector.
Presets are available under the Filters menu. Refer to Figure 4.10.

An object can have more than one filter. Each time a new filter is added to
an object, it is appended to the Property Inspector. Moreover, it is also
possible to delete a previously applied filter. Frequently used filters can be
accessed from the filter settings library.

4.5.1 Apply or Remove a Filter


To apply or remove a filter, begin by selecting a text, button, or movie clip.
Then, from the Filters section of the Property Inspector, add or remove
filters.

To add a filter, click the Add Filter button. Select a filter from the list of
available filters. Experiment with the settings for the desired look.

To remove a filter, select the filter to be removed and click the Remove
Filter button.
Figure 4.10: Add filter menu
It is also possible to delete or rename any presets.

4.5.2 Copy and Paste a Filter


1. Select an object.

2. From the Filters panel, select the filter to copy and click the Clipboard button.

3. Click Copy Selected from the pop-up menu. Incase if all the filters have to be chosen, select Copy All.

4. Select the object to which the filter has to be applied. Click the Clipboard button and choose Paste from the pop-up
menu.
Users can toggle between the enable state of the other filters in the list by clicking the enable icon in the Filter
list while keeping the Alt key pressed. On clicking the disable icon while keeping the Alt key pressed, the
selected filter is enabled, and all other filters in the list are disabled.

4.5.3 Preset Filters


Filters that can be saved with a particular setting and can be used on a later date are referred to as Preset filters. These
filters can be applied to movie clips, buttons, or text. On applying Preset filters on any object, the already applied filters
are removed. You can also create a library of filters with the preset settings by applying the filter or filters to the object.
To save a Preset filter, from the Presets menu, select Save As. In the Save As Preset dialog box that appears, enter
a name for the preset and click OK.

4.5.4 Apply a Preset Filter to an Object


1. Select the object to apply a filter preset to, and select the Filter tab.

2. Click the Add Filter button, and select Presets.

3. Select the filter preset to apply from the list of available presets at the bottom of the preset menu.

On applying a filter preset to an object, Flash Pro replaces the currently applied filters with the filters used in
the preset.

Refer to Table 4.2 to view a description of the filters available in the Properties panel.

Filters Description
Drop Shadow Creates a shadow of the selected object. Users can not only apply color but also change
the direction and distance of the shadow.
Blur This filter softens the details and edges of an object. This filter can also be used to blur
the object when it is too close or too far from the camera.
Bevel This filter gives a raised effect to the selected object.
Glow This filter applies a glow to the edges of the selected object. This filter can be applied
to the moon in an evening scene.
Gradient glow This filter creates a gradient glow. More than one color can be used to create this effect.
Gradient bevel This filter allows you to use color gradients. The options available are similar to that of
the gradient glow filter.
Adjust color This filter is used to change the color, brightness, contrast, and saturation.
Table 4.2: Filters available in the Properties panel and their description

Quick Test 4.2


1. In the symbol editing mode the window changes from the symbol view to the stage view.
True False

2. You can rename a filter preset using the Add Filter button.

True False
4.6 Understanding the Flash Library
A Library, as the name suggests, is the place where assets used in a movie is stored. An asset could be anything -
objects, symbols, instances, movie clips, and similar elements. Assets within a Library can be used across several Flash
files. It is also possible to view the Library items of multiple Flash files at the same time using a single Library panel.
To open a Library panel, from the Window menu, select Library. Alternatively, you can press the Ctrl+L keys. Refer
to Figure 4.11.

Figure 4.11: Library panel

Click here to know more about the Library panel.

4.7 Creating Patterns with the Spray Brush and Deco Tool
In Flash, you can auto-create patterns based on the settings that you enter before you use them using the Spray Brush
tool and the Deco tool. These tools use symbols in place of fill and stroke colors. These tools make it very easy to create
patterns. You can do so by simply clicking on the stage and Flash distributes instances of the selected symbol across
the stage. It also arranges the symbols based on your specifications.

4.7.1 Spray Brush Tool


Using the Spray Brush tool, you can spray particles onto the stage using the current fill color. The spray pattern
can be adjusted by selecting the Symbol and Brush
options in the Property Inspector. The Symbol
option includes:
¾¾ Scale
¾¾ Random scaling
¾¾ Rotate symbol
¾¾ Random rotation

The Brush option includes:


¾¾ Width
¾¾ Height
¾¾ Brush angle Figure 4.12: Spray Brush options

Refer to Figure 4.12.


To create more complex patterns, users can use a movie clip or graphic symbol from a Library as a particle. To do so,
click the Edit button in the Properties panel. Refer to Figure 4.13.

Figure 4.13: Spray Brush with symbols

You can access the Spray Brush tool from the Tools panel. It shares space with the Brush tool. You can select a fill
color as the default color and also set other options in the Properties panel. Incase if you want to use a movie clip or
graphic symbol as a spray particle then, click the Edit button and click and drag on the stage where you want the pattern
to appear.

Refer to Table 4.3 to view a description of the options available in the Spray Brush tool.

Tool options Descriptions


Edit This option opens the Select Symbol dialog box. This is where you can select a movie clip or
graphic symbol that can be used as a spray brush particle.
Color Selector This option helps you set a default fill color for the particle spray. On using a symbol in the
Library as a spray particle, the color selector is disabled.
Scale This property appears when a symbol from a property is used as a particle. Using this option,
you can scale the symbol that is used as a spray particle. For example, a scale value of 10%
makes the symbol 10% smaller; whereas, a scale value of 200% makes the symbol 200%
larger.
Scale width This property appears when the symbol is used as a particle. Using this option, you can scale
the width of a symbol that is used as a spray particle. For example, a value of 10% makes the
symbol 10% narrower; whereas, a value of 200% makes the symbol 200% wider.
Scale height This property appears when the symbol is used as a particle. Using this option, you can scale
the height of a symbol that is used as a spray particle. For example, a value of 10% makes the
symbol 10% shorter; whereas, a value of 200% makes the symbol 200% taller.
Random scaling This option denotes that each symbol-based spray particle is placed on stage at a random
scale, where the size of each particle is different. This option is not available while using the
default spray of dots.
Rotate symbol This property is available only when a symbol is used as a particle. Using this option, you can
rotate a symbol-based spray particle around a center point.
Random rotation This property appears only when a symbol is used as a particle. It denotes that each symbol-
based spray particle is placed on stage at a random degree of rotation. This option is disabled
on using the default spray of dots.
Tool options Descriptions
Width This option defines the width of the spray particle when a symbol is not used from the Library.
Height This option defines the height of the spray particle when a symbol is not used from the Library.
Brush angle This option defines the amount of clock-wise rotation that is to be applied to the spray particle
when a symbol is not used from the Library.
Table 4.3: Spray Brush tool options and their descriptions

For detailed step-by-step procedure, refer to demo Spray Brush Tool from:

eResources 4 Me>> My Varsity>> Web Animation and Interactivity>> Show Me How>> Creating Patterns with the Spray
Brush and Deco Tool>> Spray Brush tool

4.7.2 Using the Deco Tool


Using the Deco tool, you can apply a kaleidoscopic drawing effect to the stage or a selected object on the stage. You
can also apply the following effects:
¾¾ Vine Fill
¾¾ Grid Fill
¾¾ Symmetry Fill
¾¾ 3D Brush
¾¾ Building Brush
¾¾ Decorated
¾¾ Fire Animation
¾¾ Flame Brush
¾¾ Flower Brush
¾¾ Lightning Brush
¾¾ Tree Brush

Using the Vine effect, you can fill the stage, symbols, objects, or any closed area with a vine pattern. You can also use
your own artwork (symbols) for the leaves and flowers. Refer to Figure 4.14.

Figure 4.14: Vine fill


Using the Grid effect, you can fill the stage, symbol, object, or closed area with a symbol from the Library. You can also
create grid patterns, such as a tiled background or checkerboard. Refer to Figure 4.15.

Figure 4.15: Grid effect

Using the Symmetry effect, you can arrange symbols symmetrically around a central point. These symbols can be
controlled with a set of handles. You can also create circular elements, such as a planet. The default symbol for the
Symmetry effect is a 25 x 25 pixel black rectangle with no stroke. Refer to Figure 4.16.

Figure 4.16: Symmetry effect


You can make use of other brushes to draw buildings, flames, lightning, trees, and other effects. You can also add fire
and smoke animations or a particle system. Refer to Figures 4.17, 4.18, 4.19, and 4.20.

Figure 4.17: Other available brushes Figure 4.18: Building brush

Figure 4.19: Tree brush Figure 4.20: Decorated brush


You can access the Deco tool from the Tools panel. Then, select a drawing effect from the Property Inspector by
clicking the Drawing Effect list arrow. For the Vine Fill, Grid Fill, or Particle System effect, you can either select a fill
color for the default shape or select a custom symbol from the Library. You can also use any of the movie clips or graphic
symbol in the Library as a pattern. You can also specify any advanced options that you require for the different effects.
After making your selections, click on the stage or within the shape or symbol to apply your pattern.

For detailed step-by-step procedure, refer to demo Deco Tool from:

eResources 4 Me>> My Varsity>> Web Animation and Interactivity>> Show Me How>> Creating Patterns with the Spray
Brush and Deco tool>> Using the Deco tool

4.8 3D Spaces
In Flash, you can add 3D perspective effects to a movie clip by moving and rotating it in 3D space on the stage. When
you move or rotate a movie clip by the z-axis, it becomes a 3D movie clip. In 3D terminology, moving an object in 3D
space is called translation and rotating an object in 3D space is called transformation. Once you have applied either of
these effects to a movie clip, Flash considers it to be a 3D movie clip and a colored axes indicator appears overlaid onto
the movie clip whenever it is selected. Global and local are the two different 3D spaces in Flash. Global 3D space is the
stage space; whereas, local 3D space refers to the movie clip space. However, the default mode is global.

4.8.1 Moving an Object in 3D Space


Using the 3D Translation tool, you can move movie clip instances. On selecting a movie clip with this tool, the X, Y, and
Z axes appear on stage on the top of the object. The x-axis is depicted in red, the y-axis is depicted in green, and the
z-axis is depicted in blue.

Moving an object in Local 3D space refers to moving the object relative to its parent movie clip. You can toggle between
the two modes - global and local - using the 3D Translation tool. To do so, click the Global toggle button in the Options
section of the Tools panel keeping the 3D Translation tool selected. Alternatively, you can use the D key to toggle
between the two modes while dragging with the 3D Translation tool.

The 3D Translation and Rotation tools appear together in the Tools panel. To select the currently inactive 3D tool, you
can click and hold the active 3D tool icon in the Tools panel. By default, selected objects that have 3D translation applied
appear with a 3D axis overlay on the stage. You can turn off this overlay in the General section of Flash Preferences.
■■ Moving a single object in 3D space

To move a single object in 3D space, begin by selecting the 3D Translation tool from the Tools panel. Then, set the
mode to either Local or Global and then drag the arrow tips in the direction of the arrow (x and y-axis) or the black
arrow either upward or downward. (x- and y-axis) in the direction of the arrow or the black dot (z-axis) up or down.

You can also move the object by entering values of the x, y, and z-axis in the 3D Position and View section of the
Properties panel. Refer to Figure 4.21.

Figure 4.21: Moving objects in 3D space


4.8.2 Rotating an Object in 3D Space
Using the Rotation tool, you can rotate movie clip instances in 3D space. On rotating the movie clip, you will notice that
a 3D rotation control appears on top of selected objects on the stage. The X control is red, the Y control is green, and
the Z control is blue. Using the orange free rotate control, you can rotate around the X and Y axes at the same time.

Global is the default mode for the 3D Rotation tool. Rotating an object in global 3D space is the same as moving it
relative to the stage. Rotating an object in local 3D space is the same as moving it relative to its parent movie clip if it
has one. To toggle the 3D Rotation tool between global and local modes, click the Global toggle button in the Options
section of the Tools panel while the 3D Rotation tool is selected. Alternatively, you can toggle between the two modes
by pressing the D key while dragging with the 3D Rotation tool.

By default, the selected objects that have the 3D rotation applied, appear with a 3D axis overlay on the stage. You can
turn off this overlay from the General section of Flash Preferences.
■■ Rotate an object in 3D space

To rotate an object in 3D space, begin by selecting the 3D Rotation tool from the Tools panel. Set the mode to local
or global and then drag one of the four axis controls to rotate around that axis. You can also rotate the object by
entering values of X, Y, and Z-axis in the 3D Position and View section of the Properties panel. Refer to Figure 4.22.

Figure 4.22: Rotating object in 3D space

4.8.3 Adjusting the Perspective Angle


The apparent angle view of 3D movie clips is controlled by the Perspective Angle property. On increasing or decreasing
the Perspective Angle, the size and location of the 3D movie clip changes in relation to the stage. Increasing the
Perspective Angle, makes the 3D objects appear closer to the viewer; whereas, decreasing the Perspective Angle,
makes the 3D objects appear further away. The effect of change in the Perspective Angle is very similar to the effect
of a zoom in or out with a camera lens. The Perspective Angle property affects only those movie clips that have 3D
translation or rotation applied to them. You can view or set the Perspective Angle from the Properties panel. To do so,
begin by selecting a 3D movie clip on stage and then alter the values. You will observe that the changes done to the
Perspective Angle will be visible on stage immediately. The Perspective Angle changes automatically when you change
the Stage size so that the appearance of 3D objects does not change. You can turn off this behavior in the Document
Properties dialog box. Refer to Figure 4.23.
Figure 4.23: Perspective angle

In order to set a Perspective Angle, begin by selecting a movie clip instance that has the 3D rotation or translation
applied to it. Then, in the Properties panel, enter a value in the Perspective Angle field. Alternatively, you can also
drag the hot text to alter the values.

4.8.4 Adjusting the Vanishing Point


Vanishing Points help move 3D movie clips on stage by maintaining the same visual perspective of the original file.
These points control the orientation of the z-axis of the 3D movie clips. As you move the z-axis, you will observe that
the 3D movie clips recede toward the Vanishing Point. These Vanishing Points can be adjusted to create the desired
appearance. A single Flash file has only one Vanishing Point. You can use the Reset button in the Properties panel to
reset the position of the Vanishing Point.

Like the Perspective Angle, to view or set the Vanishing Point in the Properties panel, a 3D movie clip must be selected
on stage. Changes to the Vanishing Point are visible on the stage immediately. Refer to Figure 4.24.

Figure 4.24: Vanishing points


4.9 Summary
In this session, Symbols and Effects, you learned that:
¾¾ In Flash, users can store characters as reusable symbols. A symbol is a reusable element and an instance is a
copy of that symbol.
¾¾ On a macro level, graphics, buttons, and movie clips are the three types of symbols in Flash. Each of these
symbol has its own timeline, stage, and layers.
¾¾ Using a symbol in the timeline indicates that you are using an instance of that symbol. Making changes to an
instance does not affect the original symbol in the Library.
¾¾ Blends are rendering tools that blend an image with underlying base images to create an image that is a mix of
the two.
¾¾ Symbols can be edited in the symbol editing mode in Flash. On editing a symbol, all instances of that symbol
are automatically edited. This helps in saving a lot of time and effort.
¾¾ The Swap Symbols feature in Flash is used to swap symbols with ease. On swapping symbols, all the effects
are preserved and are applied and referenced to the new chosen symbol.
¾¾ Filters add interesting graphic effects to text, buttons, and movie clips. It is possible to animate filters by applying
motion tween. This is a unique feature of Flash Pro.
¾¾ Filters that can be saved with a particular setting and can be used on a later date are referred to as Preset filters.
These filters can be applied to movie clips, buttons, or text.
¾¾ A Library is where the assets used in a movie are stored. Assets within a Library can be used across several
Flash files. It is also possible to view the Library items of multiple Flash files at the same time using a single
Library panel.
¾¾ The Spray Brush and Deco tool are used to create patterns with ease in Flash. These tools use symbols instead
of fill and stroke colors.
¾¾ Moving or rotating a movie clip by the z-axis makes it a 3D movie clip. Moving an object in 3D space is called
translation and rotating an object on 3D space is called transformation.
¾¾ The apparent angle view of 3D movie clips is controlled by the Perspective Angle property. On increasing or
decreasing the Perspective Angle, the size and location of the 3D movie clip changes in relation to the stage.

4.10 Exercise
1. A graphic created in Photoshop and imported in Flash, is referred to as a symbol in Flash.

True

False

2. Clickable graphics in Websites that are linked to other places in the site of the Internet are referred to as _____.

Buttons

Movie clips

Timelines

Symbols

3. The process of varying the transparency or color interaction of two or more overlapping objects is referred to as
________.

Blending

Looping

Compositing

Instancing
4. Blended images interact with the underlying images that it overlaps __________.

Only if the images are on the same layer

Even if they are not on the same layer

Only if the images are on different layers

Only if they are composited images

5. On swapping symbols, the effects are preserved and are applied and referenced to the new chosen symbol.

True

False

6. Filters that can be saved with specific settings and can be used on a later date are known as ______.

Filter instances

Filter symbols

Filter presets

Filter replicas

7. The Library panel can be accessed from the _________ menu.

Context

Application

Window

Tools

8. Using the __________ effect, it is possible to arrange the symbols symmetrically around a central point.

Grid

Symmetry

Vine

Lightning

9. Rotating an object in local 3D space is different from moving it relative to its parent movie clip, if any.

True

False
S e s s io n 5
Frame-by-Frame Animation and Shape Tweening
Learning Outcomes
In this session, you will learn to:
¾¾ Work with frames in the timeline
¾¾ Create frame-by-frame animation
¾¾ Use onion skinning
¾¾ Apply shape tweening

5.1 Understanding Timeline


Flash CS6 provides several ways to create animations and special effects. Each method provides you with different
possibilities for creating engaging animated content.

Flash supports the following types of animation:


¾¾ Motion tweens
¾¾ Classic tweens
¾¾ Inverse Kinematics poses
¾¾ Shape tweens
¾¾ Frame-by-frame animation

Timeline, as the name suggests, represents the timing of the animation. Hence, it is of utmost importance in animations.
On playing your animation, the contents of your frame are displayed from left to right, across the timeline.

The timeline comprises three little rectangles, each representing one frame in your animation. The number of frames in
an animation appears at the top of the timeline. Refer to Figure 5.1.

Figure 5.1: Timeline

Using timelines you can modify and edit frames, assign special attributes, or change the type of frames. You can also
control the speed at which the animation plays, create keyframes, static frames, or blank frames.

Layers, frames, and the playhead are the major components of a timeline. Layers are listed on the left side of the
timeline. Frames in each layer appear as a row to the right of the layer name.

The timeline header indicates the frame numbers. The playhead – the red line on the timeline, indicates the current
frame that is displayed on the stage. The playhead moves from left to right through the timeline as a document plays
on the stage.
The selected frame number, current frame rate, and elapsed time to the current frame appear at the bottom of the
timeline. This is known as the timeline status.
The timeline displays the location, type, and motion paths in an animation.

Controls in the layers section of the timeline lets users hide, show, lock, or unlock layers, as well as display layer
contents as outlines. It is possible to drag timeline frames to a new location on the same layer or to a different layer.

Click here to know more about timeline.

5.1.1 Change the Appearance of the Timeline


The timeline appears below the main document window. This happens by default. The position of the timeline is not
fixed. It can be floated in its own window or docked to any other panel. Timelines can also be hidden.

Timelines can be resized to change the number of visible layers and frames. Using the scroll bar, users can view
additional layers of the Timeline.

The following actions can be performed to change the appearance of the Timeline:
¾¾ Moving a Timeline: To move a timeline when it is docked, drag the title bar at the upper-left corner of the
timeline.
¾¾ Docking a Timeline:
●● To dock a timeline to the application window, drag the title bar to the top or bottom of the document window.

●● To dock a timeline to other panels, keep the Control key pressed while dragging the timeline title bar to the
desired location. A blue bar appears indicating the position where the Timeline will dock.
¾¾ Altering the length of the name fields: To lengthen or shorten the layer name fields in the timeline panel, drag
the bar separating the layer names and the frames portion of the timeline.
■■ Change the display of frames in the timeline

The display of frames in the timeline can be modified to suit the users’ requirements. This can be done by selecting
the options available under the Frame View pop-up menu.

Users can change the width and height of the frame cells. They can also turn the tinting on or off by selecting Tinted
Frames. Refer to Figure 5.2.

Figure 5.2: Frame View pop-up menu

Refer to Table 5.1 to view a description of the options available in the Frame View pop-up menu.

Frame View Pop-Up Menu Options Description


Tiny, Small, Normal, Medium, and Large Used to change the width of the frame cells.
Short Used to decrease the height of frame cell rows.
Tinted frames Used to turn the tinting of frame sequences on or off.
Frame View Pop-Up Menu Options Description
Preview Used to display thumbnails of the content of each frame scaled to
fit the timeline frames. This option can cause the apparent content
size to vary and also requires extra screen space.
Preview in Context Used to display thumbnails of each full frame, including empty
space.

This option comes handy to view the way in which elements move
in their frames in an animation. However, previews are usually
smaller as compared to the Preview option.
Table 5.1: Frame View pop-up menu options and their description
■■ Change the layer height in the timeline

The height of the layer in a timeline can be modified in any of the following ways:
¾¾ Double-click the icon to the left of the layer name in the timeline.
¾¾ Right-click the layer name and select Properties from the shortcut menu.
¾¾ Select the layer in the timeline. From the Modify menu, point to Timeline, and then click Layer Properties. In
the Layer Properties dialog box that appears, select an option for the layer height and click OK.

5.1.2 Resize the Timeline


To resize a timeline, drag the bar separating the timeline from the stage area. This works only if the timeline is docked.
Incase if the timeline is not docked, drag the lower-right corner of the timeline to resize it.

5.1.3 Label Frames in the Timeline


Labeling frames help in organizing its contents. It also helps in referring to a frame with ease in ActionScript. Labels can
be applied only to keyframes. It is best to create a separate layer in the timeline to contain the frame labels.

Perform the following steps to add a frame to a label:

1. Select a frame in the timeline that has to be labeled.

2. Keeping the frame selected, enter a name for the label in the Label section of the Property Inspector and press
Enter. Refer to Figure 5.3.

Figure 5.3: Timeline displaying frame labels

5.1.4 Move the Playhead


When an animation is played, the playhead moves to indicate the current frame displayed on the stage. The frame
numbers of the animation are indicated by the timeline header.
¾¾ Moving the playhead from one frame to the other displays a frame on the stage.
¾¾ Moving the playhead along the timeline displays a specific frame. This is useful when there are a large number
of frames in an animation.
¾¾ Dragging the playhead to the desired position takes the user to a specific frame. Alternatively, users can click
the location of the frame in the timeline header.
¾¾ To center the timeline on the current frame, click the Center Frame button at the bottom of the timeline.

5.2 Changing the Frame Rate


The project frame rate affects the playback of all animations. The frame rate of any animation appears in the Document
Settings dialog box. To access the Document Settings dialog box, from the Modify menu, select Document.
Alternatively, you can click in the document window of an open file in the Properties panel. Remember, not to select
any items on stage if you want to access the document window options. The permissible frame rate range is between
0.01 and 120 frames per second (fps). However, the default setting in Flash is 24 fps. Refer to Figure 5.4.

Figure 5.4: Changing the frame rate

In frame-by-frame animation, the commonly used frame rate is between 12 fps and 24 fps; increasing the frame rate
results in smoother animations. It is possible to change the frame rate after you have authored a file. It is also possible
to reset the timing of the animation, insert frames, or remove frames. It is also possible to change the duration of the
tweens of an animation. However, it makes sense to streamline a final frame rate before you start designing and testing
complex animation sequences.

5.3 Frame-by-Frame Animation


Frame-by-frame animation works in a similar manner like the flip book concept. In the flip book concept, frames are
created individually on separate sheets of paper and
flipped to create an illusion of motion.

Similarly, in frame-by-frame animation, objects are


drawn again in each frame with slight differences
from the previous frame. These frames when
played, creates an illusion of movement, in turn
forming an animation. Refer to Figure 5.5.

Frame-by-frame animation - the most basic form of


animation - originated in the 2D form of sketching.
With the rise of technology, it was later implemented
in digital animation. In this form of animation, every
single frame is created separately and differently
from the previous frame. This kind of artwork, when
played in succession, creates a sense of movement. Figure 5.5: Flip book
This technique is best suited for complex animations that require subtle changes. For example, animations that throw
emphasis on facial expressions.
Like any other form of animation, frame-by-frame animation has its own drawbacks. Unlike other forms of animation,
frame-by-frame animation is very tedious and time consuming. In Flash, you can create frame-by-frame animations in
the timeline using keyframes. Each keyframe specifies a change on the stage. When the content is played in succession,
it appears to move. On exporting your movie, Flash plays these frames in succession at specific intervals depending on
the frame rate you set. Refer to Figure 5.6.

Figure 5.6: Frame-by-frame animation

5.3.1 Creating Keyframes


To add a keyframe to a timeline, begin by selecting the frame that you want to convert into a keyframe. Then, right-click
the frame and select Insert Keyframe from the contextual menu. Alternatively, from the Insert menu, choose Timeline.
From the Application menu, select Keyframe. In addition to the two methods you can also press the F6 key.

You will now learn how to create a blank keyframe. To do so, right-click the frame and select Insert Blank Keyframe
from the contextual menu. Alternatively, from the Insert menu, select Timeline. Then, select Blank keyframe from the
Application menu. In addition to the listed methods, you can also press the F7 key.
■■ Inserting frame

The number of frames in a movie and the frame rate determines the length of a movie. Increasing the number of
frames increases the duration of the movie.

To insert frames, right-click the selected frame or frames in the timeline and select Insert Frame from the context
menu. Alternatively, you can select Timeline from the Insert menu. From the submenu that appears, select Frame.

5.3.2 Converting Frames to Keyframes and Vice Versa


To convert a frame into a keyframe, begin by selecting a frame. Then, from the Modify menu, select Timeline. From the
submenu that appears, select Convert to Keyframes. Alternatively, you can right-click a keyframe in the Timeline and
select Convert to Keyframes from the context menu.

To convert a keyframe to a frame, begin by selecting a keyframe. Then, from the Modify menu, select Timeline. From
the submenu that appears, select Clear Keyframe. Alternatively, you can right-click a keyframe in the Timeline and
select Clear Keyframe from the context menu.

To convert a frame into a blank keyframe, begin by selecting a frame or a keyframe. Then, from the Modify menu, select
Timeline. From the submenu that appears, select Convert to Blank Keyframes. Alternatively, you can right-click a
keyframe in the Timeline and click Clear Frames from the context menu. In addition, you can also select Timeline from
the Edit menu. From the submenu that appears, click Clear Frames.

5.3.3 Frame-Based and Span-Based Selections


Frame-based and span-based are the two selection modes available in Flash. Refer to Table 5.2 to view the differences
between frame-based and span-based selections.

Frame-Based Selection Span-Based Selection


This is the default mode. This mode appears based on the selection of the user.
In this mode, frames are treated as individual elements. In this mode, frames are treated as a part of the frame
span. In other words, frames adjacent to a keyframe are
selected as a unit.
Table 5.2: Difference between frame-based and span-based selections

It is possible to perform most tasks in either mode. However, you can switch between modes depending on the task to
be performed. To select the desired mode, from the Edit menu, select Preferences. In the dialog box that appears, from
the General category, select the Span Based Selection check box. This will enable the span-based selection mode.
Deselecting the check box disables the selection and activates the frame-based selection.

5.3.4 Editing Keyframes


Keyframes are versatile. They can be modified or edited to suit your requirements. You can also move keyframes by
simply dragging or copying and pasting them on the timeline. Since keyframes are flexible, you can fine-tune your
animations even after they are created.

On placing the playhead on a frame, the content of that frame is displayed on the stage. On selecting a keyframe in the
timeline, all the content on that keyframe is selected. Similarly, on selecting content on the stage, the corresponding
keyframe is selected. In this manner, it is possible to edit the content in a keyframe or the position of the keyframe in
the timeline.
■■ Copy and paste keyframes

To copy and paste keyframes, begin by selecting the desired keyframe. Alternatively, you can drag to select a
range of keyframes. After selecting a range of keyframes, from the Edit menu, select Timeline. Then, select Copy
Frames. The selected frames are copied.

To paste frames, click the specific frame where you want to paste the frames. Then, from the Edit menu, select
Timeline. From the submenu, select Paste Frames.

Alternatively, you can keep the Alt key pressed and drag the keyframe to the location where you want to paste it.
■■ Move a keyframe or frame sequence and its contents

You can move a keyframe or frame sequence along with its contents by dragging the keyframe or the sequence to
its desired location.
■■ Change the length of a static frame sequence

You can change the length of a static frame sequence by keeping the Ctrl key pressed and dragging the beginning
or ending frame of the span either to the left or to the right.

5.3.5 Removing Frames and Keyframes


Based on the task to be performed, you can choose to remove a frame’s status as keyframe or remove the frame
entirely. Clearing a keyframe preserves the length of the frame and the overall duration of the animation on the layer.
It simply turns the keyframe back into a regular frame and removes any changes the keyframe contained. Conversely,
removing frames deletes the entire frame and shortens the length of the animation in the timeline.

To clear keyframes, begin by selecting the keyframe. You can also click and drag to select a range of keyframes. Then,
from the Modify menu, select Timeline. From the submenu that appears, select Clear keyframe. You will notice that
Flash converts the keyframe back into a regular frame. Refer to Figure 5.7.
Figure 5.7: Clear frames

To remove frames, begin by selecting the keyframe. You can also click and drag to select a range of keyframes. Then,
from the Edit menu, select Timeline. From the submenu that appears, select Remove Frames. You will observe that
the selected frame(s) are removed and the length of the animation movie is shortened. Refer to Figure 5.8.

Figure 5.8: Clear frames with shortened duration


Quick Test 5.1

1. Resizing frames help in organizing its contents.


True False

2. The Document Settings dialog box can be accessed from the Modify menu.
True False

3. To convert a frame into a blank keyframe, right-click a keyframe in the Timeline and click Convert to Keyframes.

True False

5.4 Using Onion Skin


In traditional animation, individual frames of a movie were drawn on thin onion skin paper that was placed on a light
source. The animators (mostly inbetweeners) would place the previous and next drawings exactly beneath the drawing
to create the inbetweens. This technique gave drawings a smooth motion.

Today, with the use of computers, a similar effect is achieved using the onion skinning technique. In this technique,
animators make the frames translucent and project them on top of each other to attain a continuous animation. Onion
skinning is a technique used for creating animated cartoons and editing movies to see several frames at once. On using
this technique, the animator or editor can make decisions on how to create or change an image based on the previous
image in the sequence. Refer to Figure 5.9.

Figure 5.9: Onion skinning

To activate the onion skin, click the Onion Skin mode in the Status bar. The onion skin markers appear in the area
above the frame numbers and the selected range of frames appear dimmed. The frames before and after the active
frames appear in varying degrees of shading on the stage; they appear lighter as they move further away from the active
frame. Refer to Figure 5.10.
Figure 5.10: Onion skin mode

5.4.1 Onion Skin Markers Display Option


On activating the onion skin, you can view the frames of an animation in any of the following ways:
¾¾ Onion skin
¾¾ Onion skin outlines
¾¾ Edit multiple frames
Refer to Figure 5.11.

Figure 5.11: Controls of the onion skinning display


5.4.2 Modifying Onion Skin Markers
On using onion skin markers it is possible to adjust the number of frames previewed in the onion skin. This can be done
either by dragging the handles of the onion skin marker manually or by defining the range of markers in the Modify
Onion Markers pop-up window. Refer to Figure 5.12.

Figure 5.12: Modifying onion markers


■■ To set onion skin markers manually

Onion skin markers come with handles that define the beginning and end of the onion skin. These handles appear
as brackets with small dots and can be dragged to adjust the number of frames. To adjust the frames using the
handles, begin by clicking the Onion Skin mode button on the Status bar. If necessary, click the small dot on either
end of the onion skin markers and then drag to include or exclude any consecutive frames in the onion skin.
■■ To set onion skin markers in Modify Onion Markers window

To set the onion skin markers in the Modify Onion Markers window, begin by clicking the Modify Onion Markers
button. The Modify Onion Markers popup window appears with various options. Refer to Table 5.3 to view a
description of the options in the Modify Onion Markers window.

Options Descriptions
Always Show Markers This option keeps the Onion Skin Markers visible in and out of Onion Skin
mode.
Anchor Onion This option maintains the selected frames even if you move the playhead.
Onion 2 This option displays two frames before and after the current frame.
Onion 5 This option shows five frames before and after the current frame.
Onion All This option includes the entire duration of the timeline in the markers.
Table 5.3: Modify Onion Markers options and their descriptions

5.4.3 Edit Multiple Frames

The Edit Multiple Frames mode is useful when you want to make changes to an entire animation or to a series of
frames at once. On enabling this feature, you will see brackets similar to those in the Onion Skin mode. On dragging
these brackets you can select the range of frames that you want to edit.

This feature works best when you want to make changes to your animation at a macro level. For example, if you want to
resize an animation or change its position, you can do so by selecting an entire frame span or layer instead of moving
or resizing content on each frame separately.

To make changes to an entire animation, begin by clicking the Edit Multiple Frames button in the Status bar. Then,
click and drag the markers to include all the frames you want to select. You will notice that all the content in the selected
frames appear on stage.

Next, click the Selection tool on the Tools panel. Then, drag a selection box around the content on the stage. You can
make changes to the location, scale, effects, and other properties of the selected frame(s).

5.5 Creating Simple Frame-by-Frame Animation


Flash incorporates traditional animation techniques along with the use of keyframe-based animation. In this technique,
artwork is placed in a keyframe in the timeline. Then, the remaining keyframes are created to record changes to the
artwork.

To do so, begin by creating an object on the first frame. This will be your first keyframe. Then, change the attributes of
the object in the other frames. On playing the frames consecutively, you will observe that the minute changes mimic the
movements. You will also observe that each keyframe describes an altered position or transform effect.

5.6 Previewing the Animation


In addition to moving the playhead in the timeline to view your animation, Flash provides a controller to navigate the
timeline. Refer to Figure 5.13.

Figure 5.13: Controller

To see your Flash movie in its final state, you can export your Flash document into a Flash movie (.swf file). The final
Flash movie displays all the elements that are not viewable in the Flash Development environment. These elements
include animations contained in movieclip symbols and ActionScript functionality. In order to preview the basic animations
from their own timeline, you can use the controller to preview them. You can also test your animation in Flash player. To
do so, from the Control menu, select Test Movie. From the submenu that appears, select Test. Alternatively, you can
press the Ctrl+Enter keys.

The Test command tests the movie based on the current test option. Flash uses the document type, as the default type,
until you change it. Refer to Figure 5.14. In the Flash Professional test option, Flash exports the entire timeline and any
other scenes you have created into a SWF file that plays in the Flash player.
Figure 5.14: Preview of an animation in Flash player

Scrubbing is the technique of moving the playhead in the Timeline to view your animation.

For detailed step-by-step procedure, refer to demo Frame by Frame Animation from:

eResources 4 Me>> My Varsity>> Web Animation and Interactivity>> Show Me How>> Previewing the Animation

5.7 Shape Tweening


The functioning of shape tweening is very similar to that of motion tweening. The structure of keyframing in the timeline
is also the same for the two types of tweening. However, shape tweening is primarily used for transforming the shape
of an object into another shape.

An object whose shape has to be transformed should be editable. This can be done by selecting the object with the
Selection tool. Shape tweening is a good option when you want to transform the shape of an object gradually and it
works best with simple shapes. On applying shape tween, Flash draws the inbetweens, such that the object appears to
morph between the two states. Following are some points to be noted while applying shape tween:
¾¾ It is best to avoid shapes with negative spaces or contours in them. Keep the shapes simple.
¾¾ Experiment with shapes you want to use to determine the results.
¾¾ Use shape hints that help in determining which points on the beginning shape should correspond to the specific
points on the end shape.

5.7.1 Creating a Shape Tween


Flash draws tweened frames mathematically. The simpler the shape, more accurate the result, and lesser the corrections.
Geometric shapes, such as, lines, rectangles, and circles yield the best results. In most cases, two simple shapes can
be tweened with ease. However, it requires a lot of experimentation. Flash attempts to morph one object into another,
as long as both - the end and start keyframes contain an editable shape.

You can either import vector shapes from another source or create a shape using any of the Drawing tools. You can also
apply a shape tween to a grouped artwork or a symbol. To do so, break apart the group or enter in the Symbol Editing
mode and apply the shape tween to any editable shape in the symbol’s timeline.
■■ Adding and removing keyframes from a Shape tween

Keyframes can be added or removed from a shape tween in the similar manner as that of a motion tween. However,
there is one crucial difference in the process. Unlike a motion tweened framespan, where you can add keyframes
by dragging an object, in shape tweening, it is not possible to add keyframes by selecting and dragging it. To add
additional locations or change shapes, you must first add a keyframe and then edit the shape. This can be done
by selecting the Keyframe command from the Timeline submenu of the Insert menu. On adding a keyframe, the
shape at that point in the keyframe can be edited.
5.7.2 Adjusting Shape Tween Properties
Shape tween properties can be modified using options available in the Properties panel. You can modify the easing
options, and blending preferences. You can also smoothen the tweened shapes using the Distributive option and
preserve corners and straight lines using the Angular option.

5.7.3 Using Shape Hints


At times it is difficult to predict the tweening of complicated shapes. Shape hints come handy in such instances. Shape
hints act as guides while drawing the inbetween frames.

While using shape hints, you can begin by specifying the beginning shape hint followed by the corresponding end shape
hint. In this manner, Flash determines which part of the shape in the first keyframe will transform into which part in the
end keyframe. Shape hints contain letters from a to z that correspond to the starting and ending shapes. You can use
up to 26 shape hints. Shape hints are yellow in a starting keyframe, green in an ending keyframe, and red when not on
a curve.

Enabling shape hints need not derive accurate results. However, this feature gives you great control over the
tweening process of complex shapes.

The following guidelines will help derive best results while tweening shapes:
¾¾ For complex shapes, it is best to create intermediate shapes and tween them instead of just defining a starting
and ending shape.
¾¾ Make sure that shape hints are logical. For example, if you are using three shape hints for a triangle, they must
be in the same order on the original triangle and on the triangle to be tweened. The order cannot be abc in the
first keyframe and acb in the second.
¾¾ Shape hints work best if you place them in counterclockwise order beginning at the top-left corner of the shape.
Perform the following steps to create shapes using shape hints:
¾¾ Begin by selecting a shape on the starting keyframe. Then, from the Modify menu, choose Shape. From the
application menu that appears, click Add Shape Hint.
¾¾ Using the Selection tool, specify a point on your starting shape and move the first hint (a). Position it on an area
of the shape that you want to match up with an area on the final shape.
¾¾ Then, position this hint to define the area of the final shape that should match up with the area specified on the
starting shape.
¾¾ Preview the new in-between shapes by dragging the playhead on the timeline. Continue to add or reposition
hints until Flash renders the in-between shapes correctly.
¾¾ To remove an individual hint, drag it off the stage with the Selection tool.
For detailed step-by-step procedure, refer to demo shape tween from:

eResources 4 Me>> My Varsity>> Web Animation and Interactivity>> Show Me How>> Shape Tweening>> Using
Shape Hints

5.8 Summary
In this session, Frame-by-Frame Animation and Shape Tweening, you learned that:
¾¾ Timeline represents the timing of the animation and forms a vital part of any animation.
¾¾ Layers, frames, and the playhead are the major components of the timeline.
¾¾ A timeline can be moved or docked. The length of the timeline can also be altered.
¾¾ Labeling frames help in organizing content. Labels can be applied only to keyframes.
¾¾ The project frame rate affects the playback of all animations. The frame rate of any animation appears in the
Document Settings dialog box.
¾¾ Frame-by-frame animation is the most basic form of animation that originated in the 2D form of sketching. With
the advent of technology, it was later implemented in digital animation. This kind of artwork is best suited for
complex animations that require subtle changes.
¾¾ In onion skinning, animators make the frames translucent and project them on top of each other to attain a
continuous animation. This technique is used for creating animated cartoons and editing movies to see several
movies at a glance.
¾¾ To see your Flash movie in its final state, you can export your Flash document into a Flash movie (.swf file). The
final Flash movie displays all the elements that are not viewable in the Flash Development environment. These
elements include animations contained in movieclip symbols and ActionScript functionality. The Test command
tests the movie based on the current test option.
¾¾ Shape tweening is used to transform the shape of an object into another object. While applying shape tween,
it is best to avoid shapes with negative spaces or contours in them. Use shape hints that help in determining
which points on the beginning shape should correspond to the specific points on the end shape.

5.9 Exercise
1. Timeline represents the _________ of an animation.

Spacing

Position

Timing

Content

2. How can a user make an animation smoother?

By reducing the frame rate

By increasing the layers

By increasing the frame rate

By testing animation sequences at logical intervals

3. The ___________ and _______________ determines the length of a movie.

Tinting, frame rate

Number of frames, content

Frame rate, object

Number of frames, frame rate

4. Identify the statement that does NOT hold true for onion skinning.

Onion skinning gives drawings a smooth motion.

Onion skinning mode can be activated from the Modify menu.

It is possible to adjust the number or frames using the onion skin markers.

The Onion 2 option displays two frames before and after the current frame.

5. __________ act as guides while drawing inbetween frames.

Shape hints

Shape tween

Motion tween

Scrubbing
S e s s io n 6
Motion Tweening and Classic Tweening
Learning Outcomes
In this session, you will learn to:
¾¾ Explain motion tween and its associated terms
¾¾ Create motion tweens
¾¾ Work in the Motion Editor panel
¾¾ Apply color effects and filters
¾¾ Work with property keyframes, edit the path of a motion tween, and work with motion presets
¾¾ Apply easing to animations
¾¾ Explain classic tween

6.1 Introduction
The frame-by-frame animation technique makes use of a lot of frames even in the most simplest of animation. This
technique, when used in combination with tweening, helps create animations with ease. Tweening defines the start and
end points of an animation, while Flash creates the inbetweens.

Following are the two types of tweening in Flash:


¾¾ Classic tween: This type of tweening, makes use of more than one instance of an object in keyframes along
with property keyframes to create tweens.
¾¾ Motion tween: This type of tweening, makes use of only one instance of an object across the entire span of the
animation along with property keyframes to create tweens.

Refer to Table 6.1 to view differences between classic tween and motion tween.

Motion Tween Classic Tween


Motion tweens are powerful and simple to create. Classic tweens include all tweens created in the earlier
versions of Flash CS6 and are complex to create.
Motion tweens offer more control as compared to classic Classic tweens offer specific controls.
tweens.
Table 6.1: Difference between motion tween and classic tween

Click here to know more about the differences between motion tweens and classic tweens.

6.2 Understanding Motion Tween


Motion tweening is created by defining a value for an object property in one frame and specifying another value for the
same property in another frame. Flash calculates the values for the property in between the two frames.

You will now understand the concept better with the help of this example. Consider placing a movie clip on the left side
of the stage in frame 1 of the timeline. Then, move that movie clip to the right side of the stage till frame 24. On creating
a tween, Flash calculates all the positions of the movie clip on the stage in between the specified positions. You end
up with an animation of the movie clip moving from the left side of the stage to the right side, from frame 1 to frame
24. Motion tweening is used to create smooth motion and transformation effects, such as scale, position, rotation, and
skew. These effects can also be applied to movie clips, graphics, buttons, and text fields. In addition to applying motion
effects, you can also use the advanced color effects in Flash to apply changes to color, alpha, and brightness. In this
type of animation, the file size of the animation is smaller as compared to other types of animations. Refer to Figure 6.1
for an example of motion tweening.
Figure 6.1: Motion tweening

Applying tweening effects to the instances in any animation, does not affect the original symbol placed in the
Library.

■■ Tween span

A group of frames in a timeline in which an object on stage can have more than one property changed over time is
referred to as a tween span. It appears as a group of frames, on a single layer, over a blue background. They can
be selected as a single object and can be dragged from one location to another on the timeline. You can also move
tween spans to another layer. A single object on a stage can be animated in each tween span. This object is referred
to as the target object of the tween span. Refer to Figure 6.2.

Figure 6.2: Motion tweening - Timeline


■■ Property keyframe

A frame within a tween span where you specify more than one property value for the tween target object is referred
to as a property keyframe. Each property you define has its own property keyframe. On defining more than one
property in a single frame, the property keyframes for each of those properties reside in that frame. The properties
of the tween span and its keyframe can be viewed in the Motion Editor panel. You can also define the types of
property keyframes to display in the timeline from the tween span context menu. Going back to the earlier example
of tweening a movie clip from frame 1 to frame 24, you will observe that frames 1 and 24 are property keyframes.

On selecting a tweened space, a tweened object, or a motion path, the Motion Editor panel displays tween property
values in categories and a grid with a graph for each property. Each keyframe for a specific property appears as a
control point on the graph. Control points are of two types – smooth points and corner points.
When the control points are smooth, Bezier handles appear that can be adjusted. Some properties in the Motion
Editor are associated with each other, such as Scale X and Scale Y. You can use the Link icon to constrain values
to match each other.

You can also add a property keyframe to a property curve. To do so, begin by placing the playhead in the desired
frame. Then, click the Add Keyframe button or the Remove Keyframe button for the property in the Motion
Editor panel. Alternatively, you can keep the Ctrl key pressed on the keyboard while you click in the position where
you want to add the property keyframe. In addition, you can also right-click the property curve and choose Add
Keyframe. Refer to Figure 6.3.

Figure 6.3: Property keyframes

You can remove a property keyframe from a property curve at any time. To do so, click the control point for the property
keyframe while keeping the Ctrl key pressed on your keyboard. Alternatively, you can right-click the control point and
select Remove Keyframe.

You can also toggle a control point between the corner point mode and smooth point mode. To do so, click the control
point while keeping the Alt key pressed on the keyboard.

When a control point is in the smooth point mode, its Bezier handles are exposed and the property curve passes through
the point as a smooth curve.

When a control point is a corner point, the property curve forms an angle when it passes through the control point. Bezier
handles are not exposed for corner points. Refer to Figure 6.4.

Figure 6.4: Corner points and smooth points

To set the point to smooth point mode, you can right-click the control point and choose Smooth Point, Smooth Right,
or Smooth Left.

To set the point to corner point mode, choose Corner Point. To move a property keyframe to a different frame, drag its
control point. You cannot drag a property keyframe past the keyframes that follow or precede it. To toggle a property
keyframe for the spatial properties X, Y, and Z between roving and non-roving, right-click the property keyframe in the
Motion Editor panel.

You can also turn off roving for an individual property keyframe in the Motion Editor panel by dragging the roving
keyframe to a vertical frame divider.

To link associated pairs of X and Y properties, click the Link X and Link Y property values button for either one of the
properties you want to link. You will observe that when the properties are linked, their values are constrained such that
the ratio between them is preserved when you enter a value for either of the linked properties. Examples of associated X
and Y properties include the Scale X and Scale Y properties and the Blur X and Blur Y properties of the Drop Shadow
filter.

6.2.1 Creating a Motion Tween and Adjusting its Properties


In motion tween animation, you can tween the position, scale, rotation, and other transformation effects applied to
symbol instances and text fields. This type of animation uses a single instance over the entire span along with property
keyframes that you define with property values to modify the tween.

You can alter the property keyframes on the stage either by modifying values in the Properties panel or through the
Motion Editor panel. On modifying values, ensure there is only one object available when applying the tween, else the
results will be unpredictable. Tweened frames must reside on the same layer in the Timeline. After adding a tween to a
layer, Flash changes it to a tween layer, which you can no longer draw on. A tween layer can contain tween spans, static
frames, and actions.

Click here to view videos and articles that demonstrate the use of the Motion Editor.
■■ Creating a motion tween

To create a motion tween, begin by selecting a symbol instance or a text field to tween on the stage. Then, from the
Insert menu choose Motion Tween. Alternatively, you can right-click the selection on the stage and choose Create
Motion tween from the context menu. Next, define the length of the animation by dragging either ends of the tween
span. Incase if you want to specify another position for the object, then place the playhead in another frame within
the tween span and drag the object on the stage to another position. You will now add motion to the tween. To do
so, click a frame within the tween span and move the object on the stage. You can tween the 3D rotation or position
by using the 3D Rotation or 3D Translation tool.
■■ Adjusting motion tween properties

Changes can be made to motion tweens in the Properties panel or in the Motion Editor. When a tweened span is
selected, a number of options are enabled that you use to add complexity to your motion path. You can set motion
tween properties to deal with position and size, set rotation direction and frequency, apply color and display blending
effects, or control the easing in or out of the motion. Refer to Figure 6.5.

Figure 6.5: Tween span Properties panel


The options defined in the Properties panel are applied to the entire tween span. These options can be used to refine
the animation after you have your basic motion tween working. Refer to Table 6.2 to view the options available in the
Properties panel on selecting a tween span.

Options Descriptions
Ease This option is used to set the speed in and out.
Rotation This option sets the direction and frequency of the rotation
of the object. You can keep your object parallel to the
guide relative to its center point by selecting the Orient
To Path check box.
Path Sets the X and Y position, and the selection width and
height.
Table 6.2: Options available in the Properties panel on selecting a tween span

Refer to Table 6.3 to view the options available in the Properties panel on selecting a tween object.

Options Descriptions
Position and Size Sets the X and Y position, and the selection width and
height.
3D Position and View Sets the 3D X, Y, and Z positions, 3D perspective selection
width and height, perspective angle, and vanishing points.
Color Effect Sets the color style effect: Brightness, Tint, Alpha, or
Advanced.
Display Sets the display blending effect, which includes Darken,
Overlay, and Invert.
Table 6.3: Options available in the Properties panel on selecting a tween object

6.2.2 Understanding the Motion Editor


The Motion Editor panel displays the tween properties and their property keyframes. It is possible to edit the properties
using this panel. It provides tools and adds precision and details to the tweens. Properties of the currently selected
tween are displayed in the Motion Editor. On creating a tween in the Timeline, the Motion Editor allows you to control
the tween in several ways. On clicking the Window menu, the Motion Editor panel appears beside the Timeline. On
selecting a tween space, tweened object, or motion path, the Motion Editor panel displays the tween property values
in categories and a grid with a graph for each property. Refer to Figure 6.6.

Figure 6.6: Motion Editor

Using the Motion Editor, you can:


¾¾ Set values of individual property keyframes.
¾¾ Add, remove, or move property keyframes for individual properties to different frames within the tween.
¾¾ Copy a property curve from one location and paste it into another. Reverse and reset the keyframes for individual
properties or categories of properties.
¾¾ Use Bezier controls to exercise control over the shape of the tween curves of most individual properties.
¾¾ Add or remove filters or color effects and adjust their settings.
¾¾ Create custom ease curves and add custom easing to individual tweened properties and groups of properties.
¾¾ Enable roving for individual property keyframes for X, Y, and Z properties. These properties do not have Bezier
controls.

6.2.3 Editing Motion Tween Properties


The Motion Editor panel allows you to view and edit all tween properties and related keyframe properties. The basic
motion of the tween can be changed by altering the values of the X, Y, and Z axes transforming the skew and scale,
applying color and filter effects, or by adding the ease in or ease out effect.
■■ Changing the Motion Editor display

To change the display of the Motion Editor, begin by selecting an object on the stage. Then, from the Window
menu choose Motion Editor. Refer to Figure 6.7.

Figure 6.7: Motion Editor display

You can change the display of the motion editor by changing any of the following options:
¾¾ Display Properties: You can change the properties by clicking the triangle beside the property category.
¾¾ Expand/Collapse Property view: Using this option you can toggle between the property names.
¾¾ Viewable Frames: Using this option you can set the number of frame of a tween shown in the Motion Editor.
¾¾ Graph Size: Using this option, you can define the size of the graph.
¾¾ Expanded Graph Size: Using this option, you can set the expanded property view size of the graph.
¾¾ Add Eases Options: Adds an ease option to menus in the Motion Editor. Click the Add button on the Eases
category, and then select an ease option.
■■ Setting the motion tween properties in the Motion Editor
¾¾ The following options are available to set the motion tween:
●● Basic Motion: This section groups the X, Y, and Z (rotation) values for the target object. A target object is
always accompanied by the X, Y, and Z values. Since these properties are related, their property keyframes
have to match up.

●● Transformation: This section groups the Skew and Scale properties for the X and Y axis of the target
object. Any differences in size or skew between the target object in the initial keyframe and the last property
keyframe of a tween span can be interpolated at different rates.

●● Color Effect: Color changes can be controlled from one property keyframe to another in a tween by editing
the tween curve. Color effects can be added to a target symbol either by using the submenu in the Motion
Editor or by using the settings in the Properties panel.

●● Filters: On applying filters to create changes in an item’s appearance in the span of a tween, the pattern
of change can be adjusted with custom easing. Filters can be added to a target symbol from the submenu
either using the Motion Editor panel or using the Properties panel.

6.2.4 Color Effects and Filters


Timeline effects add life to any animation. Effects can be added by using filters in the Motion Editor. Filters like Drop
Shadow, Blur, Glow, Bevel, Gradient Glow, Gradient Bevel, and Adjust Color can be added to a Motion tween. You
can also add color effects, such as Alpha, Brightness, Tint, and Advanced Color, to a Motion tween.

More than one effect or filter can be applied to an object to create a different effect. You also have the option of changing
or removing the applied color effect if it does not meet your requirement.
■■ Adding color effects and filters to a motion tween

To add color effects and filters to a motion tween, begin by selecting an object on the stage with a tween applied.
Then, in the Motion Editor panel, click the triangle to expand the Color Effect or Filters category.
¾¾ To apply color effects, click the Add button on the Color Effect category. Then, from the list of options, you can
choose from Alpha, Brightness, Tint, and Advanced Color. Refer to Figure 6.8.

Figure 6.8: Color effect


¾¾ To apply filters, click the Add button from the Filters category. Then, from the list of options, you can choose
from Drop Shadow, Blur, Glow, Bevel, Gradient Glow, Gradient Bevel, and Adjust Color. Refer to Figure
6.9.

Figure 6.9: Filter effect


¾¾ To remove the color effect or filter, click the Remove button from the Color Effect or Filter category. Then,
select the effect or filter that you want to remove. You can also reset the default values by clicking the Reset
Values button.

6.2.5 Editing the Path of a Motion Tween


It is possible to edit or change the path of a motion tween in any of the following ways:

¾¾ Editing the shape of a motion path with the Selection and Subselection tools. Refer to Figures 6.10 and 6.11.

Figure 6.10: Motion path


Figure 6.11: Orient to path

¾¾ Changing the position of the tweened object. Refer to Figure 6.12.

Figure 6.12: Edit motion path


¾¾ Changing the location of a motion path on the stage.
¾¾ Editing a motion path with the Free Transform tool.
¾¾ Deleting a motion path from a tween.
¾¾ Using roving property keyframes. Refer to Figures 6.13 and 6.14.
Figure 6.13: Roving keyframes

Figure 6.14: Roving option in the Motion Editor panel

Click here to know more about editing the path of a motion tween.

6.2.6 Ease In and Ease Out


Easing is a technique that helps create realistic animations by manipulating the speed of the animation, either at the
beginning or at the end. This technique modifies the way Flash calculates property values in between property keyframes
in a tween.

You can apply easing either in the Property Inspector window or in the Motion Editor. On applying easing in the
Property panel, it affects all the properties that are included in a tween. However, on applying easing in the Motion
Editor, it can affect a single property, a group of properties, or all properties of a tween. Refer to Figure 6.15.

Figure 6.15: Ease Properties panel


Click here to know more about Ease In and Ease Out.

6.2.7 Motion Tween Presets


Readymade motion tweens that can be applied to an object on the stage are referred to as motion presets. You can
preview motion tweens in the Motion Presets panel and also apply it on the stage with ease. Only one motion preset
per object can be applied on the stage. Each motion preset is associated with a specific number of frames that can be
adjusted later using the Motion Editor panel.

Using the Motion Presets panel, you can not only create and save your own custom motion presets but also import and
export them and later share them with other tweens. These presets that are imported or exported are stored as XML
files.
■■ Applying a motion tween

To apply a motion tween preset, begin by selecting a tweenable object on the stage. Then from the Window menu,
select Motion Presets to open the Motion Presets panel. On selecting a preset from the panel, a preview of the
same appears on the top of the panel in the Preview pane. You can apply the preset by clicking Apply. On the other
hand, incase if you do not want to apply the preset and close the preview pane, you can simply click outside the
Motion Presets panel. Refer to Figure 6.16.

Figure 6.16: Ease Properties panel

Incase if you are applying a preset to a non-tweenable object, a dialog box appears confirming if you want to convert it
to a symbol. On doing so, the motion is set to start at the current position of the object on the stage. To apply the preset
so that the motion ends at the current position of the object on stage, click Apply, while you keep the Shift key pressed.
■■ Saving a tween as a custom motion preset

Select the tween span, or object, or motion path on the stage along with the custom tween that you want to save as
a preset. In the Motion Presets panel, click the Save Selection As Preset (icon) button. You will be prompted to
enter a name for the preset. Enter a name for the preset in the space provided and click OK. The new preset appears
in the Motion Presets panel under Custom Presets and will be saved as an XML file in the Motion Presets folder.
■■ Importing a motion preset

Motion presets are stored as XML files that can be imported and stored in the Motion Presets panel. To do so, from
the Motion Presets panel menu, click Import. In the Open dialog box that appears, navigate to the XML file that
has to be imported and click Open. Flash CS6 opens the XML file and adds it to the Motion Presets panel.
■■ Exporting a motion preset

Select the preset to be exported from the Motion Presets panel. Then, click Export. In the Save As dialog box that
appears, enter a name for the XML file and choose a location. Then, click Save.
■■ Deleting a motion preset

It is possible to remove presets from the Motion Presets panel. On removing a preset, Flash CS6 deletes its XML
file from the disk. It is possible to delete a preset either by clicking Remove from the Motion Presets panel menu
or by clicking the Remove Item button from the panel.

For detailed step-by-step procedure, refer to demo Classic Motion from:

eResources 4 Me>> My Varsity>> Web Animation and Interactivity>> Show Me How>> Motion Tween Presets>>
Deleting a motion preset

Quick Test 6.1


1. Classic tweens are less complicated than motion tweens.
True False

2. Each property that a user defines has its own property keyframe.
True False

3. Roving controls the shape of the tween curves of most of the individual properties.
True False

6.3 Understanding Classic Tween


Classic tweens are the age-old way of creating animations in Flash. Motion tweening is a recent concept that has
evolved with the advancement of technology and is less complicated and more flexible as compared to classic tween.

However, classic tween provides better control in some aspects as compared to Motion tween. This makes it the
preferred choice among animators.

6.3.1 Create and Edit Keyframes for Classic Tween Animation


In classic tween animation, keyframes are defined at significant points. The in between frames of a tweened animation
appear as light blue or light green with an arrow drawn between frames.

It is advisable to create keyframes only at points where changes are expected to occur. This is because Flash documents
save the shapes in each keyframe.

Keyframes are indicated in the Timeline. A solid circle represents a keyframe with content on it; whereas, an empty circle
before the frame represents an empty keyframe. Succeeding frames added to the same layer have the same content
as the keyframe.

In a classic tween, it is possible to view tweened frames but they cannot be edited directly.

It is possible to edit tweened frames, either by changing one of the defining keyframes or by inserting a new keyframe
between the beginning and ending keyframes. Dragging items from the Library panel onto the stage adds the items to
the current keyframe.

Onion skinning is another technique that can be used to display and edit more than one frame at a time.
■■ Creating a classic tween animation

To create a classic tween animation, begin by defining keyframes and objects on the beginning and ending keyframes.

Click here to know more about classic tween.

For detailed step-by-step procedure, refer to demo Classic Tween from:

eResources 4 Me>> My Varsity>> Web Animation and Interactivity>> Show Me How>> Understanding Classic
Tween>> Creating a classic tween animation
6.3.2 Creating a Motion Guide Layer
A motion guide layer controls the movement of objects in an animation. It is not possible to drag a motion tween layer or
inverse kinematics pose layer onto a guide layer. To create a motion guide layer, drag a normal layer onto a guide layer.
This converts the guide layer and links the normal layer to the new motion guide layer.

It is best to place all guide layers at the bottom of the layer order inorder to avoid an accidental conversion of a guide
layer.
6.3.3 Creating Classic Tween Animation Along a Path
It is possible to draw paths using motion guide layers along which tweened instances, groups, or text blocks can be
animated. It is also possible to link multiple layers to a motion guide layer to have multiple objects follow the same path.
A normal layer that is linked to a motion guide layer becomes a guided layer.

6.3.4 Applying Custom Ease in/Ease out to Classic Tween Animation


The Custom Ease In/Ease Out dialog box displays a graph representing the degree of motion over time. The X-axis
represents frames and the Y-axis represents the percentage of change. The first keyframe is represented as 0%, and
the last keyframe is represented as 100%.

The rate of change of the object is represented by the slope of the curve. When there is no curve (the curve is horizontal),
the velocity is zero; when the curve is vertical, an instantaneous rate of change occurs.

6.4 Summary
In this session, Motion tweening and Classic Tweening, you learned that:
¾¾ Classic tweening and motion tweening are the two types of animations in Flash. Classic tween makes use of
more than one instance of an object; whereas, motion tween makes use of only one instance of an object to
create tweens.
¾¾ Motion tweening is created by defining a value for an object property in one frame and specifying another value
for the same object in another frame.
¾¾ Tween span is a group of frames in a Timeline in which an object on stage can have more than one property
changed over time.
¾¾ A frame within a tween span where you specify more than one property value for the tween target object is
referred to as a property keyframe.
¾¾ Motion tween animation uses a single instance over the entire span along with property keyframes that you
define with property values to modify the tween.
¾¾ The Motion Editor panel displays the tween properties and their property keyframes. It is possible to edit the
properties using this panel.
¾¾ Timeline effects add life to any animation. Effects can be added by using filters in the Motion Editor panel.
¾¾ Easing is a technique that helps create realistic animations by manipulating the speed of the animation, either
at the beginning or at the end. This technique modifies the way Flash calculates property values in between
property keyframes in a tween.
¾¾ Readymade motion tweens that can be applied to an object on stage are referred to as motion presets. Each
preset is associated with a specific number of frames and only one preset per object can be applied on the
stage.
¾¾ Classic tween is the age-old way of creating animations in Flash. This type of animation is more complicated
and less flexible as compared to motion tween.
¾¾ Motion guide layers are used to control the movements of objects in a classic tween animation.
6.5 Exercise
1. A group of frames on a single layer with more than one property changed over time is referred to as ___________.

Property keyframe

Tween span

Classic tween

Timeline

2. The ___________ displays the properties of the currently selected tween.

Motion Editor

Bezier controls

Graph Size option

Transformation effect

3. Easing cannot be applied in the Motion Editor panel.

True

False

4. Each motion preset is associated with a specific number of frames that can be adjusted later using the ___________
panel.

Motion presets

Motion Editor

Motion tween

Custom presets

5. D
ragging a normal layer onto a guide layer converts the normal layer and links the guide layer to a new motion guide
layer.

True

False
Session 7
Working with Audio and Video
Learning Outcomes
In this session, you will learn to:
¾¾ Import videos using the Import Video Wizard
¾¾ Describe the various components used to import videos
¾¾ Work with sound

7.1 Working with Videos


Videos that are imported into Flash can be managed and played using playback controls. Flash supports most of the
video file formats, including QuickTime, Windows Media, and Moving Pictures Experts Groups (MPEG) clips. Refer to
Table 7.1 that shows the ways to use videos in Flash.

Ways Description
Progressive download from a This is the most commonly used method for using videos in Flash. In this method,
Web server video files are external to Flash and the size of SWF file is comparatively small.
Stream video using Adobe Adobe Flash Media Server not only secures the video content but also gives a
Flash Media server smooth streaming playback experience. Video files are external to the main file.
Embed video directly inside a This method is commonly used for short video clips as the sizes of the Flash files
Flash file are very large.
Table 7.1: Ways to use videos in Flash

Click here to know more about the ways videos are used in Flash.

7.1.1 Import Video Wizard


The Import Video Wizard
helps through the process of
importing video files into Flash.
On importing video, the wizard
allows importing of a clip and
uses it in any of the formats.
The wizard also guides through
the steps for the deployment
process. During the import
process, for some methods,
the wizard provides with the
option of compressing videos
using user-defined encoding
profiles. Here, the cue points
can be set and videos can be
trimmed of excess footage.

Additionally, user can decide


to accept the Wizard’s
recommendations or make
changes. Movie playback
controls can also be attached,
which come with different skins.
Figure 7.1: Import Video Wizard
For this, the Wizard uses the
Skinning component. A basic
level of configuration is associated with the import and playback method, which can be chosen in the Wizard. However,
these settings can be modified later to match with the user’s requirements. Refer to Figure 7.1.

Refer to Table 7.2 that shows the ways to import videos using the Import Video dialog box.

Options Description
Load external video with This option imports video and creates an instance of the FLVPlayback component.
Playback component This component is used to control the video playback. When the resultant SWF file
is ready to be uploaded on the Web server or the Flash Media Server, the video file
also has to be uploaded to the specific server and the FLVPlayback component
should be configured with the location of the video file.
Embed FLV or F4V in SWF and This option embeds the FLV or F4V in the Timeline where the individual video frames
play in Timeline can be viewed. Thus, the embedded file becomes a part of the Flash document.
Import as mobile device video In this option, a video is bundled into a Flash lite document. This video is then
bundled in SWF deployed to a mobile device.
Table 7.2: Ways to import videos using the Import Video dialog box

To import videos, first select a video clip that has to be imported, followed by choosing a skin for its display. This video
clip can be selected either from the location in the computer or from the list of videos that are already uploaded to the
Web server or Flash Media Server. Then, select the Load external video with playback component to import video
that is located on the computer. Otherwise, select either the Already deployed to a Web server option, or the Flash
Video Streaming Service option, or the Stream from Flash Media Server option, and then enter the URL of the video
clip in the space provided.

During the import process, the user will be prompted to choose a skin for the video clip. At this stage, either the None
option can be chosen, which indicates that no skin is to be applied, or any of the predefined FLVPlayback component
skin can be chosen. Additionally, a custom skin can also be created, and its URL can be entered on the Web server.
Refer to Figure 7.2.

Figure 7.2: Skinning options


Refer to Figure 7.3. Steps to import videos using the Import Video Wizard are as follows:

Figure 7.3: Steps to import videos using the Import Video Wizard

Irrespective of how a video is imported on Stage, Flash stores a copy of it in the active document Library. However, it is
advisable to import video files first into the Library so as to have better control on its import and its placing on the Stage.
Once imported into the Library, it can be dragged and dropped on the Stage with ease.

It is also advisable to convert the video into a movie clip and then drag it on the Stage. This gives better control
of both the Timelines — namely, the Timeline on Stage and the Timeline of the movie clip.

For detailed step-by-step procedure, refer to demo Import Video from:

eResources 4 Me>> My Varsity>> Web Animation and Interactivity>> Show Me How>> Working with Videos>> Import
Video Wizard

7.1.2 Video Formats and Flash


Apart from the Adobe FLV video format, both Flash Player and Adobe AIR support video and audio that is encoded in
H.264 and HE-AAC from MPEG-4 file formats. These formats deliver high quality video at lower bit rates. The developers
can also control standard tools, such as Adobe Premiere Pro and Adobe After Effects, for creating and delivering
credible content.

Flash Player 7 supports the Sorenson™ Spark™ video codec encoded FLV files. Whereas, Flash Player 8 supports FLV
files encoded with Sorenson Spark or On2 VP6 encoder in Flash Professional 8. The On2 VP6 video codec supports
an alpha channel.

Flash Player 9 and its later versions support files derived from the standard MPEG-4 container format. These include
F4V, MP4, M4A, MOV, MP4V, 3GP, and 3G2, if they contain H.264 video or HE-AAC v2 encoded audio, or both. The
H.264 streams better quality video at lower bit rates when compared to the same encoding profile in Sorenson or On2.

HE-AAC v2 is an extension of AAC, a standard audio format defined in the MPEG-4 video standard. It uses Spectral
Band Replication (SBR) and Parametric Stereo (PS) techniques to increase coding efficiency at lower bit rates.

7.1.3 Working with Video on Stage


On importing a video on Stage, the playback controls can be used to play and work with it. The property settings, such
as size and position, alignment, skin, volume, autoplay, and cue points can be changed through the Properties panel.
However, the video properties in the Component Inspector panel appearing in the Parameters tab cannot be used for
making changes in the video. Refer to Figure 7.4.
Figure 7.4: Options available in the Properties panel

Refer to Table 7.3.

Options Description
Align It specifies the FLV file alignment in the player.
Autoplay It is selected or deselected for automatically playing the FLV file.
Cue points It specifies a string with cue points for the video.
isLive It is selected or deselected if the FLV file is streaming live.
Preview It creates a preview for authoring purposes.
ScaleMode It scales the video using options such as, maintainAspectRatio, noScale, or exactFit.
Skin It selects a skin for the FLV video player.
SkinAutoHide It is selected or deselected for automatically hiding or showing the video skin.
SkinBackgroundAlpha It specifies a background alpha channel for the skin.
SkinBackgroundColor It specifies a background color for the skin.
Source It specifies the path to the video source file.
Volume It specifies a volume setting for the video.
Table 7.3: Options in the Properties panel with description

Placing the video inside a movie clip gives more control over the content. This is because the video’s Timeline
plays independently from the main Timeline. The main Timeline need not be extended by frames to accommodate
the video, which otherwise makes working with the FLA file difficult.

7.1.4 Import Video Files into Library


Import or Import To Library commands or the Import button in the Video Properties dialog box can be used to import
files in the FLV or F4V format.

In order to create a customized video player that dynamically loads FLV or F4V files from an external source, place the
video inside a movie clip symbol. When an FLV or F4V file is loaded, adjust the movie clip’s dimensions to match with
the actual video file’s dimension, and scale the video by scaling the movie clip.

To import an FLV or F4V file into the Library, anyone of the following can be opted:
¾¾ Select File, then click Import, and then select Import To Library.
¾¾ Select any existing video clip from the Library Panel, and select Properties from the Library Panel menu.
Click Import option. Locate the file to import, and click Open.

7.1.5 Change the Properties of a Video Clip


The properties can be changed for an instance of an embedded video clip on the Stage by assigning it with an instance
name, values of width, height, and position on the Stage using the Property inspector. An instance of a video clip
can be swapped by assigning a different symbol to an instance of a video clip. When a different symbol to an instance
is assigned, a different instance is displayed on the Stage but the other instance properties, such as dimensions and
registration point remain intact.

The following actions can be performed using the Video Properties dialog box:
¾¾ View information about an imported video clip
¾¾ Change the video clip’s name
¾¾ Update video clip if it is modified with an external editor
¾¾ Import an FLV or F4V file to replace the selected clip
¾¾ Export a video clip as an FLV or F4V file

7.1.6 Adding Cue Points


Cue points refer to markers within a video clip that are used to trigger different segments. The two kinds of cue points
that can be worked within Flash are as follows:
¾¾ Encoded cue points: These are added while encoding video with Adobe Media Encoder.
¾¾ ActionScript cue points: These are added to a video through the Properties panel. They are accessible only
in Flash and Flash Player.
■■ Working with cue points in the Properties panel

First, select the video on the Stage. Then, from the Properties panel, click to expand the Cue Point section. Under
this section, the following actions can be performed:
¾¾ Adding of an ActionScript cue point by clicking the Add (+) button.
¾¾ Deleting an existing ActionScript cue point by clicking the Delete (-) button.
¾¾ Specifying the time by increasing or decreasing the timecode, either by dragging the mouse cursor or by
entering a value in the space provided.
¾¾ Importing and exporting an ActionScript cue point list in the XML format using the Import ActionScript Cue
Point button and Export ActionScript Cue Point button. While importing cue points, a dialog box displays the
number of ActionScript cue points imported and while exporting, it exports all the Navigation and Event cue
points that are embedded in the video along with all the ActionScript cue points that have been added.

In addition to this, parameters of a cue point can be added and renamed from the Parameters section of the
Properties panel. To add a parameter, select the ActionScript cue point and click the Add (+) button at the bottom
of the Parameters section. To rename a parameter, click in the Name field and enter a new name for the parameter.
Refer to Figure 7.5.
Figure 7.5: Properties panel

7.1.7 FLVPlayback Component


Another alternative to importing external FLV files in Flash Player is to dynamically play them using the FLVPlayback
component. The FLVPlayback component is the display area where the video is viewed. It is made up of a customizable
skin with playback controls.

A movie can be exported as a FLV file from Flash or a video editing program using the FLV Export plug-in and then the
FLVPlayback component in Flash can be used to play it back. In order to include closed captioning, which is the World
Wide Web Consortium (W3C) standard XML format Timed Text, the FLVPlayback Captioning component can be used.
Refer to Figure 7.6.

Figure 7.6: Working with FLVPlayback component


Following steps can be performed:

1. From the Window menu, click Components to open the Components panel. Under the Video section, drag the
FLVPlayback component on the Stage and then select the component. Refer to Figure 7.7.

Figure 7.7: FLVPlayback components dragged on Stage from the Components panel

2. Next, open the FLV video file that has to be used. To do so, from the Properties panel, click the Edit Source button.
The Content Path dialog box appears. Click the Browse Folder icon. Then, navigate to select the FLV video file
and click Open. Refer to Figure 7.8.

Figure 7.8: Content Path dialog box and the Edit Source button

3. The Match source dimensions check box will be activated once the FLV video file is selected. Select the check
box to use the same video size as the file. Click OK. Any further changes to the properties of the video file, can be
made using the Properties panel. Once done, the movie can be tested by pressing the Ctrl+Enter keys.
For detailed step-by-step procedure, refer to demo FLVPlayback Component from:

eResources 4 Me>> My Varsity>> Web Animation and Interactivity>> Show Me How>> Working with Videos>>
FLVPlayback Component

Click here to know more about FLVPlayback Component.

Quick Test 7.1


1. Irrespective of how a video is imported on Stage, Flash stores a copy of it in the active document library.
True False

2. Another alternative to importing external FLV files in Flash Player is to dynamically play them using the
____________.
FLVPlayback Component Import Video Wizard FLVPlayback Captioning Parameters

7.2 Working with Sound


Adobe® Flash® Professional exhibits a number of ways to use sound. This can be by playing sounds continuously, or
independent of the Timeline, or the Timeline can be used to match animation to a sound track. Sounds can be added
to buttons to make them more interactive, and these sounds can be tuned with animation for delivering a more refined
sound track.

A well-designed sound can add a whole new depth to an animation. However, as sound files are big and take more time
to download, options need to be selected depending upon the final mode of delivery. If the animation has to be played on
a Website, Flash offers different options for managing the download time. However, while adjusting the Sound option,
a generalized assumption of the audience and their devices need to be taken into consideration.

7.2.1 Sound Categories and Supported Sound File Formats


Flash offers four options to synchronize sound with the animation. They are event, stream, start, and stop. Sounds can
be used in shared libraries, or to link a sound from one Library to multiple movies. They can be used in sound objects
to control sound playback with ActionScript. If Flash Professional content is being created for mobile devices, it allows
including device sounds in the published SWF file. These device sounds are encoded in the natively supported audio
format, such as MIDI, MFi, or SMAF. All sounds in Flash, whether music or sound effects, fall into two categories —
namely: Event Sounds and Stream Sounds.
¾¾ Event Sounds: Event sounds synchronize sound to the occurrence of an event. It must be downloaded
completely before it begins to play, and it continues to play until stopped.
¾¾ Stream Sounds: Stream sounds synchronize sound for playing on a Website. They begin to play as soon as
enough data for the first few frames has been downloaded. Stream sounds are synchronized with the Timeline
for playing on the Web.

Sounds can be compressed effectively as graphics and animation files. Macromedia recommends an optimal setting
of 22 KHz with mono sounds in Flash. If mono is used, the file is cut to half the size as only a single sound channel is
used instead of two.

Following sound file formats can be imported into Flash Professional:


¾¾ Adobe Sound (ASND) (Windows or Macintosh). This is the native sound format of Adobe® Soundbooth™.
¾¾ Waveform (WAV) (Windows only)
¾¾ Apple Interchange File Format (AIFF) (Macintosh only)
¾¾ Moving Picture Experts Group - Audio layer 3 (MP3) (Windows or Macintosh)

If QuickTime® 4 or later versions are installed on the system, following additional sound file formats have to be installed:
¾¾ AIFF (Windows or Macintosh)
¾¾ Sound Designer® II (Macintosh only)
¾¾ Sound Only QuickTime Movies (Windows or Macintosh)
¾¾ Sun AU (Windows or Macintosh)
¾¾ System 7 Sounds (Macintosh only)
¾¾ WAV (Windows or Macintosh)
7.2.2 Importing Sound Clips into the Library and Setting Properties
To import sounds in Flash, from the File menu, select Import. From the sub-menu that appears, select the Import
to Stage command or Import to Library command. When sounds are imported, they are placed in the Library. Each
sound can be heard immediately by selecting sound in the Library and pressing the Play button in the preview window.
Moreover, multiple instances of sound clip can be dragged on the Stage without affecting the file size. Refer to Figure
7.9.

Figure 7.9: Library panel displaying the sound in the Preview mode
■■ Sound properties

After importing a sound, the sound statistics can be checked and also the compression settings can be set.
Compression is always a choice between sound quality and file size. High quality sound can increase the file size to
a great extent. Hence, every effort should be made to compress the sound. Refer to Figure 7.10.
Figure 7.10: Properties panel displaying the sound properties

Flash offers two ways to compress a sound:


¾¾ Use the Publish Settings dialog box to specify the compression settings for sounds in a movie. If there is one
sound or a couple of sounds, use the publish settings to apply the same compression settings for all sounds in
a movie.
¾¾ If different compression settings have to be specified for each sound, use the Sound Properties dialog box
from the Library panel. Refer to Figure 7.11.

Figure 7.11: Sound Properties dialog box

7.2.3 Add Sound to the Timeline


Sound can be added to a document using the Library, or it can be loaded into a SWF file during runtime, using the
loadSound method of the Sound object. Following steps can be used:

1. Import the sound into the Library if not already imported.


2. Select Insert, and then click Timeline, and then select Layer.

3. After the new sound layer is selected, drag the sound from the Library panel onto the Stage. This adds the current
layer.

4. In the Timeline, select the first frame that contains the sound file.

5. Select Window and in that click Properties, and click the arrow in the lower-right corner to expand the Property
inspector.

6. In the Property inspector, select the sound file from the Sound pop-up menu.

7. Select an effect option from the Effects pop-up menu. Refer to Figure 7.12.

Figure 7.12: Properties panel

Refer to Table 7.4.

Effects Description
None It applies no effects to the sound file. Select this option to remove previously
applied effects.
Left Channel/Right Channel It plays sound in the left or right channel only.
Fade Left To Right/Fade Right To Left It shifts the sound from one channel to the other.
Fade In It gradually increases the volume of a sound over its duration.
Fade Out It gradually decreases the volume of a sound over its duration.
Custom It creates custom in and out points of sound using the Edit Envelope.
Table 7.4: Effects available in the Effect drop-down menu

8. Select any one of the synchronization options from the Sync pop-up menu.

9. Enter a value for Repeat, which will specify the number of times the sound should loop, or select Loop to repeat
the sound continuously.

10. To test the sound, drag the playhead over the frames containing the sound or use commands in the Controller or
the Control menu.

Click here to know more about the synchronization options available in the Sync pop-up menu.
7.2.4 Remove a Sound from the Timeline
In the Timeline layer containing the sound, select a frame that contains the sound. In the Property inspector, move to
the Sound section and select None from the Name menu. This makes Flash delete the sound from the Timeline layer.

7.2.5 Adding Sound in Symbols


In Flash, sounds can be placed in movies and buttons. A button can be created that plays a sound when pressed or
released. Likewise, sounds can be started or stopped by keyframes.

Any animation can be made lively with a sound clip. Like graphics, sound file instances can be inserted into frames on
the Timeline and used throughout the movie. Sounds are represented by waveforms in Flash frames. Flash organizes
movie by allowing to place sounds in another layer. This makes it easier to find sound files quickly and edit them as
needed. Flash also allows multiple sound layers in a movie.

When a sound clip is dragged from the library on the Stage, there is no visual representation of the sound.
Instead, a waveform image of vertical lines representing the digital sampling of the sound appears in the
Timeline.

7.2.6 Synchronizing Sound with Animation


For synchronizing sound with animation, the following steps can be used:

1. Add a sound to the Timeline in its own layer.

2. To synchronize this sound with that of event in the scene, a beginning keyframe should be created for the sound.
This sound should match to the keyframe of the event in the scene to which sound has to be triggered. Then, select
any of the synchronization options.

3. Create a keyframe in the sound layer’s Timeline at the frame where the sound has to be ended. A representation of
the sound file appears in the Timeline.

4. Select Window and in that click Properties, and click the arrow in the lower-right corner to expand the Property
inspector.

5. In the Property inspector, select the same sound from the Sound pop-up menu.

6. From the Property inspector, select Stop from the Sync pop-up menu. When the SWF file is played, the sound
stops playing when it reaches the ending keyframe.

7. To play the sound back, drag the playhead in the Timeline.

7.2.7 Editing Sound


After placing a sound clip, it can be edited by fine-tuning the settings. For example, define the starting point of a sound or
control the volume of the sound as it plays, using the sound-editing controls in the Properties panel. Flash can change
the points at which a sound starts and stops playing. This is useful for making sound files smaller by removing unused
sections. Following steps can be implemented for editing sound:

1. Add sound to a frame, or select a frame that already contains a sound.

2. Click the Edit button on the right side of the Property inspector, the Edit Envelope dialog box appears. Refer to
Figure 7.13.
Figure 7.13: Edit Envelope dialog box

3. Then, any of the following can be opted:


¾¾ To change the starting and ending points of a sound, drag the Time In and Time Out controls in the Edit
Envelope.
¾¾ To change the sound envelope, drag the handles of the envelope to change levels at different points in the
sound. Envelope lines show the volume of the sound as it plays. To create additional envelope handles, which
comes up to eight in total, click the envelope lines. To remove an envelope handle, it can be dragged out of the
window.
¾¾ Click the Zoom In or Zoom Out buttons to display more or less of the sound in the window.
¾¾ To switch the units between seconds and frames, click the Seconds and Frames buttons.
¾¾ To hear the edited sound, click the Play button.
7.2.8 Finding and Replacing a Sound
Find and Replace is a feature which is used to find and replace text, font, color, symbol, sound, and video in a document
or a current scene. Find and Replace elements of the same type can be found for, such as sound with sound, text with
text, and color with color.

To find and replace sound clips, from the Edit menu, select Find and Replace. Alternatively, press the Ctrl+F keys. In
the dialog box that appears, select Sound from the For drop-down list. Then, select the desired files to find and replace
in the Name drop-down list. Refer to Figure 7.14.
Figure 7.14: Find and Replace tab

For detailed step-by-step procedure, refer to demo Working with Sound from:

eResources 4 Me>> My Varsity>> Web Animation and Interactivity>> Show Me How>> Working with Sound>> Finding
and Replacing a Sound

7.3 Summary
In this session, Working with Audio and Video, you learned that:
¾¾ Flash supports most of the video file formats, including QuickTime, Windows Media, and MPEG clips.
¾¾ The Import Video Wizard helps through the process of importing video files into Flash. Videos can be imported
in the following three ways:

●● Load external video with playback component

●● Embed FLV or F4V in SWF and play in Timeline

●● Import as mobile device video bundled in SWF


¾¾ While importing video files, it is advisable to import them first into the Library so as to have better control over
their working. Import or Import To Library commands or the Import button in the Video Properties dialog box
can be used to import files in FLV or F4V format.
¾¾ Apart from the Adobe FLV video format, both Flash Player and Adobe AIR support video and audio that is
encoded in H.264 and HE-AAC from MPEG-4 file formats.
¾¾ Movie playback controls, which come with different skins, can be also attached. For this, the Wizard uses the
Skinning component. The property settings, such as size and position, alignment, skin, volume, autoplay, and
cue points can be changed through the Properties panel.
¾¾ Various properties available are Align, Autoplay, Cue points, isLive, Preview, ScaleMode, Skin, SkinAutoHide,
SkinBackgroundAlpha, SkinBackgroundColor, and SourceVolume. These can be changed for an instance of an
embedded video clip on the Stage by assigning it with an instance name, values of width, height, and position
on the Stage using the Property inspector.
¾¾ Cue points refer to markers within a video clip that are used to trigger different segments. The two kinds of cue
points used are Encoded and ActionScript.
¾¾ Another alternative to importing external FLV files in Flash Player is to dynamically play them using the
FLVPlayback component.
¾¾ Adobe® Flash® Professional exhibits a number of ways to use sound. This can be by playing sounds
continuously, or independent of the Timeline or the Timeline can be used to match animation to a sound track.
¾¾ All sounds in Flash, whether music or sound effects, fall into two categories — namely, Event Sounds and
Stream Sounds. Formats such as ASND, WAV, AIFF, and MP3 can be imported into Flash Professional.
¾¾ Flash enables importing of sounds, playing them, checking their statistics, and adjusting compression settings.
Sound can be added, edited, synchronized, and removed. Apart from this, other tools, such as Find and Replace
and Adding sound in symbols are also available to the users.

7.4 Exercise
1. The Import Video Wizard comes with different skins and for applying it, the ___________ component is used.

Streaming

Playback

Skinning

Properties

2. If mono sound is used, the file is cut to half the size as only a single sound channel is used instead of two.

True

False

3. Bit rate is always a choice between sound quality and file size.

True

False

4. ___________ type of sound must be downloaded completely before it begins to play, and it continues to play until
stopped.

Event

Stream

Start

End

5. _____________ option measures the video using options, such as, maintainAspectRatio, noScale, or exactFit.

Scale

Volume

Preview

ScaleMode
Session 8
Exporting and Publishing
Learning Outcomes
In this session, you will learn to:
¾¾ Export images, audio, and videos
¾¾ Work with the Publish command
¾¾ Explain the formats in which animated files can be published

After creating animations in the Flash interface, images, image sequences, and movie clips of the final file can be exported
or published in more than one format. Publishing a Flash movie is the last step towards completing an animation. On a
macro level, exporting in Flash is broadly classified into the following two categories:
¾¾ Export Image: To access this option, from the File menu, choose Export. From the sub-menu that appears,
click Export Image.
¾¾ Export Movie: To access this option, from the File menu, choose Export. From the sub-menu that appears,
click Export Movie.

8.1 Exporting Images and Graphics


Refer to Table 8.1. Following are the extensions and their description in which image sequences can be exported:

File Formats Extension Description


Flash Movie .swf This format is used for the basic output for Flash animations. These are small,
useful for publication on the Web. SWF files support animations and can contain
applications of varying degrees of interactivity and function.
Enhanced Metafile .emf Enhanced Metafile is similar to Windows Metafile. However, unlike Windows
Metafile, .emf files are exported in 32-bit format.
Windows Metafile .wmf Windows Metafiles can be used across applications. These files can contain vector
and bitmap components. They are commonly used for storing line-art, illustrations,
and content created in drawing or presentation applications.
EPS 3.0 .eps EPS files are self-contained. They are PostScript documents that describe an image
or drawing. These files can be embedded within another PostScript document.
Adobe Illustrator .ai Adobe Illustrator Artwork (AI) is a file format developed by Adobe. These files are
used for representing single-page vector-based drawings in either EPS or PDF
format.
AutoCAD DXF .dxf AutoCAD DXF (Drawing Interchange Format or Drawing Exchange Format) is
a CAD data file format. It is developed by Autodesk. This file format is used for
enabling data inter-functioning between AutoCAD and other programs.
Bitmap .bmp In computer graphics, a bitmap is an image file format used to store digital images.
JPEG Image .jpg JPEG is a very common image format. Here, the size of the image is compressed
to a greater extent, without much loss to its quality.
GIF Image .gif GIF image supports upto 8 bits per pixel. This format allows a single image to
reference a palette of 256 distinct colors that are chosen from the 24-bit RGB color
space. This format suits for animations and allows a separate palette of 256 colors
for each frame. Unlike JPEG, this format is best suited for simpler images that are
filled with solid areas of colors.
PNG Image .png Portable Network Graphics (PNG) is a bitmap image format. This format supports
lossless data compression and was created as a replacement for the GIF format.
Table 8.1: File formats and extensions for exporting animation files in Flash
8.1.1 Flash Document (SWF)
If the Flash Pro content is to be placed in another application such as Dreamweaver, the entire file has to be exported as
a SWF file. Flash Pro exports it by using the current settings from the Flash tab of the Publish Settings for the FLA file.

A new compression algorithm, Lempel–Ziv–Markov chain algorithm (LZMA), is also available for SWFs that target Flash
Player 11 or its later versions. This new compression can be upto 40 percent more efficient, particularly for files that
contain a lot of ActionScript or vector graphics. Following are the steps to access it:

1. Choose File, and then select Publish Settings.

2. In the Advanced section of the dialog box, select the Compress movie option and choose LZMA from the menu.

8.1.2 Bitmap (BMP) Image


Bitmap images can be created for other applications. Following options are present in the Export Bitmap dialog box:
¾¾ Dimensions: It sets the size of the exported bitmap image, which is measured in pixels. The size specified will
have the same aspect ratio as the original image.
¾¾ Resolution: It sets the resolution of the exported bitmap image, which is measured in dots per inch (dpi) and
the width and height is automatically calculated based on the size of the drawing. Select the Match Screen, for
the resolution to match the monitor.
¾¾ Color Depth: It specifies the bit depth of an image. However, if there are any compatibility issues with Windows
while using this 32-bit per channel (bpc) depth for bitmap images, the 24-bpc format can be used.
¾¾ Smooth: It applies anti-aliasing effect to the exported bitmap. This effect not only produces a higher-quality
bitmap image, but also creates a halo of gray pixels around it and can be seen when placed on a colored
background.

8.1.3 JPEG Sequence and JPEG Image


These options share similarities with the JPEG
Publish Settings options, however, with one
exception:
¾¾ The Match Screen option makes the
exported image match to the size of the
Flash Pro content as it appears on the
screen.
¾¾ Match Movie matches the JPEG image
to the Flash Pro content and maintains
the aspect ratio of the original image.
Refer to Figure 8.1.

8.1.4 Animated GIF, GIF Sequence,


and GIF Image
The settings for GIF are similar to those for the
GIF tab in the Publish Settings dialog box, with
the following exceptions:
¾¾ Resolution: It is set in dpi. To use it, enter
a resolution or click Match Screen.
¾¾ Include: It is used for exporting the
minimum image area or the full document
size.
¾¾ Colors: It is used to set the number of
colors that can be used to create the
exported image. The color choices are: 2
(black and white), 4, 6, 16, 32, 64, 128, or
256 colors; or Standard Color, which can
be 216-color Web-safe palette.
¾¾ Animation: It is available for exporting
in the Animated GIF format only. The Figure 8.1: JPEG Publish Settings
number of repetitions can be entered, where 0 repeats endlessly.

8.1.5 PNG Sequence - Creating and Using Sprite Sheets


The Flash Professional CS6 release has introduced a new feature called as Sprite Sheet Generator.

A sprite sheet is a bitmap image file that contains several smaller graphics arranged in a tiled grid format. When a single
file has to be loaded, these small graphics can be complied into a single file by Flash Professional and other applications.

Thus, by using sprite sheets, the Graphics Processing Unit (GPU) does not have to load all graphic components on the
primary memory but only load a single file. This enhances the performance of the GPU.

A series of image files can be exported from an individual movie clip, button, or graphic symbol in the Library or on the
Stage. During export, Flash Pro creates a separate image file for each frame in the symbol. If exported from the Stage,
any transforms, such as scaling or skewing that has been applied to the symbol instance, are preserved in the output
image.

To create a sprite sheet, use the following steps:

1. Select one or more symbols in the Library or symbol instances on the Stage. This selection can include bitmaps
also.

2. Right-click the selection and select Generate Sprite Sheet.

3. From the Generate Sprite Sheet dialog box, select Options, and then click Export.
Click www.youtube.com/watch?v=UDdKMV_rvbs to view a demonstration on Creating Sprite Sheets in Flash CS6.

Click here to know more about export options.

8.1.6 FXG Graphic Interchange Format


The FXG format is a graphic interchange file format, which works with the Flash Platform. FXG is based on a sub-set
of MXML, which is the XML-based programming language used by the Flex framework. To enable smooth exchange of
graphical content between designers and developers with high reliability, FXG format assists a lot. Designers can create
graphics using Adobe design tools and export the same to FXG. Then, these FXG files can be used in tools, such as
Adobe Flash Builder and Adobe Flash Catalyst to develop rich Web experiences and applications.

When an FXG file is created, vector graphics get stored directly within the file. The elements for which no corresponding
tag exists in FXG are exported as bitmap graphics and then referenced in the FXG file. Such elements include some
types of bitmaps, filters, blend modes, gradients, masks, and 3D.
When a file containing vector and bitmap images is exported using FXG export, a separate folder simultaneously gets
created along with the FXG file. This folder is named as <filename.assets> and contains the bitmap images associated
with the FXG file.

In Flash, content can be exported in FXG format in two ways:


¾¾ For exporting objects on the Stage as FXG, select the objects and choose Export, and then click Export
Selection. Then select FXG format from the File Type menu.
¾¾ For saving the entire Stage as FXG, choose Export. Select Export Image, and then click Adobe FXG from the
File Type menu.

8.2 Exporting Video and Sound


Apart from SWF and GIF, Refer to Table 8.2 that shows the other formats in which files can be exported using the Export
Movie command.
File Formats Extension Description
Windows AVI .avi This format is used to export a document as a Windows video after discarding
interactivity. This format is best suited for opening a Flash animation in a video-
editing application. Since AVI is a bitmap-based format, the size of the documents
containing long or high-resolution animations can become very large.
QuickTime .mov QuickTime is a multimedia framework that can handle various digital formats,
such as, digital video, media clips, sound, text, animation, music, and interactive
panoramic images.
Table 8.2: File formats and extensions for exporting video files in Flash

8.2.1 Exporting as FLV


With Flash Pro, videos can be imported or exported with encoded audio. When video clips are exported from Flash
in FLV format with streaming audio, the audio is compressed by adjusting the Streaming Sound dialog box settings.
Whereas, files in the FLV format are compressed using the Sorensen codec. Following are the steps to export video
clips in Flash:

1. Export a copy of an FLV file from the Library.

2. Right-click the FLV video clip in the Library panel.

3. Click Properties option from the context menu.

4. In Video Properties dialog box, click Export.

5. Enter a name for the exported file. Then, select a location, click Save, and click OK.

8.2.2 Exporting as QuickTime Videos


Following are the two methods that Flash Pro provides for exporting Flash Pro documents as QuickTime:
¾¾ QuickTime export: This option is useful for those users who want to distribute Flash Pro content, such as
animation in this format. Using this option, a QuickTime file is exported that can be distributed as streaming
video, as DVD, or can be used in any video editing application, such as Adobe Premiere Pro.
¾¾ Publish as QuickTime: This option assists in combining the interactive features of Flash Pro with the multimedia
and video features offered by QuickTime in a single QuickTime 4 movie. This can be viewed with QuickTime 4
or its later versions. Thus, it creates an application with a Flash Pro track in the same QuickTime format, which
is installed on the computer. Following are the steps for exporting a video in QuickTime format:

1. Select File, then click Export, and then click Export Movie.

2. Specify settings for the QuickTime movie to export.

3. Click Export.

8.2.3 Exporting as WAV Audio


Here, only the sound file of the current document is exported to a single WAV file. The sound format of the new file can
be specified later. The sampling frequency, bit rate, and the stereo or mono settings of the exported sound can be set by
adjusting the Sound Format options. For excluding event sounds from the exported file, select Ignore Event Sounds
option.

For detailed step-by-step procedure, refer to demo Exporting Image and Video from:

eResources 4 Me>> My Varsity>> Web Animation and Interactivity>> Show Me How>> Exporting Video and Sound >>
Exporting as WAV audio

Quick Test 8.1


1. ______________ format supports lossless data compression and was created as a replacement for the GIF
format.
PNG JPEG BMP AI

2. _________ option in Export Bitmap dialog box applies anti-aliasing effect to the exported bitmap.
Smooth Resolution Bit depth Color Depth
8.3 Publishing Movies
The Publish Settings can be adjusted to minimize the file size of an animation. This is because a large file size
increases the download time and cause the animations to play incorrectly. The Publish command creates a Flash SWF
file and an HTML document that inserts a Flash movie into a browser window. Flash also enables publishing of FLA
file in alternative file formats including GIF, JPEG, PNG, and QuickTime. Publish Settings can also be used to choose
the delivery mode of the animation, which can be a standalone projector file, a QuickTime movie, an image file, or an
embedded file in a Web page. Settings can also be specified at one place. From the File menu, select Publish Settings
to open the Publish Settings dialog box. The Formats tab appears selected by default. Refer to Figure 8.2.

Figure 8.2: Publish Settings dialog box

8.3.1 Types of Publishing Formats


Refer to Table 8.3 that shows the formats in which animated files can be published.

Formats Description
GIF GIF files allow exporting of drawings and simple animations for use in Web pages. Standard GIF
files are compressed bitmaps. Animated GIFs can also be created.
JPEG JPEG files can display many more colors than GIF files and therefore, produce more realistic
photos and complex drawings. JPEG graphics are compressed to reduce the file size. However,
they decompress when downloaded, using more memory. Flash exports the first frame in the
movie as a JPEG, unless a different keyframe is marked by placing the playback head on the
keyframe.
Formats Description
PNG PNG files can display more colors than GIF files, and support transparency. They offer some
advantages of both GIFs and JPEGs, but not all browsers support them completely.
QuickTime This format is used for digitized movies. QuickTime movies are played using the QuickTime
player. Flash provides importing, exporting, and publishing of QuickTime movies.
C r e a t i n g A projector can be used for a Flash movie for placing on a CD-ROM. A Windows or a Mac
Projectors version from either platform can be created. However, if a Mac version is created in Windows, a
file translator such as BinHex is needed so that the Mac Finder recognizes it as an application.
Table 8.3: Formats for publishing animated files

8.3.2 Publish Settings for Flash


When the Publish, Test Movie, or Debug Movie commands are used, a SWF file from the FLA file is created by Flash.
In the Publish Settings dialog box, the Flash tab enables adjusting the settings of the Flash player file, also called as
an SWF file. Refer to Figure 8.3.

Figure 8.3: Publish Settings dialog box with the Flash tab active

Click here to know more about the Publish Settings for Flash dialog box options.

8.3.3 Publish Settings for HTML


Playing a Flash movie in a Web browser requires an HTML document that activates the movie and specifies browser
settings. This document is generated automatically by the Publish command, from HTML parameters in a template
document.

The HTML parameters determine various settings, such as the placement of the Flash movie window, background color,
and the size of the movie. It sets attributes for the object and embed tags. However, such settings can be changed in
the HTML tab of the Publish Settings dialog box. Changing these settings will override the options that have been in
the movie. Refer to Figure 8.4.

Figure 8.4: Publish Settings dialog box with the HTML tab selected

Click here to know more about the Publish Settings for HTML dialog box options.

8.3.4 Publishing for Mobile Devices


The Adobe AIR for Android and iOS allows users to create interactive content for mobile devices. For this, ActionScript
scripting language, drawing tools, and templates are used.

A Mobile Content Simulator acts as a tool for testing content created with Adobe AIR in an imitated Android or iOS
environment. This allows simulating hardware keys, Accelerometer, Multi-touch, and Geo-location. With the Mobile
Content Simulator, from the Control option, the Test Movie command can be used to test the Flash file in the AIR
Debug Launcher for Mobile, which in turn launches the Simulator.

With Flash Professional CS6 Update 12.0.2, AIR applications can be deployed on iOS directly, bypassing the use of
iTunes. This feature reduces the downloading time required to publish an AIR application for iOS and thereby improves
the performance significantly.

Click here to know more about the Adobe® AIR® for Android.

It is advisable to install iTunes on those machines that have Flash Professional CS6 installed in them.

To enable direct deployment on iOS device, the following steps can be implemented:

1. Ensure that iTunes is installed on the machine on which Flash Professional CS6 is installed.

2. In Flash Professional CS6, on the Properties panel, click the button beside the Target drop-down to bring up the
AIR for iOS Settings dialog box.

3. On the Deployment tab, select Install Application On The Connected iOS Device option.

4. Click Publish.

The mobile device used can impose certain compatibility restrictions on ActionScript commands and sound
formats that are supported.

8.3.5 Direct Mode Publishing


Direct is a new window mode, which enables hardware accelerated content using Stage3D. However, the Stage3D
requires Flash Player 11 or later to function. Direct mode can be set for AIR for Desktop, AIR for iOS and AIR for Android.
Refer to Figure 8.5.

Figure 8.5: Publish Settings dialog box showing Direct mode

Following steps can be implemented:


1. Choose File and select Publish Settings.

2. Select HTML Wrapper.

3. Select Direct from the Window Mode menu.

8.3.6 Publishing and Previewing


The file can be previewed and published after the file format types and specifications for each file has been entered in
the Publish Settings dialog box. Refer to Figure 8.6.

Figure 8.6: Publishing and previewing

For detailed step-by-step procedure, refer to demo Publishing Movie from:

eResources 4 Me>> My Varsity>> Web Animation and Interactivity>> Show Me How>> Publishing Movies>> Publishing
and previewing

8.4 Summary
In this session, Exporting and Publishing, you learned that:
¾¾ Publishing a Flash movie is the last step towards completing an animation. On a macro level, exporting in Flash
is broadly classified into the following two categories — namely, Export Image and Export Movie.
¾¾ The various formats in which images and image sequence can be published are Flash Movie, Enhanced
Metafile, Windows Metafile, EPS 3.0, Adobe Illustrator, AutoCAD DXF, Bitmap, JPEG, GIF, and PNG.
¾¾ The Flash Professional CS6 release has introduced a new feature called as Sprite Sheet Generator. By using
this, the GPU does not have to load all graphic components on the primary memory but only load a single file.
This enhances the performance of the GPU.
¾¾ The FXG format is a graphic interchange file format, which works with the Flash Platform. FXG files can be
used in tools, such as Adobe Flash Builder and Adobe Flash Catalyst to develop rich Web experiences and
applications.
¾¾ Apart from SWF and GIF, Windows AVI and QuickTime are the formats in which files can be exported using the
Export Movie command.
¾¾ With Flash Pro, videos can be imported or exported with encoded audio. The two options for exporting Flash
Pro documents as QuickTime are QuickTime export and Publish as QuickTime.
¾¾ By using the Sound Format option, only the sound file of the current document is exported to a single WAV file.
¾¾ The formats in which animated files can be published are JPEG, GIF, PNG, QuickTime and Creating Projectors.
¾¾ By using the Publish Settings dialog box, animated files can be published into Flash, HTML, and for mobile
devices. Direct is a new window mode, which enables hardware accelerated content using Stage3D. However,
the Stage3D requires Flash Player 11 or later to function.
¾¾ This file can be previewed and published after the file format types and specifications for each file has been
entered in the Publish Settings dialog box.

8.5 Exercise
1. The __________ for Android and iOS allows Flash Pro users to create interactive content for mobile devices.

Adobe Flash Builder

Adobe AIR

Adobe Flash Catalyst

Adobe Illustrator

2. ____________ acts as a tool for testing content created with Adobe AIR in an imitated Android or iOS environment.

Sprite Sheet Generator

Test Movie

AIR Debug Launcher

Mobile Content Simulator

3. ____________ format exports a document as a Windows video after discarding interactivity.

AVI

MP3

MOV

GIF

4. QuickTime export option assists in combining the interactive features of Flash Pro with the multimedia and video
features offered by QuickTime in a single QuickTime 4 movie.

True

False

5. By using sprite sheets, the GPU does not have to load all graphic components on the primary memory but only has
to load a single file.

True

False
Session 9
Introduction to ActionScript 3.0 and Programming
Concept
Learning Outcomes
In this session, you will learn to:
¾¾ Understand the basic concept of ActionScript 3.0 (AS3) programming
¾¾ Describe the uses of Conditionals, Loops, and Operators in AS3 programming
¾¾ Understand the use of static method and static variable
¾¾ Identify different kinds of functions
¾¾ Describe the use of Array in AS3 programming
¾¾ Distinguish between Web scripting, interactivity, and AS3 programming

9.1 Core Concepts


AS3 offers an extensive programming model, familiar to those developers who have a basic knowledge of object-
oriented programming. It is designed to facilitate the creation of some highly complex applications with large data and
codes with object-oriented concepts.

AS3 is not required for content that run in Adobe Flash Player 9, but it opens the door to performance improvement
available with the ActionScript Virtual Machine 2.0 (AVM2), a new virtual machine. However, ActionScript Virtual Machine
(AVM1) executes ActionScript 1.0 and ActionScript 2.0 code and is supported by Flash Player 9.

AS3 includes new features of the core language and an improved Flash Player API that provides increased control of
low-level objects.

9.1.1 Basic Knowledge of Programming


A set of written instructions to be carried out by a computer application is called a program, and the person who creates
it can be called a programmer, a coder, or a developer. All programs are written in a programming language that dictates
the syntax and grammar, which the programmers use to form the instructions. Thus, a programmer creates a readable
text or a set of written instructions of a program called source code or a code.

Thus, it is very important to understand what a computer program is and how it works. Refer to Figure 9.1.

Figure 9.1: Computer program with examples


9.1.2 Programming Techniques
There are two types of programming techniques, Top-Down and Bottom-Up approach.
¾¾ Top-Down approach: This approach is also known as stepwise programming. This approach involves splitting
a system in order to get detailed information into its compositional sub-systems. An overview of the system
is formulated in a top-down approach that specifies the first-level sub-systems. Each of the sub-systems are
further developed into more sub-system levels till the complete condition is reduced to its base elements. This
is also known as procedural programming in which the code is based on sequential programming structure.
For example, in reality, the main function is written first to call the stubs. Then, these stubs are sub devised into
smaller stubs and output is achieved.
¾¾ Bottom-Up approach: In this approach, the individual base elements of the system are specified in detail. A
larger sub-system is formed by linking these elements together, which in turn gets linked into many levels, until
a complete top-level system is formed. This strategy resembles to a seed model.

In real-life, all programming is done using a combination of approaches. In Object-Oriented Programming (OOP),
the problem is sub-divided by identifying domain objects, which is a top-down step, refining those objects and then
recombining into a final program, which is a bottom-up step.

There are several differences between top-down approach and bottom-up OOP approach. Refer to Table 9.1.

No. Top-down approach Bottom-up OOP approach


1 The importance is given to the sequence of things The importance is given to the data.
to be done. For example, algorithms.
2 The larger programs are divided into functions. The larger programs are divided into objects.
3 Most functions share global data. This also means The data is private and only functions inside the object
the data moves freely around the system from can access the data.
function to function.
4 In problem solving, the top-down approach is In problem solving, the bottom-up approach is followed.
followed.
5 The adding of data and function is difficult. The adding of data and function is easy.
6 There is no access specifier. There is public, private, and protected specifier.
7 The operator cannot be overloaded. The operator can be overloaded.
Table 9.1: Difference between Top-down approach and Bottom-up OOP approach

9.1.3 Difference between AS2 and AS3


ActionScript evolved along with Flash and upgraded AS2 to AS3, which has many new features, such as Runtime
Exceptions, Sealed Classes, Method Closures, New Event Model, and E4X Object.

The advantages of AS3 over AS2 are as follows:


¾¾ It has a stricter compiler than the earlier version, which saves time.
¾¾ It works on AVM that increases the pace of the file ten times more than AVM 1. It works as a master renderer
for the SWF files in Flash Player.
¾¾ It is faster than AS2. It has an advanced OOP method to code and an advanced AVM.
¾¾ It has more OOP programming than AS2. It focuses more on OOP as compared to AS2.
¾¾ The delicate improvements have been combined with better syntax writing. So, the new properties do not carry
useless underscores, loading of data is done dynamically, and linking to a URL has made regular changes in it.
¾¾ It has more scripting options. There is improvement in the Text or String, such as calculating the index of the
letter in the first line, last line, and under the mouse letters. Thus, calculating the length of the specific line or
paragraph is now possible. These improvements make working with the text easy and also allows a tighter
integration with the lines and characters in a field and their surrounding stage elements.
¾¾ It has advanced options to access raw data, which were not available before. Raw binary data can be accessed
at runtime. For example, accessing individual bytes of data during sound playback, download, and during
bitmap data management.
¾¾ There is improved OOP in AS3. For example, the addition of sealed classes and few namespaces.
9.1.4 AS3 Coding
AS3 follows good coding practices. Unlike AS2, where coding was faster, the global variables have been minimized in
AS3, thereby compelling the use of OOP, which is better and simpler to debug, but the only downside is that it requires
a long time to code. AS2 can code small projects faster as the functioning code works faster, but AS3 makes it easier to
debug many lines of code in bigger projects.

AS2 programs cannot be compiled for output in AS3, unlike many compilers that support previous versions
and new ones as well.

9.1.5 AS3 Execution


AVM is technically the software module inside Flash Player that executes ActionScript programs. AS2 was used to make
SWF files’ data using AVM 1 version, but AS3 has a new name called Virtual Machine which is AVM 2.

Owing to this compatibility issue, AS2 and prior codes cannot be executed in AS3. ActionScript is designed to make the
creation of highly complex applications with large data easy. An SWF file written in ActionScript 1.0 or 2.0 can be loaded
by AS3 code, but it cannot access SWF file’s variables and functions.

One major drawback about AS3 is that more steps are required to code for a simple application.

9.1.6 About Flash Client Runtime Environments


Flash Player, Adobe AIR, and Flash Lite are the three different software applications that help execute an ActionScript
program. Flash Player, Adobe AIR, and Flash Lite are known as Flash Client Runtime Environments or Flash runtimes
since they manage ActionScript programs while they execute or run.

Click here to know more about the Flash Client Runtime Environments.

9.1.7 Compilation
ActionScript program needs to be converted into a binary format that Flash runtime can understand. This is known as
ActionScript bytecode or ABC. ActionScript bytecode cannot be executed by Flash runtimes and needs to be wrapped
in a binary file known as SWF file, which stores the bytecode in Flash file format or SWF. The process of converting an
ActionScript program into a bytecode is called as compiling a program and the process of generating SWF file is known
as compiling the SWF file or publishing the SWF file.

A software module known as a compiler is required to compile AS3 programs and SWF files. A compiler that compiles
ActionScript code is known as an ActionScript compiler. A compiler that generates SWF files is known as an SWF
compiler. Any SWF compiler that claims full support for the Flash file format includes an ActionScript compiler.

There are two levels of compilation that takes place in ActionScript code. In the first level, the developer compiles the
code from readable format by the Flash runtime. In the second level, the ActionScript bytecode is automatically compiled
by the Flash runtime to a format understood by the hardware running the program. The second level is called just-in-time
compilation or JIT because it takes place just before the particular bytecode is being complied and is required by the
program.

9.1.8 Variables and Values


Each object in ActionScript, is considered a single data or information, which is called as a value and the special legal
values, null and undefined, which represent the concept of no value. An identifier or a name with a value is called a
variable. Variables help to keep track of information in a program and provide a means of referring to an object after it
is created.

There are four types of variables: local variables, instance variables, dynamic variables, and static variables. Refer to
Figure 9.2.
Figure 9.2: Types of variables

In a computer program, the memory location where the data is stored is called a variable. The smallest variable is one
bit, and the largest is up to millions of bytes. Current processors stores data of 4 or 8 bytes at one time (32 and 64 bit
CPSs). Hence, the big variables take longer to read or write. The size of the variable depends on its type. Following are
the types:
¾¾ String: This is a textual value, similar to a name of the text.
¾¾ Numeric: There are three specific data types for numeric data:
●● Number: This is any number, which includes values with or without a fraction.

●● int: This is an integer, which is a whole number without a fraction.

●● uint: This is an unsigned integer, which means a whole number that cannot be negative.

¾¾ Boolean: This data type has only two values: true or false or 1 and 0. No other values are considered valid.
¾¾ Null: This type of data contains only one value called as null, which is also the default value for the String data
type of all classes defining complex data types, such as Object class.

¾¾ Void: This data type has only one value, which is undefined. In the earlier versions of ActionScript, undefined
was the default value for instances of the Object class, but in AS3, the default value is null.

ActionScript stores primitive values internally as immutable objects. Storing immutable objects means,
that passing by reference is effectively the same as passing by value. This reduces the memory usage and
increases execution speed, as references are usually smaller than the values themselves.

¾¾ Some complex data types in AS3


A complex value is a value that is not a primitive value. Data types that define sets of complex values are as
follows:

●● MovieClip: This is a movie clip symbol.

●● TextField: This is a dynamic or input text field.

●● SimpleButton: This is a button symbol.

●● Date: This data provides information about a single moment in time, which is a date and time.

●● XML: This data is a revised XML object based on the E4X (Standard ECMA-357).

●● Object: This type is defined by the Object class, which also serves as the Base class for all class
definitions in ActionScript.

●● Array: This contains a list of data. Though AS3 is a strongly typed language, the contents of an Array may
be of any type and values must be cast back to their original type after being retrieved.
9.1.9 Classes and Objects
Assume an example of making a car from scratch. The entire process needs to be listed. A person would not just go to a
metal shop for welding. He would rather start by drawing several blueprints for each part of the car, describing a specific
part conceptually and matching the actual part of a car, such as seats, brakes, wheels, steering wheel, and so on. Each
of these parts would have to be manufactured individually and assembled in accordance with the blueprint.

In a similar way, classes are the blueprints on which objects are based. Incarnations or instances of classes are objects.
Each class describes both the characteristics and behavior of a particular type of object.

Class definitions contain constants and variables, which have the data values and methods. These are functions that
hold the behavior to the class. Either primitive values or other objects are stored. Primitive values are numbers, strings,
or Boolean values.

It is important for programmers, with previous ActionScript experience, to note that the Object data type is not a default
data type, despite the fact that all the other classes derive from it.

As per AS3, the following lines of code are equivalent because the variable is of Object type:
var someObj:Object;

var someObj;

In AS3, the concept of untyped variables has been introduced that can be selected in the following two ways:
var someObj:*;

var someObj;

An untyped variable is different as compared to a variable of type Object as it can hold the special value undefined,
whereas a variable of type Object cannot hold.

Classes can be defined using the class keyword by declaring class properties in the following three ways:
¾¾ By using the const keyword to define the constants
¾¾ By using the var keyword and properties to define the variables
¾¾ By using the get and set attributes in a method declaration, the setter properties can be defined
An important group of classes is the native classes that are directly built into ActionScript.

An instance of a class can be created using the new operator. For example, an instance of the Date class called
myBirthday is created as follows:
var myBirthday:Date = new Date();

An object is an instance of a class. As seen earlier, every object has states and behaviors. For example, a human being
has states such as color and name, and behaviors, such as habits, eating, walking, and so on. Similarly, a software
object’s state is stored in fields and behavior, which is shown through methods.

A running ActionScript program is a group of interoperating objects that are based on a set of classes that represent
tangible and intangible concepts in a program. Objects are made from the classes in a program and tell them what has
to be done. Thus, the behavior of the objects is determined by what the object does.

Thus, a program that is built with classes and objects is known as Object-Oriented Programming (OOP). Refer to Table
9.2.

Class Description
String It represents textual data, which is a string of characters.
Boolean It represents the logical states, true and false.
Number It represents floating - point numbers, which are numbers with a fractional value.
int It represents integer numbers, which are numbers with no fractional value.
uint It represents positive integer numbers.
Array It represents an ordered list.
Class Description
Error It represents a program error, which is a problem in the code.
Date It represents a specific point in time.
Math It contains common mathematical values and operations.
RegExp It defines tools for searching and replacing text.
Function It represents a reusable set of instructions that can be executed, or called, repeatedly.
Object It defines the basic features of every object in ActionScript.
Table 9.2: Aspects that complete the design of a character

9.1.10 First Step to Build a Program


Design phase forms the basis of development of a new ActionScript program wherein the program’s functionality is
broken into a logical set of classes. Each class is given a specific name, a set of features, and a role to play. The main
class VirtualOffice is an example of a virtual office program. Refer to Figure 9.3.

Figure 9.3: Steps to build a program


virtualoffice

I – src

I - VirtualOffice.as

To avoid the naming convention with the built-in classes name, use Packages.

9.1.11 Packages
Packages help in bundling class definitions together to facilitate code sharing and reduce naming conflicts. Packages
also allow organizing class files. As the name suggests, packages is a group of classes. Each package is limited to a
physical region of a program called package name.

In AS3, the packages are implemented with namespaces. Namespaces help in controlling the visibility of identifiers,
such as property and method names, and can be applied to code whether it resides inside or outside a package. At the
time of declaring a package, create a special type of namespace, which is known at the compile time. Namespaces
allow managing of the visibility of individual properties and methods.

One can use a package definition directive to create a new package. All the program instructions in ActionScript are
known as Directives.

A definition that creates something in a program defines or declares thing. Definitions are also known as declarations.
Following is the general form of package definition directive:
package packageName {

The keyword to start all package definitions is package that tells ActionScript to create a package. The desired package
name is represented by packageName and the class source code within a package takes the name of the package.
This is followed by marking the beginning and end of the package contents using curly brackets like {and}.

To insert the source code between the curly brackets with the packageName, use the following:
package packageName {

Class source code goes here

For example, a class named Solitaire in a package named game becomes game.Solitaire. The package name
is written first followed by the class name with a period (.) character. This helps in identifying names between different
parts of a program or between the classes and ActionScripts’ built-in classes.

Package names have the following structures:


¾¾ The reversed domain name of the organization creating the program
¾¾ This is followed by a period (.)
¾¾ Followed by the general purpose of the package’s contents
For example, a package containing classes for a Website application created Astar Ltd., whose domain name is astar.
com, will be named com.astar.site as shown in the following code:
package com, astar.site {

Here, notice that in the package name, the domain name is reversed. Now, use packages in the virtual office program
by using the package name office, without any leading domain name.

To define the office package, add the following code to the file VirtualOffice.as:
package office {

After having added a package to the file VirtualOffice.as, change the file location on the file system to match the
package. The Adobe’s ActionScript compiler imposes a requirement that when a source contains a class or a definition
in a package, it must be stored in a folder structure that matches the package name.

Thus, a new folder named office is created in the program’s file structure and VirtualOffice.as moves into it. Now,
the file structure of the program’s source files becomes, as follows:
virtualoffice

I – src

I – office

I - VirtualOffice.as

After having the package definition, add the VirtualOffice class to it.

9.1.12 Defining a Class


A new class is created by using a class definition, which is as follows:
class Identifier {

The keyword class is followed by a class name identifier that refers to a name. All the first words must begin with
a capital letter as in VirtualOffice.

Block statement is the curly brackets following identifier. In the preceding class definition, which is also known as the
class block or class body, contains directives describing the characteristics and behavior of the class and its instances.
For example, the class definition of VirtualOffice will be placed in the packaged body, in the file VirtualOffice.as:
package office {

class VirtualOffice

}}

Since the preceding VirtualOffice class definition resides in a package named office, the complete name of the
class is office.VirtualOffice. The shorter class name is VirtualOffice.

Create another class in the program, for example VirtualWorkforce class and create objects that represent the
workforce in the office.

Just like VirtualOffice, place the source code for the VirtualWorkforce class in the office package in its file
named VirtualWorkforce.as saved in the office folder. The code from the VirtualWorkforce.as file is as
follows:
package Office {

class VirtualWorkforce {

}}

There are two classes in the game namely, VirtualOffice, which is the main class and VirtualWorkforce, which
represents the employees in the game. The classes reside in the package office, and are stored in the plain-text files
named VirtualOffice.as and VirtualWorkforce.as.
■■ Access control modifiers for classes

An access modifier helps to modify classes that can instantiate a particular class or access one of its properties.
Access modifiers in AS3 are of four types:
¾¾ public
¾¾ private
¾¾ protected
¾¾ internal

A class in a package is used by code that also resides in that package. This is by default. It is important to define
a class outside the package with the public attribute, wherein the class attributes direct how the class and its
instances can be used in a program.

In a class definition, the attributes are listed before the keyboard in the following way:
attribute class ClassIdentifier {

Click here to know about the access control modifiers for classes.
■■ Code comments in ActionScript

Code comments are notes that can be read only by a programmer and ignored by the compiler. Code comments
in ActionScript are in two varieties: Single line starts with two slashes (//), and multiline starts with the character
sequence /*, and ends with the character sequence */.
¾¾ Following is the single line comment:
// Only programmers are here

¾¾ Following is a multiline comment:


/*

Only programmers

are here

*/
The current code for the office game is as follows:
// Contents of the file VirtualOffice.as

package office {

public class VirtualOffice.as}}

// Contents of the file Virtualworkforce.as

package office {

internal class VirtualWorkforce {

}}

The next step in the development of a program is constructing method of the main class, VirtualOffice.

9.1.13 Constructor Methods


Constructor methods are called as Constructors and they are functions that share the same name as the class in which
they are defined.

A function definition is used within a class block to create a constructor method, as shown in the following code:
class SomeGroup {

function SomeGroup ( ) {

The keyword function begins the constructor method following the code. This is followed by the constructor method
name, which is same as the class name. Next, a pair of parenthesis containing a list of constructor parameters follows.
Following the parameters list are the curly brackets ({}) that are a block statement, similar to the one in the package
and class definitions. The block statement of the constructor method is known as a constructor body that contains the
directives that initialize instances. Refer to the following example:
class SomeGroup {

function SomeGroup ( value1, value 2) {

The directives in the constructor body are executed whenever a new instance is created in a sequence order starting
from top to bottom. This is also called as executing the constructor or running the constructor. ActionScript provides
a default constructor that performs no initialization on new instances of the class when a class does not define a
constructor function. It is therefore necessary to include an empty constructor as this provides an indication that the
class design does not require a constructor and can be done by adding a comment. Refer to the following example:
class SomeGroup {

// Empty constructor. This class does not require initialization.

function SomeGroup ( ) {

} }

The constructor method of an application’s main class is the program point of entry.

The following code is an example of adding a constructor method to the VirtualOffice class:
package office {

public class VirtualOffice {

public function VirtualOffice ( ) {

This application now has a point of entry. On starting the application, the Flash runtime creates a VirtualOffice
instance that executes the VirtualOffice constructor method in the process. The first thing to do is to create a
VirtualWorkforce object, which means adding an employee to the office.

9.1.14 Creating Objects


The process of creating an object is called as instantiating the object. In simple terms, it means creating an instance of
a particular class by using that keyword new along with the name of the class as shown in the following code.
new GroupName

In the following example, the code is used to make an object from the VirtualWorkforce class:
new VirtualWorkforce

Similarly, multiple independent objects can be made from the same class, as shown in the following example that
creates two VirtualWorkforce objects:
new VirtualWorkforce

new VirtualWorkforce

9.1.15 Constructor Parameters and Arguments


A special type of local variable that is created as a part of the constructor-method definition is called a constructor
parameter. Refer to the following example:
class SomeClass {

function SomeClass (identifier1 = value1, identifier2 = value2, identifier3 = value3) {

A value supplied to a constructor parameter when an object is instantiated is known as constructor argument.

9.1.16 Instance Variable


An instance variable is a variable that contains the properties of an object. It may be declared with the keyword var
and const without the static keyword. This is a part of the class instance rather than an entire class. Refer to the
following example:
package office {

public class VirtualOffice {

public function VirtualOffice ( ) {

var workforce = new VirtualWorkforce;

workforce. workforceName = “Stan”;

}}

As mentioned in the earlier code, the workforceName instance variable set through a VirtualWorkforce instance
from within the VirtualOffice is defined in the VirtualWorkforce class. Therefore, the workforceName instance
variable is accessible to code in the VirtualOffice class. This means that when a class makes its instance variables
accessible to code in other classes, it allows those classes to amend the characteristics of its instances.
■■ Access control modifiers for instance variables

An instance variable’s access control modifier controls that variable’s accessibility in a program. Access control
modifiers are used to limit access. Refer to Table 9.3 that lists some access control modifiers.

Code placement Public Internal Protected Private


Code in class containing variable’s Access allowed Access allowed Access allowed Access allowed
definition
Code in descendant of class Access allowed Access allowed Access allowed Access denied
containing variable’s definition
Code in different class in same Access allowed Access allowed Access denied Access denied
package as variable’s definition
Code not in same package as Access allowed Access denied Access denied Access denied
variable’s definition
Table 9.3: Access control modifiers

Hence, an instance variable is used to give characteristics to the objects of a class.

9.1.17 Instance Methods


The things that an object can do are defined by instance methods. These are a set of instructions that carry out tasks
associated with a given object. The function keyword is used within a class block to create an instance method. A
call expression is used to create instance methods using the function keyword. The following example explains how
to use a call expression to create instance methods using the function keyword:
object.methodName()

In this code, methodName is the name of the method whose code should be executed, and object is a reference to
the specific instance that will theoretically perform the task represented by the particular method. Calling a method of
an object is done by using a call expression to execute the code in an instance method’s body. Similarly, it also means
calling a method through an object, or calling an object’s method. The term invoke is also used to mean call.

Methods are functions that are a part of a class definition bound to that instance, the moment it is created. They help in
implementing functionality that affects individual instances of a class. A method cannot be used apart from the instance
to which it is attached. Methods that are declared without the static keyword are called instance methods. Refer to
the following example:
package Office {public class VirtualOffice {

private var workforce ; public function VirtualOffice ( ) {

this.workforce = new VirtualWorkforce (“Bob”) ;

// Invoke programming ( ) on the VirtualWorkforce object referenced by the

// variable workforce

this. workforce. programming ( );}}}

9.1.18 Members and Properties


As per the specifications given in the AS3, an object’s variables and methods are referred to as its properties. A name
associated with a value or method is termed as property.

Instance member or members refer to a class’s instance methods and instance variables.
Quick Test 9.1
1. The process of creating an object is called as ___________ the object.
Executing Implementing Initiating Instantiating

2. Methods that are declared without the static keyword are called dynamic methods.
True False

9.2 Conditionals, Loops, and Operators


9.2.1 Conditionals
To add logic to a program, conditionals are used. Conditionals are a type of statements that execute only when a
specified condition is met, and it also allows a program to choose between multiple courses of action that is based on the
current circumstances. There are two different conditionals that ActionScript provides: the if statement and the switch
statement. It also provides a single conditional operator, such as ? : ,

The if statement contains two blocks of code and a test expression that indicate which block should execute. The
following code is used to create an if statement:
if (testExpression) {

codeBlock1

} else {

codeBlock2}

ActionScript executes codeBlock1 or codeBlock2, depending on the value of testExpression. If the Boolean value
is True of the value of testExpression, then the first block is executed and if the Boolean value is False of the value
of testExpression, then the second block is executed.

ActionScript converts testExpression to a Boolean object if the value of testExpression is not a Boolean value
and uses the result of that conversion to decide which block to execute.

For example, in the if statement, the testExpression has the Boolean value as True, so the value of the variable ‘a’
is set to “Mango”, not “Orange”. Refer to the following example:
var greeting;

// Test expression is true, so….

if (true) {

//…. this code runs

greeting = “Mango”;

} else {

// This code doesn’t run

greeting = “Orange”;

}
Sometimes if statement is used without else. In this case the example will be as follows:
var greeting;

// Test expression is true, so

if (true) {

//…. this code runs

greeting = “Mango”;

}
■■ Chaining if statements

Multiple if statements are chained together to make a decision between two or more courses of actions. Following
is a code for a condition with three possible outcomes:
if (testExpression) {

codeBlock1

} else if (testExpression2) {

codeBlock 2

} else {

codeBlock3

In this case the example will be as follows:

var greeting;

if (language == “english”) {

greeting = “Friend”;

else if (language == “Hindi”) {

greeting = “Dost”;
}

else if (language == “Marathi”) {

greeting = “Mitra”;

else

greeting = “Friend”;

■■ Switch-Case Statement

The switch statement helps in the execution of several code blocks based on the value of a single testExpression,
in the following form:
Switch (testExpression) {

case expression1:

codeBlock1

break;

case expression2:

codeBlock2

break;

default:

codeBlock3

All statements following the default label are executed if no case expression matches testExpression.

In the following code, ActionScript attempts to match testExpression with each of the supplied case expressions,
beginning from the top to bottom. The case expressions and statement label case are followed by a colon.

All the statements follow soon after the case labels are executed, if testExpression matches a case expression.
This includes those in any subsequent case blocks. However, they can be prevented from executing, by using the
break statement at the end of each block. On the other hand, the break statement can be omitted when more than
one condition is needed to activate the execution of the same block of code.

In the following code, codeBlock1 executes when testExpression matches either expression1 or expression2:
switch (testExpression) {

case expression1:

case expression2:

codeBlock1

break;

case expression3:

codeBlock2

break;

default:

codeBlock3

The following code shows how to implement multiple conditions using a switch statement, which is easier to read
and scan quickly:
var month;

switch (number) {

case “1”:

month = “January”;

break;

case “2”:

month = “February”;

break;

case “3”:

month = “March”;

break;

case “4”:

month = “April”;

break;

default:

// Code here (not shown) would display as error message indicating

// that language was not set properly

For detailed step-by-step procedure, refer to demo Basics Programming Concept Conditionals from:

eResources 4 Me>> My Varsity>> Web Animation and Interactivity>> Show Me How>> Conditionals, Loops, and
Operators>> Conditionals

9.2.2 Loops
A loop allows a statement block to be executed repeatedly and is also referred to as Counter Loops, as long as its
expression remains True. The different types of loops are as follows:

¾¾ while statement
A while statement is similar to the if statement where the main statement encloses a code block that is
executed only when a testExpression is True, as shown in the following code:
while (testExpression) {

codeBlock

¾¾ do-while statement
The body of a do-while loop is executed only once. This is done through the loop and the syntax for the do-
while statement is like an inverted while statement.
do {

codeBlock

} while (testExpression);
Example:
var address = “abrock.org”;

var isValidAddress = false;

var i = 0;

do {

isValidAddress = true;

if (address.charAt(i) ==”@”) {

break;

i++;

while (i < address.length)

trace(isValidAddress)

The do-while loop guarantees the execution of the block at least once, as the condition is checked only after
the code block is executed. Hence, the output generated through the address does not contain the character
“@” and the trace shows “true”.
¾¾ for statement
for loop is written with more compact syntax as given follows:
for (initialization; testExpression; update) {

codeBlock }

Example:
var i:int;

for (i=0; i<5;i++)

trace(i);

Output:

The code shown for loop checks whether a string contains the @ character. It is identical to the earlier while
loop that performs the same task, as follows:
var address = “ ab@rock.org”;

var isValidAddress = false;

for (var i = 0; i < address.length; i++) {

if (address.charAt(i) == “@”) {

isValidAddress = true;

break;

trace(isValidAddress)

■■ Processing lists with loops

Loops are used to process lists of loops. Refer to the following example:
var address = “ab@rock.org”;

Now, create the isValidAddress variable and set it to False:


var isValidAddress = false;

Next, create loop iterator:

var i = 0;

The while statement of the loop runs once for every character in the address. To be able to retrieve the numbers
of letters in a string, the string class’s instance variable length is used. Refer to the following example:
while (i < address.length) {

i++;

One of the characters in the address must be retrieved and compared to the string ‘@’ each time the loop body runs.
If the retrieved character is equal to ‘@’ then the isValidAddress is True. In order to retrieve a specific character
from a string, use the built-in String class’s instance method ‘charAt’, which is a short for ‘character at’, where
the character indices start at zero.

As per the example, the call expressions have the value ‘a’ because the character at index 0 is ‘a’.
address.charAt(0);

The validation code of the e-mail address is as follows:


var address = “abc@rock.org

var isValidAddress = false;

var i = 0;

while (i < address.length) {

if (address.charAt(i) = = “@”) {

isValidAddress = true;

i++;

■■ Ending a loop with a break statement

By using the following code, make a loop statement to terminate a loop:


var address = “ab@rock.org”;

var isValidAddress = false;

var i = 0;

while (i < address.length) {

if (address.charAt(i) ==”@”) {

isValidAddress = true;

break;

i++;

trace(isValidAddress);

For detailed step-by-step procedure, refer to demo Basics Programming Concept Loops from:
eResources 4 Me>> My Varsity>> Web Animation and Interactivity>> Show Me How>> Conditionals, Loops,
and Operators>> Loops

9.2.3 Operators
To perform calculations and to compare, modify, or combine variables, objects, properties, and expressions, special
symbols or words are used. These are called operators. Operands are values – variables, literals, or expressions used
as inputs by an operator. Operators can be of various types:
¾¾ Arithmetic operators
¾¾ Assignment and compound assignment operators
¾¾ Equality and comparison operators
¾¾ Logical operators
■■ Arithmetic operators

The additive and multiplicative operators (+, -, *, /) take two operands and perform appropriate calculations.

The modular operator returns the remainder after a division operation. Increment (++) and decrement (--) are unary
operators and therefore require only one operand. They either add (increment) or subtract (decrement) 1 from the
expression they are used on, and it can be used either as prefix or postfix operators. Refer to Table 9.4.

Operator Operation Performed


+ It adds numbers.
- It subtracts numbers.
* It multiplies two numeric expressions.
/ It divides expressions1 by expressions2
% Modulo calculates the remainder of expressions1 divided by expressions2
++ This is an increment that adds 1 to a numeric expression.
-- This is a decrement that subtracts 1 from a numeric expression.
Table 9.4: List of Arithmetic Operators
■■ Assignment and Compound assignment operators

The assignment operator assigns the value of expression on the right to the expression on the left. Compound
assignment operators perform arithmetic on a variable and then store the result in that same variable. Refer to Table
9.5.
Operator Operation Performed
= This is assignment. It assigns the value of expression2 to the variable in expression1.
+= This is addition assignment. It assigns expression1 the value of expression1 + expression2.
-= This is subtraction assignment. It assigns expression1 the value of expression1 - expression2.
*= This is multiplication assignment. It assigns expression1 the value of expression1*
expression2.
/= This is division assignment. It assigns expression1 the value of expression1 /expression2.
%= This is modulo assignment. It assigns expression1 the value of expression1/expression2.
Table 9.5: List of Assignment and Compound assignment operators
■■ Equality operators

The equality operators take two operands, compare their values, and return a Boolean value. The relational operators
take two operands, compare their values, and return a Boolean value. Refer to Table 9.6.

Operator Operation Performed


== It specifies equality. It tests two expressions for equality (==) operator. If the
expressions are equal the result is true.
!= It specifies inequality. It tests for the exact opposite of the equality. The result is
False if expression1 is equal to expression2.
=== It implies strict equality. It tests two expressions for equality. If both expressions are
equal, including their data, the result is True.
!== It implies strict inequality. It tests for the exact opposite of the strict equality (===)
operator. The result is False if expression1 is equal to expression2, and also if their
data types are equal.
< It implies less than. It compares two expressions and determines whether
expression1 is less than expression2, and if it is so then the result is True.
> It implies greater than. It compares two expressions and determines whether
expression1 is greater than expression2, and if it is so then the result is True.
<= It implies less than or equal to. It compares two expressions and determines
whether expression1 is less than or equal to expression2, and if it is so then the
result is True.
>= Implies greater than or equal to. It compares two expressions and determines
whether expression1 is greater than or equal to expression2, and if it is so then the
result is True.
Table 9.6: List of Equality and Comparison operators
■■ Logical operators

Operators that take two operands and return a Boolean result are known as Logical operators, and they are used to
combine conditions. Refer to Table 9.7.

Operator Operation Performed


! The Logical NOT inverts the Boolean value of a variable or expression.
&& This is Logical AND. If it is False, it returns expression1 or can be converted to False and
expression2. If both operands are True and are of type Boolean, the result is True.
|| This is Logical OR. If it is true, it returns expression1 or can be converted to True and
expression2. The result is True if both operands are of type Boolean, and if either or both
expressions are True. The result is False, if both expressions are False. (It is also known as
the PIPE sign).
&&= This is Logical AND assignment. It assigns the value of expression1 & expression2 to
expression1.
Operator Operation Performed
||= This is Logical OR assignment. It assigns the value of expression1 || expression2 to
expression1.
Table 9.7: List of Logical operators

The operators that are used for creating Array and Objects literals, grouping expressions, calling functions,
instantiating class instances, and accessible properties are the primary operators.

A short hand method of applying the else conditional statement is called the conditional operator. There are some more
types of operators, such as Bitwise logical operators and Bitwise shift operators.

9.3 Static Variables and Static Methods


Variables can be declared with var or const keywords. Methods are functions that are part of a class definition.

9.3.1 Static Variables


Static variables are attached to a class and are used for storing and sharing information applicable to the class of
objects.

Static variables are used to keep track of information that relates logically to an entire class, as opposed to information
that varies from instance to instance.

Static variables are created using variable definitions within class definitions and must also include the static attribute
as shown in the following code:
class SomeClass {

static var identifier = value

Similar to instance variables, the static variables in a program use the access control modifiers to control the accessibility.
The access control modifiers that are available for static variable definitions are the same to those available for instance
variable definitions. Internal (package-wide access) is used when the modifier is not specified. Similarly, when a modifier
is specified, then it is positioned before the static attribute, as demonstrated in the following code:
class SomeClass {

private static var identifier = value;

Add static variables to the VirtualOffice class. There are two pieces of information in the VirtualOffice class:
the total resource and the maximum allocated Business Unit (BU).

The following example shows the total resource and maximum allocated BU definitions:
package office {

internal class VirtualOffice {

private static var totalResource = 100;

private static var maxAllocated BU1 = 10;

// Remainder of class not shown

9.3.2 Constants
A constant is a value that once initialized, remains fixed for the rest of that program. A constant could be a static variable,
instance variable, or a local variable. A standard variable-definition syntax is used to create a constant with the keyword
const instead of var.
¾¾ To create a constant static variable, the following code is used within a class body:
static const IDENTIFIER =value

¾¾ To create a constant instance variable, the following code is used within a class body:
const IDENTIFIER =value

¾¾ To create a constant local variable, the following code is used within a class body:
const IDENTIFIER =value

Constants have fixed values that cannot be altered.

9.3.3 Static Methods


Static methods are attached to a class, and hence they are also called as class methods. They are declared with a
static keyword. Static methods provide functionality that does not directly affect the value of a class instance. Static
methods are created by using function definitions within the class definitions that also include the static attribute.
Refer to the following code:
class SomeClass

static function methodName (identifier1 = value1,

identifier2 = value2,…

identifiern = valuen) {

Similar to instance methods, the accessibility of static methods in a program can be controlled by access control
modifiers. The access control modifiers existing for static methods definitions are same as those available for instance
method definitions.

Internal is used when no modifier is specified. Likewise, when a modifier is specified, then it is placed before the static
attribute. To invoke a static method, the following code is used:
SomeClass.methodName(value1, value2,...value‘n’)

In this code, SomeClass is the class within which the static method is defined, methodName is the name of the method,
and value1, value2, ...value ‘n’ is a list of zero or more method arguments.

9.4 Functions
Function is a set of instructions that carry out tasks that are independent of any class or object. Functions have the same
syntax and usage as instance methods and static methods. They are defined with the function keyword and are used
in standalone form.

Blocks of code that carry out specific tasks and can be reused in a program are called Functions. In AS3, the two types
of function are as follows:
¾¾ methods
¾¾ function closures
Depending on the context in which the function is defined, a function is called a method or a function closure. If a function
is defined as part of a class definition or attaches it to an instance of an object, it is called a method. If it is defined in any
other way, it is called a function closure.
Functions are of two types — namely, System defined or inbuilt function and User defined or external.

System defined or inbuilt functions are already defined in the system, so it need not be created again and can be used
directly. For example, ToString();, trace();, setInterval();, and so on.

To create a User defined function, the following code is used:


function identifier (param1, param2, …paramn) {

//user code

}
In this code, identifier is the name of the function and param1, param2, and paramn is an optional list of the function’s
parameters.

9.4.1 Package-level Functions


A function definition is placed directly within a package body to create a function that is available throughout a package
or an entire program that is preceded with the access control modifier internal, as shown in the following code:
package packageName

internal function identifier ( ) {

In order to make the function accessible throughout the program, the access control modifier public precedes as follows:
package packageName {

public function identifier ( )

ActionScript uses internal if no access-control modifier is specified.


■■ Global functions

Global functions are defined at the package-level within the unnamed package as they can be referenced globally
during a program, and does not need the import statement. As mentioned in the example, the following code defines
a global function, isLinux( ). Since the isLinux( ) function is defined within the unnamed package, it can be
accessed by any code in the same program.
package {

import flash.system.*;

public function isLinux ( ) {

return Capabilities.os == “Linux”;

}}

The isLinux( ) is used in the given Welcome class. Observe that isLinux( ) need not be imported before being
used.
package setup {

public class Welcome {

public function Welcome ( ) {

// Use isLinux( )if (isLinux( )) {

// Do something Linux-specific

}}}}

9.4.2 Nested Functions


A nested function is created when a function definition occurs within a method or another function and is available for
use only within the containing method or function.

Functions that can be declared within other functions are called as nested functions, and it is available only within its
parent function, unless a reference is given to external code as shown in the following example:
// Define method x ( )

Public function x ( ) {

// Invoke nested function y( )

y( );

// Define nested function y( )

function y( ) {

// Function body would be inserted here

The nested function can be invoked anywhere within the containing method. Access control modifiers, such as
public and internal, cannot be applied to nested functions.

9.4.3 Source-file-level Functions


A function definition that occurs at the top-level of a source file, outside any package body, creates a function that is
available within that specific source file only. The following example shows the code contents of a source file, A.as that
contains a package definition, a class definition, and a source-file-level function definition.
package {

// Ok to use f ( ) here

class A {

// Ok to use f ( ) here

public function A ( ) {

// Ok to use f( ) here

// Ok to use f ( ) here

function f ( ) {

}
Since the function is defined outside the package statement, it can be used anywhere within A.as, but cannot access
outside A.as. However, the f ( )’s definition does not include any access control modifier, such as public and internal.

9.4.4 Accessing Definitions from within a Function


Within a function closure, the this keyword always refers to the global object irrespective of where the function is
defined as shown in the following code:
public function a ( ) {

var currentObject = this;

function b ( ) {

// Access to currentObject is granted here

Trace(currentObject); // output the object through

// which a ( ) was invoked

}
9.4.5 Functions as Values
Every function in ActionScript is represented by an instance of the Function class that can be assigned to a variable,
passed to a function, or returned from a function like a value. The following code defines a function, p ( ) and then
assigns it to a variable q. The parentheses operator ( ) is omitted, if it were included, the code would assign p ( )’s
return value to q, as follows:
function p ( ) {

var q = p;

On assigning a variable to a function, it can be invoked through that variable using the standard parentheses operator,
( ).

In the following example the code invokes the function p( ) through the variable q:
p( );

For creating dynamic classes and objects, use function values.

9.4.6 Function Literal Syntax


Instances of the Function class can be created with literal syntax. Function literals have the same syntax except that
the function name is omitted as shown in the following code:
function (param1, param2, …paramn) {

As mentioned previously, param1, param2, …paramn is an optional list of parameters. The function can be assigned,
which is defined by a function literal outside the expression in which the literal occurs to a variable as follows:
var someVariable = function (param1, param2, …paramn) {

The function can then be invoked through that variable as follows:


someVariable (org1, org2, …orgn)

9.4.7 Recursive Functions


A recursive function calls itself as shown in the following example:
function trouble ( ) {

trouble ( );

A recursive function calls itself without conditions because if left unchecked, infinite recursion would trap a program in
an endless cycle of function execution. To avoid this, practical recursive functions calls themselves only when a given
condition is met.

Example 1: Calculating factorials using recursion.


function factorial (n) {

if (n < 0) {

return; // Invalid input, so quit

} else if (n <= 1) {

return 1;

} else {

return n * factorial(n-1);

// Usage:

factorial(3); // Returns: 6

factorial(5); // Returns: 120

Usually, a factorial can be calculated without recursion, as shown in Example 2.


Example 2: Calculating factorials without recursion.
function factorial (n) {

if (n < 0) {

return; // Invalid input, so quit

} else {

var result = 1;

for (var i = 1; i <= n; i++) {

result = result * i;

}return result;

}}

Examples 1 and 2 show two different ways to solve the same problem. As per the recursive approach, “The factorial
of 6 is 6, multiplied by the factorial of 5. The factorial of 5 is 5, multiplied by the factorial of 4...”, and so on. Whereas,
the nonrecursive approach loops over the numbers from 1 to n and multiplies all of them together into one big number.
Function recursion provides a simple solution by calling the same function repeatedly and moving on to a complex
problem. Repeated function calls are less competent than loop iterations. The nonrecursive approach to calculating
factorials is more efficient than the recursive approach.

For detailed step-by-step procedure, refer to demo Working with Functions from:

eResources 4 Me>> My Varsity>> Web Animation and Interactivity>> Show Me How>> Functions>> Recursive functions

9.5 Arrays
Multiple values can be stored in a single data structure with the help of arrays. Arrays can also be multidimensional,
containing elements that are themselves arrays.

9.5.1 Basics of an Array


A programming element that acts as a container for a set of items, such as a list of songs is called as an array. It is
usually seen that all the items in an array will be instances of the same class, but that is not a prerequisite in ActionScript.
The array elements are the individual items in an array. Variables can be used as elements in the array, which is similar
to putting a folder in the file drawer. When there are many files in the drawer, work with the array as a single variable.
For example,
¾¾ Carrying the whole drawer to a different location
¾¾ Flipping through the folders one by one searching for a piece of information
¾¾ Accessing them individually (like opening the drawer and selecting a single folder)
Arrays are a fundamental tool in sequential and repetitive programming as it stores and manipulate ordered lists of
information, for example a grocery list. A data structure that contains multiple individual data values in an ordered list is
called an array.

The examples show two separate strings that are followed by an array containing two strings as follows:
“bananas” // A single string

“mangoes” // Another string

[“apples”, “berries”] // A single array containing two strings

An array can contain both strings and numbers as follows:


[“bananas”, 12, “mangoes”, 6, “apples”, 4];

Some of the common array tasks are as follows:


¾¾ Creating indexed arrays
¾¾ Adding and removing array elements
¾¾ Sorting array elements
¾¾ Extracting portions of an array
¾¾ Working with associative arrays and dictionaries
¾¾ Working with multidimensional arrays
¾¾ Copying array elements
¾¾ Creating an array subclass

9.5.2 Importance of Creating Arrays in Programming


Arrays are vital in programming languages as it provides influential attribute that builds a complex type of data structure,
which is similar to the execution of stacks and queues. Arrays are defined as a fixed collection of homogeneous elements.
In other words, an array has the ability to store the same type of items, which are either all floating numbers, all integer
numbers, string, and so on, ensuring that the data is of the same type.

Following are some important features about array:


¾¾ It has a zero index.
¾¾ All the data can be stored as items in the array in consecutive memory locations.
¾¾ It can be stored under a common heading or a variable name.
¾¾ It can either be a character, an integer, or floating point data item, which is initialized only on declaration time
not afterwards.
¾¾ It can always be read or written through loops.
9.5.3 Anatomy of an Array
Each individual item in an array is called as an element, and each element has a specific numeric position also known
as index.
¾¾ Array elements
Each array element can be assigned any value. An entire array is a collection of sequentially named variables
and each item has an element number (the first element is 0 and not 1). In order to manipulate, the array
elements are arranged by number.
¾¾ Array element indexing
The position of an element in an array is known as its index, which can be used to set or retrieve the element’s
value. Elements can be inserted or deleted from the beginning or end, or even middle of an array. An array can
have gaps, which means some elements can be empty. Array with gaps are called sparse arrays.
¾¾ Array size
A particular array, at any point during its life span, has a specific number of elements both empty and occupied.
The number of elements in an array is called the array’s length.

9.5.4 Creating Arrays


Array literal or the new operator [new Array( ) ] is used to create a new array. The square brackets demarcate the
beginning and end of the array. The values of the array elements are specified inside the square bracket as a comma-
separated list, given as follows:
[expression1, expression2, expression3]

There are differences in the ways arrays are implemented across different languages as many languages do not allow
arrays to contain different types of data. An array can contain numbers or strings, but not both in the same array.

An array within an array is called a nested array or a two-dimensional array as given in the following example:
// Simple numeric elements

[6. 7, 8];

// Simple string elements

[“bananas”, “mangoes”, “berries:]

// Numeric expressions with an operation

[2, 4, 5 + 9]

// Numeric values and strings as elements

[firstClass, secondClass, “fair”, “short”]

// A nested array literal

[“month middle days”, [ 16, 17, 18] ]

To create an array with a new operator, the following code is used.


new array(arguments)

When more than one argument is supplied, or when a single non-numeric argument is supplied, then each argument
becomes one of the element values in the new array, as given in the following example:
new Array(“book”, “pencil”, “ruler”)

Following is an example of an array with 12 empty elements.


new array(12)

9.5.5 Referencing Array Elements


To retrieve or change the value of its elements on creating an array, the array access operator, [ ] is used.

The element’s index is written within square brackets, as follows:


theArray[elementNumber]

Example:
var names:Array = new Array(“Jerry”, “Sam”, “Dan”);
trace(names[0]); // output: Jerry

trace(names[1]); // output: Sam

trace(names[2]); // output: Dan

9.5.6 Determining the Size of an Array


An instance variable named length indicates the current number of elements in the array. The dot operator is used to
access an array’s length variable as given in the following way:
theArray.length

Example:
var names:Array = new Array(“Jerry “, “Sam”, “Kate”)

trace(names.length); // output: 3

Example:
var student:Array = new Array(35);// Note the single numeric argument

// used with the Array ( ) constructor

trace(student.length);// output: 35
9.5.7 Adding Elements to an Array
There are three Array class methods: push( ), unshift( ), and splice( ), or concat( ) that allow inserting of
elements in an array.

¾¾ push( ) method
In the push( ) method, one or more elements are appended to the end of an array, which simply means that
this method will have the highest index number if the last element inserted into the array is used.

Syntax:
theArray.push(item1, item2,...itemn);

Example:
// Create an array with two elements

var menuItems:Array = [“home”, “ about us”];

// Add an element

menuItems.push(“products”, “services”, “contact”);

trace(menuItems); // output: home, about us, products, services, contact

¾¾ unshift( ) method
By using the unshift( ) method, which is always at index number 0, one or more elements can be inserted
at the beginning of an array.

Syntax:
theArray. unshift(item1, item2,...itemn);

Example:

var menuItems:Array = [“home”, “about us”, ”products”, ”services”, ”contact”];

// Add an element using unshift

menuItems.unshift(“site map”);

trace(menuItems); // output: site map, home, about us, products, services, contact

¾¾ splice( ) method
By using the splice( ) method any number of items can be inserted at a specified index in the array.

Syntax:
theArray.splice(startIndex, deleteCount, item1, item2,...itemn)

As mentioned in the syntax, the array is a reference to an Array object; startIndex is a number that specifies
the index at which element removal and optional insertion should commence (remember that the first element’s
index is 0); deleteCount is an optional argument that dictates how many elements should be removed
(including the element at startIndex). When deleteCount is omitted, every element including startIndex
and thereafter is removed. The optional item1, item2, itemn parameters are items to be added to the array
as elements starting at startIndex.
Example:
var menuItems:Array = [“site map”, “home”, “about us”, ”products”, ”services”, ”contact”];

menuItems.splice(0, 1, “feedback”);

trace(menuItems); // output: feedback, home, about us, products, services, contact

¾¾ concat( ) method
Two or more arrays are combined by concat( ) method to form a single new array, which it returns. The
concat( )method has the following general form:
Syntax:
origArray.concat(elementList)

The concat( ) method appends the elements contained in elementList, one by one, to the end of origArray
and returns the result as a new array, leaving origArray untouched. Normally, the returned array is stored in
a variable. Here, simple two string items are to be added to the array as shown in the following example:
Example:
var menuItems:Array = [“home”, “about us”, “products”, “services”, “contact”];var
subMenuServices:Array=menuItems.concat(“Website Development”, “eLearning”);

trace(subMenuServices);

// output: home, about us, products, services, contact, Website Development, eLearning
9.5.8 Removing Elements from an Array
The three Array methods that allow to remove elements from an array are pop( ), shift( ), and splice( ).

¾¾ pop( ) method
The element at the highest index number is removed by the pop( ) method from the end of the array. The pop(
) method is the antithesis of push( ): it removes the last element of an array.

Syntax:
theArray.pop( )

Example:
var menuItems:Array = [“home”, “about us”, “products”, “services”, “contact”];

menuItems.pop( )

trace(menuItems); // output: feedback, home, about us, products, services

¾¾ shift( ) method
The shift ( ) method is used to remove the element from the beginning of the array as it always removes the
element at index number 0. However, the unshift ( ) method is used to add an element to the beginning of
an array.

Syntax:
theArray.shift( )

Example:
var menuItems:Array = [“home”, “about us”, “products”, “services”, “contact”];

menuItems.shift( )

trace(menuItems); // output: about us, products, services, contact

¾¾ splice( ) method
The splice( ) function can both remove elements from and add elements to an array. To remove an arbitrary
number of elements starting at the index number as specified by the first argument sent to the method, use the
splice ( ) method, which is also used to insert elements.
To remove element syntax, refer to the following code:

Syntax:
theArray.splice(startIndex, deleteCount)

Example:
var menuItems:Array = [“site map”, “home”, “about us”, ”products”, ”services”, ”contact”];

menuItems.splice(0, 1)

trace(menuItems); // output: home, about us, products, services, contact


9.5.9 Checking the Contents of an Array with the toString( ) Method
The method that is common to all objects and returns a string representation of the object upon which it is invoked
is called as toString( ). The toString method of an Array object returns a list of the array’s elements that are
converted to strings and separated by commas. It can be called as follows:
theArray.toString ( )

Example:
var menuItems:Array = [“home”, “about us”, “products”, “services”, “contact”];

menuItems.toString( )

trace(menuItems); // output: home, about us, products, services, contact

9.5.10 Multidimensional Arrays


Multidimensional arrays are also called as nested arrays. They contain other arrays as elements. In a two-dimensional
array, the elements are organized conceptually into a grid of rows and columns where the rows are the first dimension
of the array and the column are the second.

For example, consider a list of clothes:


var tshirt:Array = [3, 3.99]; // Quantity 3, Price 3.99

var shirt:Array = [2, 9.99]; // Quantity 2, Price 9.99

var jeans:Array = [1, 69.99]; // Quantity 1, Price 69.99

Next, the clothes are placed into a container array named spreadsheet as shown in the following example:
var spreadsheet:Array = [tshirt, shirt, jeans];

By multiplying the quantity and the price of each row and adding them all together, the total cost of the order can be
found. A two-dimensional array’s elements using two indexes (one in the rows and one for the column) can be accessed.
The expression (0) represents the first row’s two-column array. The spreadsheet [0] [1] can be used, which yields 3.99.
Following are the steps to calculate the total price of the items in the spreadsheet:
// Create a variable to store the total cost of the order.

var total: Number;

// Now find the cost of the order. For each row, multiply the columns

// together, and add that to the total.

for (var i: int = 0; i < spreadsheet.length; i++) {

total += spreadsheet [i] [0] * spreadsheet [i] [1];

trace(total); // output: 101.94

For detailed step-by-step procedure, refer to demo Working with Arrays from:

eResources 4 Me>> My Varsity>> Web Animation and Interactivity>> Show Me How>> Arrays>> Multidimensional
arrays
9.6 Summary
In this session, Introduction to ActionScript 3.0 and Programming Concept, you learned that:
¾¾ There are two kinds of programming techniques: top-down approach, and bottom-up approach.
¾¾ AS3 Execution: AS3 helps load SWF file written in AS1 or AS2.
¾¾ Classes and Objects: Classes are blueprints on which objects are based. Each class describes in code the
characteristics and behavior of an object.
¾¾ Building a Program: Design base forms the basis of development of a new ActionScript program that is broken
into logical set of classes.
¾¾ Packages: These help in bundling class definitions to facilitate code sharing and reduce naming conflicts.
¾¾ Access Control Modifiers: For classes, it helps to specify which classes can instantiate or access property.
¾¾ Code Comments: These are notes that a programmer can read and the compiler can ignore.
¾¾ Constructor methods are functions that share the same name as the class in which they are defined.
¾¾ Creating objects is a process of instantiating the object.
¾¾ AS3 data types are of two kinds — namely, Primitive and Complex.
¾¾ Variables and Values: An identifier or a name with a value is called a variable. The four types of variables are:
local, instance, dynamic, and static.
¾¾ ActionScript provides two Conditionals: the if statement, and the switch statement.
¾¾ Operators are special symbols that perform calculations. The four types of Operators are: Arithmetic, Assignment
and Compound, Equality and Comparison, and Logical.
¾¾ Functions are a set of instructions. The two types of Functions are methods and functional closure.
¾¾ Arrays act as a container for a set of items, for example, a list of songs.
¾¾ Adding elements to an array are done by three methods, namely — push( ), unshift( ), and splice( )
methods.

¾¾ Removing elements from an array can be done by three methods: pop( ), shift( ), and splice( ) methods.
¾¾ Multidimensional arrays are arrays themselves. They are also called as nested arrays.
9.7 Exercise
1. The process of converting an ActionScript program into a bytecode is called as _________.

Flash runtime

Compiling a program

Adobe AIR

OOP method

2. Which of these is a primitive value data type?

String

Date

MovieClip

XML

3. A special type of local variable that is created as a part of the constructor-method definition is called a
________________.

Constructor parameter

Constructor argument

Constructor body

Constructor function

4. Increment (++) and decrement (--) are unary operators and therefore require only one operand.

True

False

5. Variables can be declared only with var keyword.

True

False
Session 10
Working with Built-in Classes (Text, Video, and Sound)
Learning Outcomes
In this session, you will learn to:
¾¾ Differentiate between the different types of text
¾¾ Identify different tasks that can be performed using text
¾¾ Explain the use of media class, such as video and sound

10.1 Working with Text


10.1.1 Identifying the Types of Text
Text handling is one of the basic requirements of Web application development. Different types of text are as follows:
¾¾ Dynamic text: Content that is loaded from an external source is included in this type of text. For example,
an XML file, text file, a remote Web service, or any Flash program that generates an output and needs to be
displayed on screen.
¾¾ Input text: Any text that is entered by a user or a dynamic text that a user can edit is an input text. To assign
properties to the text field for the input content, the flash.text.TextFormat class can be used, or a style
sheet can be set to format input text.
¾¾ Static text: Text that can be created only through the Flash authoring tool and not by ActionScript 3.0 (AS 3.0)
is a static text. However, to manipulate an existing static text instance, ActionScript classes like StaticText
and TextSnapshot can be used.

Text is characterized by its source.

In AS 3.0, there are different built-in classes to perform text handling tasks. Some of them that can be performed using
classes are as follows:
¾¾ Modifying text field contents
¾¾ Using HTML in text fields
¾¾ Using images in text fields
¾¾ Selecting and manipulating text
¾¾ Capturing text input
¾¾ Restricting text input
¾¾ Applying formatting
¾¾ Cascading Style Sheets (CSS) styles to text
¾¾ Formatting text

An instance of a built-in TextField class is used to display text on the screen in Adobe Flash Player. The text can be
populated in the TextField from a text file or database. The text within a text field can appear as HTML content along
with images that are embedded in the rendered HTML format.

In addition, flash.text package classes can be used to establish an instance of a TextField to control the text’s
appearance. This is similar to the TextFormat and the StyleSheet classes. All the classes related to creating,
managing, and formatting text in ActionScript are in the flash.text package.

The properties defining the appearance of the text, such as size, color, and weight are present in the TextFormat
object or StyleSheet object.

Text can be formatted using a TextFormat object, which is then assigned to the text field. Using the StyleSheet
object, styles can be assigned to specific pieces of the text field content.
The properties of the TextFormat object are assigned to all the contents that are within a range of text or text field. For
example, one sentence can be in blue italic text and the other can be bold green text. StyleSheet can be applied to
the text field, if it contains HTML text.
■■ Common tasks for working with text

There are two types of examples.


¾¾ Example 1: This type manipulates a text field object without creating the object openly. Refer to Figure 10.1.
The code listing can be tested by:

●● Creating an empty Flash document

●● Selecting a keyframe in the Timeline

●● Opening the Actions panel and copying the code listing into the Script pane

Figure 10.1: Steps for manipulating a text field object without creating the object openly
¾¾ Example 2: This type defines a class in a code listing, which can be used as the document class for the SWF.
Refer to Figure 10.2. Here, a TextField instance is created by the example code, so it need not be created
separately.

Figure 10.2: Steps in defining a class in a code listing, which can be used as the document class for the SWF

■■ Modifying TextField contents

Adobe Flex Builder and Flash authoring tools provide many options for displaying text that include text tools or
text-related components. However, the primary way to display text programmatically is through a TextField. The
TextField values include text strings or variables.

Strings help in working with many objects, such as TextField, StaticText, XML, ContextMenu, and
FileReference objects. Methods of the String class allow working with text strings.

By assigning a string to the flash.text.TextField.text property, dynamic text can be defined. A string can
be directly assigned to the flash.text.TextField.text property. Refer to the following code:
myTextField.text = “Hello Friend”;

Variables are the primary information storage of ActionScript that help to retrieve all the information. A value from
a variable defined in the script can also be assigned to a text property. The given example demonstrates how a
variable can be assigned to a text property:
package

import flash.display.Sprite;

import flash.text.*;

public class TextWithImage extends Sprite

private var myTextBox:TextField = new TextField();

private var myText:String = “Hello World”;

public function TextWithImage()

addChild(myTextBox);

myTextBox.text = myText;

A value from a remote variable can also be assigned to a text property. For loading text values from remote sources,
any one of the following three options can be used:
¾¾ flash.net.URLLoader and flash.net.URLRequest classes: This helps load variables for the text from a
local or remote location.
¾¾ FlashVars attribute: This contains values for text variables and is embedded in the HTML page hosting the
SWF file.
¾¾ flash.net.SharedObject class: This class manages the storage of values.
■■ Using HTML in TextFields
By using the flash.text.TextField class that has an htmlText property, the text string containing HTML tags
for formatting the content can be identified.

In ActionScript 3.0 Language and Components Reference, the flash.text.TextField.htmlText property


describes the supported HTML tags and entities in detail. A subset of HTML tags and entities for the htmlText
property is supported by Flash Player. On designating the content using the htmlText property, the style sheets or
the textformat tag can be used for formatting the content.

For example, for Flash Player, to display the text as HTML, the string value can be assigned to the htmlText
property, as given in the following example:
var myText:String = “<p>This is <b>some</b> content to <i>render</i> as

<u>HTML</u> text.</p>”;

myTextBox.htmlText = myText;

In the given example, text “This is some content to render as HTML text” is formatted in HTML and assigned to a
string variable. This string is then assigned to a text field to be displayed as its text value is formatted with HTML.
■■ Using images in TextFields

Another advantage of displaying content as HTML text is using images in the text fields. Any local or remote image
can be accessed by using the img tag and allowing it to appear within the associated text field.

The following example displays how to create a text field named ‘myTextBox’ and include a JPG image of an ear,
stored in the same directory as the SWF file:
package

import flash.display.Sprite;

import flash.text.*;

public class TextWithImage extends Sprite

private var myTextBox:TextField;

private var myText:String = “<p>This is <b>some</b> content to

<i>test</i> and <i>see</i></p><p><img src=’ear’.jpg’ width=’20’

height=’20’> </p><p>what can be rendered?</p><p>You should see an ear

image and some <u>HTML</u> text.</p>”;

public function TextWithImage()

myTextBox.width = 200;

myTextBox.height = 200;

myTextBox.multiline = true;

myTextBox.wordWrap = true;

myTextBox.border = true;

addChild(myTextBox);

myTextBox.htmlText = myText;

■■ Scrolling text in TextFields

The following scroll-related properties of the flash.text.TextField class can be used to manage vertically (V)
or horizontally (H) lengthy content. These properties help to respond to events, such as clicking or pressing:
¾¾ TextField.scrollV
¾¾ TextField.scrollH
¾¾ maxScrollV
¾¾ maxScrollH
The following example displays how a text field can be created with a set size containing more text so that it can be
displayed at one time. Here, the text scrolls vertically as the user clicks the TextField.
package

import flash.display.Sprite;

import flash.text.*;

import flash.events.MouseEvent;

public class TextScrollExample extends Sprite

{
private var myTextBox:TextField = new TextField();

private var myText:String = “Hello friend and welcome to the party. It’s really nice to
see you. Come and take your seat. Hope you will enjoy the evening. I have arranged some
fun games. Don’t forget to eat the cake and whole lot of snacks.”

public function TextScrollExample()

myTextBox.text = myText;

myTextBox.width = 200;

myTextBox.height = 50;

myTextBox.multiline = true;

myTextBox.wordWrap = true;

myTextBox.background = true;

myTextBox.border = true;

var format:TextFormat = new TextFormat();

format.font = “Verdana”;

format.color = 0xFF0000;

format.size = 10;

myTextBox.defaultTextFormat = format;

addChild(myTextBox);

myTextBox.addEventListener(MouseEvent.MOUSE_DOWN, mouseDownScroll);

public function mouseDownScroll(event:MouseEvent):void

myTextBox.scrollV++;

10.1.2 Selecting and Manipulating Text


An action that can be performed by an object is called a method, and an index is the position at which an object is
displayed on the display list.

By selecting dynamic or input text, the text selection properties and methods of the TextField class programmatically
selects dynamic or input text. Even if the content is unknown, it uses the index positions to set the range of text to
manipulate.

On choosing the selectable option on a static Textfield in the Flash authoring tool, a regular dynamic Textfield
can be exported and placed on the display list.

By using the setSelection() method, the text can be selected programmatically in a text field. By default, the
flash.text.TextField.selectable property is set to true. For example, when the user clicks the text field, a
specific text can be set within a text field which is to be selected. Refer to the following example:
var myTextField:TextField = new TextField();

myTextField.text = “No matter where you click this text field the TEXT IN

ALL CAPS is selected.”

myTextField.autoSize = TextFieldAutoSize.LEFT;

addChild(myTextField);

addEventListener(MouseEvent.CLICK, selectText);

function selectText(event:MouseEvent):void

myTextField.setSelection(49, 65);

The technique for specifying certain actions that should be performed in response to particular events is known as
event handling. This system allows programmers to respond to user input and system events in a convenient way.

On selecting a text within a Textfield, the text is initially displayed, an event handler function has to be created
called as the Textfield, and it is then added to the display list.

In ActionScript 3.0, an event object represents each event that belongs to an instance of the Event class or one
of its sub-classes. An event object contains methods that assist manipulation of the event object and also stores
information about a specific event.

For detailed step-by-step procedure, refer to demo Working with Text Dynamic from:

eResources 4 Me>> My Varsity>> Web Animation and Interactivity>> Show Me How>> Working with Text>>
Selecting and manipulating text

10.1.3 Capturing Text Input


When a user selects a text from a complete string or a paragraph, the selectionBeginIndex and selectionEndIndex
is captured programmatically.

However, the properties of the TextField class, selectionBeginIndex and selectionEndIndex, cannot be
set programmatically, as they are ‘read-only’. However, these properties can be used by the user to capture text that is
selected. Moreover, the caretIndex property can be used by input text fields. The following example shows how the
code traces the index values of user-selected text:

var myTextField:TextField = new TextField();

myTextField.text = “Please select the TEXT IN ALL CAPS to see the index values for the
first and last letters.”;

myTextField.autoSize = TextFieldAutoSize.LEFT;

addChild(myTextField);

addEventListener(MouseEvent.MOUSE_UP, selectText);

function selectText(event:MouseEvent):void

trace(“First letter index position: “ + myTextField.selectionBeginIndex);

trace(“Last letter index position: “ + myTextField.selectionEndIndex);

}
By default, the property of a text field’s type is set to dynamic. However, user input can be collected and the
value can be saved for use in other parts of the application, if the type property is set to input using the
TextFieldType class.

Input text fields are useful for forms and any application that wants the user to define a text value for use, elsewhere
in the program.

In the given example, the code creates myTextBox, which is an input text field. The textInput event gets triggered
as soon as the user enters text in the field. An event handler, textInputCapture, assigns it as a variable and
captures the string of text entered. The new text created is basically another text field called myOutputBox, which
is displayed by Flash Player.
package

import flash.display.Sprite;

import flash.display.Stage;

import flash.text.*;

import flash.events.*;

public class CaptureUserInput extends Sprite

private var myTextBox:TextField = new TextField();

private var myOutputBox:TextField = new TextField()

private v

ar myText:String = “Type your text here.”

public function CaptureUserInput()

captureText();

public function captureText():void

myTextBox.type = TextFieldType.INPUT;

myTextBox.background = true;

addChild(myTextBox);

myTextBox.text = myText;

myTextBox.addEventListener(TextEvent.TEXT_INPUT, textInputCapture);}

public function textInputCapture(event:TextEvent):void {

var str:String = myTextBox.text;

createOutputBox(str);

myOutputBox.x = 200;

addChild(myOutputBox);

myOutputBox.text = str;
}

10.1.4 Restricting Text Input


Input text fields are commonly used in applications for forms or dialog boxes. In such input text fields, users can either
limit the types of characters entered in a text field, or hide the text as used for passwords. The flash.text.TextField
class has a restrict property and a displayAsPassword property that help users to control text input.

When the user enters text, the displayAsPassword property keeps the text hidden and displays the same as a series
of asterisks.

The Cut and Copy commands and other keyboard shortcuts do not function when the displayAsPassword is set to
true. This property can be assigned for the background and color as given in the following example:
myTextBox.type = TextFieldType.INPUT;

myTextBox.background = true;

myTextBox.displayAsPassword = true;

addChild(myTextBox);

Since the restrict property is complicated, the user needs to specify the characters that are allowed in an input text
field. Only specific letters, numbers, and characters can be allowed.

The following code allows the user to enter only uppercase letters (and not numbers or special characters) in the text
field:
myTextBox.restrict = “A-Z”;

For detailed step-by-step procedure, refer to demo Working with Text Input from:

eResources 4 Me>> My Varsity>> Web Animation and Interactivity>> Show Me How>> Working with Text>> Restricting
text input

10.1.5 Formatting Text


■■ Applying Cascading Style Sheets (CSS) styles to text

Text fields are either plain text or HTML – formatted text. The text property of the instance is stored in plain text and
the HTML text is stored in the htmlText property.

To define text styles and apply them to many different text fields, the CSS style declarations can be used, which can
be created in application code loaded at run time from an external CSS file.

The flash.text.StyleSheet class handles CSS styles and the StyleSheet class recognizes a limited set of
CSS properties. Following example shows how CSS can be created in code and applied by using a StyleSheet
object to HTML text:
var style:StyleSheet = new StyleSheet();

var styleObj:Object = new Object();

styleObj.fontSize = “bold”;

styleObj.color = “#FF0000”;

style.setStyle(“.darkRed”, styleObj);

var tf:TextField = new TextField();

tf.styleSheet = style;

tf.htmlText = “<span class = ‘darkRed’>Red</span> apple”;

addChild(tf);
As seen in the example, on creating a StyleSheet object, a simple object is created to hold a set of style declaration
properties. After this, the StyleSheet.setStyle() method is called to add the new style to the style sheet with
the name “.darkred”. By assigning the StyleSheet object to the text field object’s StyleSheet property,
the Style sheet formatting is applied. Next, the Style sheet needs to be applied to a text field object before the
htmlText property is set to enable the CSS styles to take effect. If an input text field is assigned a style sheet, the
text shows the style sheet properties but the user is not allowed to enter new text into it.

The following ActionScript APIs on a text field with an assigned Style sheet cannot be used:
¾¾ The TextField.replaceText() method
¾¾ The TextField.replaceSelectedText() method
¾¾ The TextField.defaultTextFormat property
¾¾ The TextField.setTextFormat() method

If a style sheet is assigned to a text field, and the TextField.styleSheet property is set to null, then the tags and
attributes will be added to the contents of TextField.text and TextField.htmlText properties to incorporate
the formatting from the previously assigned style sheet.

The original htmlText property can be preserved by saving it in a variable before setting the style sheet to null.
■■ Loading an external CSS file

Loading CSS information from an external file at run time is more powerful. The visual style of text in the application
can be changed without changing ActionScript 3.0 source code. This can be done after the application has been
deployed and without redeploying the applications SWF file.

A string that contains CSS data into style declarations in the StyleSheet object is converted by the StyleSheet.
parseCSS() method. The following example displays how to load the content of the CSS file with the name
example.css:
p {

font-family: Times New Roman, Times, _serif;

font-size: 14;

h1 {

font-family: Arial, Helvetica, _sans;

font-size: 20;

font-weight: bold;

.bluetext {

color: #0000CC;

The content of the CSS file with the name example.css is loaded in this way.

Following is the ActionScript code for a class that loads the example.css file and applies the styles to TextField
content:
package

import flash.display.Sprite;

import flash.events.Event;

import flash.net.URLLoader;

import flash.net.URLRequest;

import flash.text.StyleSheet;

import flash.text.TextField;

import flash.text.TextFieldAutoSize;

public class CSSFormattingExample extends Sprite

var loader:URLLoader;

var field:TextField;

var exampleText:String = “<h1>This is a headline</h1>” +

“<p>This is a line of text. <span class=’bluetext’>” +

“This line of text is colored blue.</span></p>”;

public function CSSFormattingExample():void

field = new TextField();

field.width = 300;

field.autoSize = TextFieldAutoSize.LEFT;

field.wordWrap = true;

addChild(field);

var req:URLRequest = new URLRequest(“example.css”);

loader = new URLLoader();

loader.addEventListener(Event.COMPLETE, onCSSFileLoaded);

loader.load(req);

public function onCSSFileLoaded(event:Event):void

var sheet:StyleSheet = new S

field.styleSheet = sheet;

field.htmlText = exampleText;

The onCSSFileLoaded() method executes when the CSS data is loaded and calls the StyleSheet.parseCSS()
method to transfer the style declarations to the StyleSheet object.
■■ Applying formatting

The display of a text can be formatted programmatically by using any one of these properties such as TextField.
thickness, TextField.textColor, and TextField.textHeight. These properties can be set directly on
the text field instance.

Another way of formatting text is by using the htmlText property and the supported HTML tags, such as b (for
bold), i (for Italic), and u (for underline).

For consistency and control on the appearance of text throughout an application, use the TextFormat and
StyleSheet objects. Use the TextFormat object to apply on text fields containing plain text, and StyleSheet
objects to apply on text fields containing the htmlText property.

The TextFormat is used to set and apply a number of different text display properties to the entire contents of a
TextField object or to a range of text.

In the following example, one of the TextFormat object applies to an entire TextField object. Another
TextFormat object applies to a range of text within that TextField object. The text that is already displayed in
the text field is affected by the TextField.setTextFormat() method.

Thus, the application needs to call the TextField.setTextFormat() method again to reapply the formatting
if the content in the TextField changes. The TextField object’s default TextFormat property can be set to
specify the format to be used for user-entered text.

Notice the following example which shows how to assign text formats:
var tf:TextField = new TextField();

tf.text = “Hello Hello”;

var format1:TextFormat = new TextFormat();

format1.color = 0xFF0000;

var format2:TextFormat = new TextFormat();

format2.font = “Courier”;

tf.setTextFormat(format1);

var startRange:uint = 6;

tf.setTextFormat(format2, startRange);

addChild(tf);

■■ Formatting ranges of text within a TextField

The setTextFormat()method is a very useful method of the flash.text.TextField class. By using


setTextFormat(), specific properties can be assigned to parts of a text field’s content so as to respond to user
input. For example, forms that remind users about certain entries or to change a subsection of a text within a text
field as the user selects parts of the text.

In the following example, the TextField.setTextFormat() is used on a range of characters to change overall
appearance of a portion of content of myTextField, on clicking the text field.
var myTextField:TextField = new TextField();

myTextField.text = “No matter where you click this text field the TEXT IN

ALL CAPS changes format.”;

myTextField.autoSize = TextFieldAutoSize.LEFT;

addChild(myTextField);

var myformat:TextFormat = new TextFormat();

myformat.color = 0xFF0000;

myformat.size = 18;
myformat.underline = true;

function changeText(event:MouseEvent):void

myTextField.setTextFormat(myformat, 49, 65);

}
10.1.6 Advanced Text Rendering
A variety of classes in the flash.text package are provided by ActionScript 3.0 that helps to control the properties of
displayed text. This includes anti-aliasing settings, embedded fonts, alpha channel control, and other specific settings.
■■ Embedding a font in Flash

The Flash authoring tool helps to embed fonts like TrueType fonts and Type 1 Postscript fonts. The following are the
ways to embed fonts in a Flash application:

¾¾ Setting the font and style properties of a TextField on the Stage and clicking the Embed Fonts check box
¾¾ Creating and referencing a font symbol
¾¾ Creating and using a run-time shared library containing embedded font symbols
■■ Controlling sharpness, thickness, and anti-aliasing

Flash Player determines the settings for text display controls like thickness, sharpness, and anti-aliasing as text
resizes, changes color, or is displayed on various backgrounds by default.

An important feature of Flash Player is to maintain control over the settings of very small or very large text,
or text on a variety of unique backgrounds. By using the flash.text.TextRenderer class and its associated
classes, like the CSMSettings class, the Flash Player settings can be overridden and these classes help give
total control over the rendering quality of embedded text.

To be able to set the sharpness, thickness, or gridFitType property, or to use TextRenderer.


setAdvancedAntiAliasingTable()method, the flash.text.TextField.antiAliasType property must
have the value AntiAliasType.ADVANCED (the default value).

The following example displays how to apply custom Continuous Stroke Modulation (CSM) properties and formatting
to displayed text, using an embedded font called myFont.
var format:TextFormat = new TextFormat();

format.color = 0x336699;

format.size = 48;

format.font = “myFont”;

var myText:TextField = new TextField();

myText.embedFonts = true;

myText.autoSize = TextFieldAutoSize.LEFT;

myText.antiAliasType = AntiAliasType.ADVANCED;

myText.defaultTextFormat = format;

myText.selectable = false;

myText.mouseEnabled = true;

myText.text = “Hello Friend”;


addChild(myText);

myText.addEventListener(MouseEvent.CLICK, clickHandler);

function clickHandler(event:Event):void

var myAntiAliasSettings = new CSMSettings(48, 0.8, -0.8);

var myAliasTable:Array = new Array(myAntiAliasSettings);

TextRenderer.setAdvancedAntiAliasingTable(“myFont”, FontStyle.ITALIC,

TextColorType.DARK_COLOR, myAliasTable);
}
10.1.7 Working with Static Text
Static text can be created within the Flash authoring tool. It is useful only if the static text is short and does not intend
to change. It is similar to a graphic element drawn on the Stage like a square or a circle in the Flash authoring tool. It
can be programmatically instantiated by using the ActionScript. However, the ability to read the property values of static
text using the flash.text.StaticText class is supported by ActionScript 3.0. Moreover, to read the values out of the
static text, the flash.text.TextSnapshot class can be used.

■■ Accessing static text fields with the StaticText class

To interact with a static text instance placed on the Stage, use the flash.text.StaticText class in the Actions
panel of the Flash authoring tool. It is also possible to work in ActionScript files that interact with an SWF file
containing static text, but it cannot be instantiated programmatically. It can be created in Flash CS3 authoring tool.
The items can be repeated in the display list and assigned a variable to create a reference to an existing static
TextField in ActionScript 3.0 as given in the following example:
for (var i = 0; i < this.numChildren; i++) {

var displayitem:DisplayObject = this.getChildAt(i);

if (displayitem instanceof StaticText) {

trace(“a static text field is item “ + i + “ on the display list”);

var myFieldLabel:StaticText = StaticText(displayitem);

trace(“and contains the text: “ + myFieldLabel.text);

} }
Properties of static TextField can be used in ActionScript 3.0 on having a reference to a static text field.

The following code is attached to a frame and assumes a variable named ‘myFieldLabel’ that is assigned to a
static text reference.

As given in the following example, a dynamic text field named myField is positioned relative to the x and y values
of ‘myFieldLabel’ and displays the value of ‘myFieldLabel’ again:
var myField:TextField = new TextField();

addChild(myField);

myField.x = myFieldLabel.x;

myField.y = myFieldLabel.y + 20;

myField.autoSize = TextFieldAutoSize.LEFT;

myField.text = “and “ + myFieldLabel.text \

■■ Using the TextSnapshot class

To retrieve values or select parts of a static text instance, apply methods to that instance. For this use the flash.text.
TextSnapshot class to work with the textSnapshot property of a flash.display.DisplayObjectContainer.

In the following example, an existing static field is placed containing the text “TextSnapshot Example” on the
Stage. Add the following ActionScript to Frame 1 of the Timeline:
var mySnap:TextSnapshot = this.getTextSnapshot();

var count:Number = mySnap. charCount ();

mySnap.setSelected(0, 4, true);

mySnap.setSelected(1, 2, false);

var myText:String = mySnap.getSelectedText(false);

trace(myText);
In case, the text has to be used as a value in another part of an application, then use the TextSnapshot class for
getting the text out of static text fields in a loaded SWF.

For detailed step-by-step procedure, refer to demo Working with Text Static from:

eResources 4 Me>> My Varsity>> Web Animation and Interactivity>> Show Me How>> Working with Text>> Using
the TextSnapshot Class

Quick Test 10.1


1. The flash.text.TextField class has a _________ property and a displayAsPassword property that help
users to control text input.
limit void restrict parameter

2. A value from a remote variable can also be assigned to a text property.


True False

10.2 Working with Video


By using ActionScript, the user can have better control over displaying, loading, and controlling playback of video. This
means customized video player skin can be created for different video.

10.2.1 Basics of Video


Working with video in ActionScript involves a combination of classes such as Video class, NetStream class, and
Camera class.

To load external video, load the file from a standard Web server for progressive download playback, or work with
streaming video such as Adobe’s Macromedia Flash Media Server. The following are the video-related tasks:
¾¾ Displaying and controlling video on the screen
¾¾ Loading external FLV files
¾¾ Handling metadata and cue point information in a video file
¾¾ Capturing and displaying video input from a user’s camera

Click here to know more about basics of video.


■■ Understanding the Flash Video (FLV) format

The FLV file format contains encoded audio and video data for delivery when the Flash Player is used. FLV files are
created by importing video into the flash authoring tool and then exporting it as an FLV file. Also, by using the FLV
Export plug-in, FLV files can be exported from supported video-editing applications.

External FLV files provide some capabilities that are not available while using imported video, such as the following:
¾¾ Without slowing down playback, longer video clips can be used in Flash documents. By using cached memory
external FLV files play, in other words large files are stored in small pieces and accessed with less memory than
embedded video files.
¾¾ The Flash document has different frame rate than an external FLV file in which it plays. For example, the Flash
document frame rate can be set to 40 frames per second (fps) and the video frame rate to 31 fps. This setting
gives a better control of the video and ensures smooth video playback by allowing playing FLV files at different
frame rates without the need to alter existing Flash content.
¾¾ While the video is loading, the Flash document playback does not have to be interrupted with the external FLV
files as it can also be performed independently on the Flash document.
¾¾ With external FLV files, captioning video content is easier as the video’s metadata can be accessed using event
handlers.

The file extension has to be registered as well as Multipurpose Internet Mail Extensions (MIME) type with the
Web server. Even the Web server documentation has to be checked while loading FLV files from a Web server.
The MIME type for FLV files is video/x-flv.

10.2.2 Understanding the Video Class


Live streaming video in an application is displayed by the Video class without embedding it in SWF file. The
Camera.getCamera() method captures and plays live video. The Video class can also be used to playback FLV files
over HTTP or from the local file system. The following are the ways to use video in projects:
¾¾ Load an FLV dynamically using the NetConnection and NetStream classes and display the video in a
Video object
¾¾ Capture input from the user’s camera
¾¾ Use the FLVPlayback component

The instances of the Video class are instances of a Video object.

The Video class in the flash.media package inherits from the flash.display.DisplayObject class. Hence, all
the display objects, functionality filters, and matrix transformation can be applied to the video instances.

10.2.3 Loading Video Files


Loading video files using the NetConnection and NetStream classes is a multistep process:
■■ Creating a NetConnection object

This is the first step that allows playing of streaming FLV files from an HTTP address or a local drive by passing the
value null to the connect() method if not using a server such as Adobe’s Flash Media Server 2 or Adobe Flex.
var nc:NetConnection = new NetConnection();

nc.connect(null);

■■ Creating a NetStream object

This is the second step that takes a NetConnection object as a parameter and specifies which FLV file has to be
loaded and then connects a NetStream object to the specified NetConnection instance and loads an FLV named
video.flv in the same directory as the SWF file.
var ns:NetStream = new NetStream(nc); ns.addEventListener(AsyncErrorEvent.ASYNC_ERROR,
asyncErrorHandler);

ns.play(“video.flv”);

function asyncErrorHandler(event:AsyncErrorEvent):void

// ignore error }

■■ Creating a new Video object and attaching the previously created NetStream object using
the Video class attachNetStream() method

This is the third step. As given in the following example, the video object can be added to the display list using the
addChild() method. Refer to the following example:
var vid:Video = new Video();

vid.attachNetStream(ns);

addChild(vid);

Flash Player will attempt to load the video.flv video file in the same directory as the SWF file, after entering the previous
code or by specifying the path in the volume internal/external.

10.2.4 Writing Callback Methods for onCuePoint and onMetaData


Invisible markers in a video file, which can be used to trigger external events, are called as cue points. Synchronizing
graphics and sub-titles, providing navigation options, and loading other video files or SWF movies are considered as
cue points.

When specific cue points are reached or specific metadata is received by the player, then actions can be triggered in the
application. Thus, the onCuePoint and onMetaData event handlers can be used to trigger such actions. Callback
methods for these handlers must be written or else the Flash Player may throw errors. In the following example, the code
plays an FLV file named video.flv in the same folder as in the SWF document:
var nc:NetConnection = new NetConnection();

nc.connect(null);

var ns:NetStream = new NetStream(nc);

ns.addEventListener(AsyncErrorEvent.ASYNC_ERROR, asyncErrorHandler);

ns.play(“video.flv”);

function asyncErrorHandler(event:AsyncErrorEvent):void{trace(event.text); }

var vid:Video = new Video();

vid.attachNetStream(ns);

addChild(vid);

A local FLV file named video.flv is loaded by the previous code and also listens for the asyncError (AsyncErrorEvent.
ASYNC_ERROR) to be dispatched. When an exception is thrown from native asynchronous code, then this event is
dispatched. Here, it is dispatched when an FLV contains metadata or cue point information, and the appropriate listeners
have not been defined. In case the video file’s metadata cue point information is not required, then the previous code
handles the asyncError event and ignores the error.

If asyncErrorHandler is ignored while loading an external video.flv it will show the error in metadata and
cue point.

If the FLV had metadata and several cue points, then the following information would be traced:
¾¾ Error #2095: flash.net.NetStream was unable to invoke callback onMetaData.
¾¾ Error #2095: flash.net.NetStream was unable to invoke callback onCuePoint.
¾¾ Error #2095: flash.net.NetStream was unable to invoke callback onCuePoint.
¾¾ Error #2095: flash.net.NetStream was unable to invoke callback onCuePoint.

Click here to know more about the Callback methods for onCuePoint and onMetaData.

10.3 Working with Sound


Computers can capture and encode digital audio, which can be stored and retrieved to playback over speakers. Playback
sound can also be played by using Adobe Flash Player and ActionScript.

Sound effect can be added to an audio feedback of an application user interface, a video game, and also for making a
program that analyzes MP3 files loaded over the Internet, with sound at the core of the application.

The sound-related tasks that can be performed are as follows:


¾¾ Loading and tracking external MP3 files
¾¾ Playing, pausing, resuming, and stopping sounds
¾¾ Playing streaming sounds while they are being loaded
¾¾ Manipulating sound volume and panning
¾¾ Retrieving ID3 metadata from an MP3 file
¾¾ Using raw sound wave data
¾¾ Capturing and replaying sound input from a user’s microphone

Click here to know more about working with sound.

10.3.1 Loading External Sound Files


To load more than one sound file, a new sound object needs to be created. To enable automatic loading of new sound
files, use the following code:
var req:URLRequest = new URLRequest(“click.mp3”);

var s:Sound = new Sound(req);

URLRequest object is accepted by the Sound() constructor as its first parameter and a new Sound object starts
loading the specified sound resource automatically, when a value for the first parameter is supplied.

While loading external sound files, different events during the sound loading process dispatch different objects.

The application tracks the loading progress and ensures that the sound is loaded completely before playing. Refer to
Table 10.1.

Event Description
open (Event.OPEN) It is dispatched before the sound loading operation begins.
progress (ProgressEvent.PROGRESS) It is dispatched when data is received from the file or stream,
periodically during the sound loading process.
id3 (Event.ID3) It is dispatched when ID3 data is available for an MP3 sound.
complete (Event.COMPLETE) It is dispatched when all of the sound resource’s data has been
loaded.
ioError (IOErrorEvent.IO_ERROR) It is dispatched when a sound file cannot be located or when the
loading process is interrupted before all sound data can be received.
Table 10.1: Different Events dispatched by sound objects

The following code displays how to play a sound after it has finished loading:
import flash.events.Event;

import flash.media.Sound;

import flash.net.URLRequest;

var s:Sound = new Sound();

s.addEventListener(Event.COMPLETE, onSoundLoaded);

var req:URLRequest = new URLRequest(“bigSound.mp3”);

s.load(req);

function onSoundLoaded(event:Event):void

var localSound:Sound = event.target as Sound;

localSound.play();

}
First, a new sound object is created by the code without giving it an initial value for the URLRequest parameter. Then,
it listens for the Event.COMPLETE event from the sound object that is responsible for causing the onSoundLoaded()
method to execute on loading all the sound data.

Lastly, the Sound.load() method calls with a new URLRequest value for the sound file. When the sound loading is
complete, the onSoundLoaded() method executes. The event object is a reference to the sound object and on calling
the play() method, the sound starts the sound playback.

10.3.2 Controlling Sound Volume and Panning


Both the left and the right stereo channels for a sound are controlled by an individual SoundChannel object. The
amplitude of each stereo channel of the sound can be found by using the leftPeak and rightPeak properties of the
SoundChannel object. The actual playback volume are not represented by these properties, however these properties
show the peak amplitude of the sound waveform itself.

The volume values set in the SoundChannel object of the SoundMixer class, and the function of the amplitude of the
sound wave is the actual playback volume. To specify a different volume level for each of the left and right channels during
playback, the pan property of a SoundChannel object can be used whose value ranges from -1 to 1. -1 represents the
left channel that plays at top volume and the right channel remains silent. 1 represents the right channel that plays at top
volume while the left channel remains silent. The value 0 represents both channels that play at a balanced volume level.

A SoundTransform object with a volume value of 0.6 and a pan value of -1 (top left channel volume and no right
channel volume) is created in the following example:
var snd:Sound = new Sound(new URLRequest(“mySound.mp3”));

var trans:SoundTransform = new SoundTransform(0.6, -1)

var channel:SoundChannel = snd.play(0, 1, trans);

The volume and panning can be altered while a sound is playing by setting the pan or volume properties of a
SoundTransform object and then, applying that object as the SoundTransform property of a SoundChannel object.

The global volume and pan values for all sounds can also be set by using the SoundTransform property of the
SoundMixer class, as shown in the following example:
SoundMixer.soundTransform = new SoundTransform(1, -1);

In the following example, the panning of the sound is alternate from left channel to the right channel and back while the
sound plays:
import flash.events.Event;

import flash.media.Sound;

import flash.media.SoundChannel;

import flash.media.SoundMixer;

import flash.net.URLRequest;

var snd:Sound = new Sound();

var req:URLRequest = new URLRequest(“mySound.mp3”);

snd.load(req);

var panCounter:Number = 0;

var trans:SoundTransform;

trans = new SoundTransform(1, 0);

var channel:SoundChannel = snd.play(0, 1, trans); channel.addEventListener(Event.SOUND_


COMPLETE, onPlaybackComplete);

addEventListener(Event.ENTER_FRAME, onEnterFrame)

function onEnterFrame(event:Event):void

trans.pan = Math.sin(panCounter);

channel.soundTransform = trans; // or SoundMixer.soundTransform = trans;

panCounter += 0.05;

function onPlaybackComplete(event:Event):void

removeEventListener(Event.ENTER_FRAME, onEnterFrame);

By loading a sound file and later creating a new SoundTransform object with volume set to 1 (full volume) and pan
set to 0 (evenly balanced between left and right) the code can be started. Then, the snd.play()method is called by
passing the SoundTransform object as a parameter.

The onEnterFrame()method is repeatedly executed while the sound plays. The Math.sin() function is used to
generate a value between -1 and 1. This range corresponds to the acceptable values of SoundTransform.pan property.
A new value is set to the SoundTransform object’s pan property and then set to use the altered SoundTransform
object. The filename mySound.mp3 is replaced with the name of a local MP3 file to run the example. Thus, it enables to
hear the left channel volume that gets louder and at the same time the right channel volume gets softer, and vice versa.

The same effect can be achieved by setting the SoundTransform property of the SoundMixer class, but this can
affect the panning of all sounds that is currently playing.

10.3.3 Accessing Raw Sound Data


The SoundMixer.computeSpectrum() method allows an application to read the raw sound data for the waveform
that is currently being played. The SoundMixer.computeSpectrum() method shows the combined sound data of
every SoundChannel object mixed together, if more than one SoundChannel object is currently playing.

A ByteArray object is returned by the sound data that contains 512 bytes of data and each byte contains a floating
point value between -1 and 1 that represent the amplitude of the points in the sound waveform being played. The values
are divided in two groups, each of 256 bytes. The first group is delivered for the left stereo channel and the second group
for the right stereo channel.

Fast Fourier Transform (FFT) is used to convert the waveform data into frequency spectrum data. The resulting frequency
spectrum values range from 0 to roughly 1.414 (the square root of 2).

If the FFTMode parameter is set to true, then the SoundMixer.computeSpectrum() method returns frequency
spectrum data and shows amplitude that is arranged by sound frequency from the lowest to highest frequency.

The following figure compares the data returned from the computeSpectrum() method irrespective of setting it to true
or false. A loud bass sound in the left channel and a drum hit sound in the right channel are used. Refer to Figure 10.3.

Figure 10.3: Graphical display of values returned by computeSpectrum() function

Data that has been resampled at a lower bit rate can be returned by the computeSpectrum() method resulting in
smoother waveform data or frequency data at the expense of detail. The rate at which the computeSpectrum()
method data is sampled is controlled by the stretchFactor parameter. This rate is halved if the stretchFactor
parameter is set to 0. If the sound data is sampled at a rate of 44.1 kHz, then it gets halved to 22.05 kHz and a value of 2
specifies a rate of 11.025 kHz. When a higher stretchFactor value is used, then the computeSpectrum() method
still returns 256 bytes per stereo channel.

There are a few limitations of the SoundMixer.computeSpectrum() method which are as follows:

¾¾ The SoundMixer.computeSpectrum() method will not return data from those sources, because the sound
data from a microphone or from Real Time Messaging Protocol (RTMP) streams do not pass through the global
SoundMixer object.

¾¾ Security restrictions will cause the SoundMixer.computeSpectrum() method to throw an error, if one or
more of the sounds being played come from sources outside the current content sandbox.

For detailed step-by-step procedure, refer to demo Working with Text Dynamic from:

eResources 4 Me>> My Varsity>> Module Name>> Show Me How Web Animation and Interactivity>> Show Me How>>
Working with Sound>> Accessing raw sound data

10.4 Summary
In this session, Working with Built-in Classes (Text, Video, and Sound), you learned that:
¾¾ The three types of text are: Dynamic text, Input text, and Static text.
¾¾ In AS 3.0, there are different built-in classes to perform text handling tasks.
¾¾ An instance of a built-in TextField class is used to display text on the screen in Adobe Flash Player. The
properties defining the appearance of the text, such as size, color, and weight are present in the TextFormat
object or StyleSheet object.

¾¾ By assigning a string to the flash.text.TextField.text property, dynamic text can be defined.


¾¾ Any local or remote image can be accessed by using the img tag and allowing it to appear within the associated
TextField.

¾¾ Scroll-related properties of the flash.text.TextField class can be used to manage vertically (V) or
horizontally (H) lengthy content.

¾¾ When a user selects a text from a complete string or a paragraph, the selectionBeginIndex and
selectionEndIndex is captured programmatically.

¾¾ The flash.text.StyleSheet class handles CSS styles and the StyleSheet class recognizes a limited set
of CSS properties. It also has a restrict property and a displayAsPassword property that help users to
control text input.

¾¾ To interact with a static text instance placed on the Stage, use the flash.text.StaticText class in the
Actions panel of the Flash authoring tool.

¾¾ The flash.text.TextField class helps to identify the text string for formatting the content.
¾¾ The user input can be collected and the value can be saved for use in other parts of an application, if the type
property to input is set using the TextFieldType class.

¾¾ The flash.text.TextField class has a restrict property.


¾¾ The display of a text can be formatted programmatically by using any one of these properties such as
TextField.thickness, TextField.textColor, and TextField.textHeight. By using the htmlText
property and the supported HTML tags, such as b (for bold), i (for Italic), and u (for underline), the content of
the text can be formatted.
¾¾ Cascading Style Sheets are used to define text styles and apply to different text fields. Loading CSS information
from an external file at run time is more powerful.
¾¾ Advanced Text Rendering includes anti-aliasing settings, embedded fonts, alpha channel control, and other
specific settings.

¾¾ To read the values out of the static text, the flash.text.TextSnapshot class can be used.
¾¾ To interact with a static text instance placed on the Stage, use the flash.text.StaticText class.
¾¾ The TextSnapshot class is useful for getting the text out of static text fields in a loaded SWF.
¾¾ Working with video in ActionScript involves a combination of classes such as Video class, NetStream class,
and Camera class.
¾¾ By using Flash Player, the FLV file format contains encoded audio and video data for delivery.
¾¾ NetConnection and NetStream classes are used for loading.
¾¾ The onCuePoint and onMetaData event handlers to trigger actions.
¾¾ Sound effect can be added to an audio feedback of an application user interface, a video game, and also to
make a program that analyzes MP3 files loaded over the Internet.

¾¾ Both the left and the right stereo channels for a sound are controlled by an individual SoundChannel object.
¾¾ The SoundMixer.computeSpectrum() method allows an application to read the raw sound data for the
waveform that is currently being played.
10.5 Exercise
1. Which of these text loads content from the external source?

Input text

Dynamic text

Static text

Output text

2. Which are the ways to use video in projects?

Copying the example code listing into the Script pane

Selecting the first keyframe in the Timeline, and open the Actions panel

SoundMixer

Capture input from the user’s camera

3. The SoundMixer.computeSpectrum() method allows an application to read the raw sound data for the waveform
that is currently being played.

True

False

4. Both the left and the right stereo channels for a sound are controlled by an individual ______ object.

computeSpectrum

SoundTransform

SoundChannel

SoundMixer

5. The TextSnapshot class is useful for getting the text out of dynamic text fields in a loaded MP3.

True

False
Session 11
Object-Oriented Programming with ActionScript 3.0
Learning Outcomes
In this session, you will learn to:
¾¾ Understand the Object-Oriented Programming concept
¾¾ Know more about classes and identify them
¾¾ Understand how to define interfaces and implement them in a class
¾¾ Learn about Inheritance and identify them

11.1 Basics of Object-Oriented Programming


ActionScript was initiated as an object-oriented language for Macromedia’s Flash authoring tool, which is now developed
by Adobe Systems as Adobe Flash. The initial three versions of the Flash authoring tool, however, provided inadequate
interactivity features.

In 1999, Flash 4 was released that introduced variables, expressions, loops, if statements, and operators. Internally, this
came to be known as ‘ActionScript’ that uses the term ‘actions’ to describe a set of commands.

ActionScript 2.0 was introduced by Flash MX 2004 as a scripting programming language, which was appropriate for the
development of Flash applications. Scripting often saves time than animating and also enables a higher level of flexibility
when editing.

ActionScript 3.0 is a superset of the syntax and semantics of language, which is more widely known as JavaScript.
ActionScript 3.0 is primarily used for the development of Web sites and software targeting the Adobe Flash Player
platform, which is in turn used on Web pages in the form of embedded SWF files.

In addition, ActionScript 3.0 is suitable for use in some database applications and in basic robotics. Moreover, the
Object-Oriented Programming (OOP) support is optional in ActionScript 3.0, and it provides flexibility to programmers to
choose the best approach for complex projects of varying scope.

11.1.1 Important Concepts and Terms


OOP helps in organizing the code in a program by grouping different objects into one individual element based on
functionality and data values.

For example, different music information, such as artist name, track title, or album title along with actions related to that
information, such as ‘play all songs by this artist’ or ‘add track to playlist’ can be grouped into one element. All these items
together form a single item or object, for example, a ‘Music Track’ or an ‘Album’. This combination proves beneficial as
it helps keep a track of a single variable instead of multiple variables that organize these functionalities together and
also structure programs that are more real. Some of the important terms used while working with OOP are as follows:
¾¾ Class: The behavior of objects of a certain type and the definition of the structure is referred to as a class. For
example, a template or a blueprint for objects of that data type.
¾¾ Class hierarchy: This is the structure that specifies the class that inherits functionality from other classes.
¾¾ Attribute: A class element to which a characteristic is assigned in a class definition is called as attribute. These
are used to define the method or property available for code in a program. Private and public are examples
of attributes. The code that is called within the class is called as a private method, and the code that is called
from another class is called as a public method.
¾¾ Constructor method: The constructor method is called when a new instance of an object is created. The
constructor method is like a normal public method except that it shares the same name as the class and it
cannot return a value. It can have none, one, or many parameters.
¾¾ Data type: It is a particular variable that can be stored and has the same properties as a class.
¾¾ Dot operator: This refers to the period sign (.). In ActionScript, this sign refers to a child element of an object
similar to a method or property. For example, in the expression myObject.myProperty, the dot refers to
some value that is an element of the object named myObject.
¾¾ Enumeration: This refers to a set of related constant values that are grouped together as a single class.
¾¾ Inheritance: It implements parent-child relationship, where the child class can inherit the attributes and behavior
of the parent class (Base class).
¾¾ Namespace: This is a custom attribute that allows total control over codes.
11.1.2 Identifying Common OOP Tasks
Following are the common OOP tasks:
¾¾ Defining classes
¾¾ Creating properties, methods, and get and set accessor methods
¾¾ Controlling access to classes, properties, methods, and accessory
¾¾ Creating static properties and methods
¾¾ Creating enumeration-like structures
¾¾ Defining and using interfaces
¾¾ Working with inheritance, including overriding class elements

11.2 Classes
An abstract representation of an object is called a class. It stores information about the types of data that an object can
hold and the behaviors that an object can exhibit. When small scripts are written containing a few objects that interact
with one another, its usefulness is not apparent. As the scope of any program grows, the objects and its number are to
be managed.

The nested function can be invoked anywhere within the containing method. However, access-control
modifiers, such as public and internal cannot be applied to nested functions.

11.2.1 Class Definitions


The syntax for a class definition includes the class keyword followed by the class name. The class name is followed
by the class body, which is enclosed by curly brackets ({}) as shown in the following example:
Public class Color // defining a class, named Color

var visible: Boolean = true; // body of the class

ActionScript 3.0 introduces the package statement that includes the package declaration.

// ActionScript 2.0

class flash.display.BitmapData {}

// ActionScript 3.0

package flash.display

public class BitmapData {}

}
In this example, the code creates a class named color that contains only one variable, named ‘visible’.
■■ Class attributes

Class definitions can be modified in ActionScript 3.0 by using any one of the following attributes:
¾¾ dynamic: Here, properties are allowed to be added to instances at run time.
¾¾ final: This cannot be extended by another class.
¾¾ internal: Here, references inside the current package are visible and is the default setting.
¾¾ public: Here, references everywhere are visible.
Except internal, each of these attributes must clearly include the attribute to get the associated behavior. For example,
adding properties to a class instance at run time will not be possible if the dynamic attribute is not included. An attribute
has to be assigned explicitly at the beginning of the class definition, as shown in the following code:
Dynamic class Shape { }

Click here to know more about the class attributes.


■■ Class body

The class body enclosed by curly brackets is used to define the variables, constants, and methods of a class. Refer
to the following example:
Public final class Accessibility

Public static function gets active (): Boolean;

Public static function update Properties (): void;

Here, the example shows the declaration for the Accessibility class in the Adobe Flash
Player API.

A namespace inside a class body can also be defined. Notice the following example
carefully:

Public class Sample Class

Public namespace sample Namespace;

Sample Namespace function does something (): void

This example demonstrates how a namespace can be defined within a class body and used as an attribute of a
method in that class.
In ActionScript 3.0, statements can also be allowed along with definitions in a class body when the class definition
is first encountered and the associated class object is created. The following example includes a call to an external
function, hello(), and a trace statement that outputs a confirmation message when the class is defined. Thus,
the statements that are inside a class body, but outside a method definition, are executed exactly once. Refer to the
following example:
Function hello (): String

Trace (“hola”);

Class Sample Class

Hello ();

Trace (“class created”);

// output when class is created


Hola

Class created

ActionScript 3.0 allows defining a static property and an instance property with the same name in the same class
body. Refer to the following example:
Class Static Test

Static var message: String = “static variable”

var message: String = “instance variable”;

// in your script

var myST:StaticTest = new StaticTest();

trace(StaticTest.message); // output: static variable

trace(myST.message); // output: instance variable

Here, the code declares a static variable named message and an instance variable of the same name.

11.2.2 Class Property Attributes


Anything that can be a member of a class is termed as property, and it also includes variables. There are four special
attributes provided in ActionScript 3.0 that control access to properties defined inside a class:
■■ public attribute
A public attribute can be visible anywhere in the script. For example, the method with the public attribute has
to be declared to make a method available to code outside its package. This is true for any property, whether it is
declared using var, const, or function keywords.
■■ private attribute
The private attribute can be visible only to callers within the property’s defining class. Properties that are marked
as private are unavailable during both compile and run time. Refer to the following example:
class PrivateExample

private var privVar:String = “private variable”;

var myExample:PrivateExample = new PrivateExample();

trace(myExample.privVar); // compile-time error in strict mode

trace(myExample[“privVar”]); // ActionScript 2.0 allows access, but in

ActionScript 3.0, this is a run-time error.

In the example, the code creates a simple class named PrivateExample with one private variable, and then
attempts to access the private variable from outside the class.

An attempt to access a private property using the dot operator (myExample.privVar) in ActionScript 3.0, results
in a compile-time error if strict mode is used. When the property access operator (myExample[“privVar”]) is
used, the error is reported at run time.

Refer to Table 11.1 that shows the result of attempting to access a private property belonging to a sealed (not
dynamic) class.

Strict Mode Standard Mode


dot operator (.) compile-time error run-time error
bracket operator ([]) run-time error run-time error
Table 11.1: Run-time errors

However, attempting to access a private variable will not result in a run-time error when classes are declared with
the dynamic attribute. The variable is not visible, hence Flash Player returns the value undefined. If the dot operator
is used in strict mode, then a compile-time error occurs.

Refer to the following example of a dynamic class PrivateExample:


{

private var privVar:String = “private variable”

var myExample:PrivateExample = new PrivateExample();

trace(myExample.privVar); // compile-time error in strict mode

trace(myExample[“privVar”]); // output: undefined

The example is the same as the earlier example, except that the PrivateExample class is declared as a dynamic
class. Instead of generating an error when a code, external to a class, attempts to access a private property, the
dynamic classes return the value undefined. Refer to Table 11.2 that shows an error which is generated only when
the dot operator is used to access a private property in strict mode.

Strict Mode Standard Mode


dot operator (.) compile-time error undefined
bracket operator ([]) undefined undefined
Table 11.2: Undefined errors
■■ protected attribute
In ActionScript 3.0, the protected attribute makes a property visible to callers within its own class or within its sub-
class. This also means that a protected property is available within its own class or to classes that lie anywhere
in the following inheritance hierarchy. This holds true for all sub-classes within the same package or in a different
package.
■■ internal attribute
In ActionScript 3.0, the internal attribute makes a property visible to callers within its own package. This is the
default attribute for code inside a package, and it applies to any property that does not have any of the following
attributes:
¾¾ public
¾¾ private
¾¾ protected
¾¾ A user-defined namespace
The internal attribute is accessible in ActionScript 3.0 that clearly signifies the intent to make a property visible
only to callers within its own package.
■■ static attribute
The static attribute can be used with properties declared with var, const, or function keywords. This allows
attaching of a property to the class rather than to instances of the class. Code external to the class must call static
properties by using the class name instead of an instance name.

Static properties are not inherited by sub-classes, but the properties are part of a sub-class’s scope chain. In other
words, this means that within the body of a sub-class, a static variable or method can be used without referring to
the class in which it was defined.
■■ User-defined namespace attributes

A custom namespace can be created for use as an attribute or as an alternative to the predefined access control
attributes. Only one namespace per definition can be used, and it cannot be used in combination with any of the
access control attributes, such as public, private, protected, and internal.

11.2.3 Variables
Variables can be declared with var or const keyboards. The variables that are declared with the var keyboard can
change their values a number of times while the script is executed. The variables that are declared with the const
keyword are called constants. Values can be assigned to them only once and it results in an error if a new value is
assigned to an initialized constant. There are two types of variables as follows:
■■ Static variables

By using a combination of the static keyword and var or const keywords, static variables can be declared. They
are useful for storing and sharing information that applies to an entire class of objects.

For example, to keep a tally of the number of times a class instance is allowed, a static variable is appropriate as
it can store a maximum number of class instances. A totalCount variable can be created to track the number of
class instantiations and a MAX_NUM constant to store the maximum number of instantiations. The totalCount and
MAX_NUM variables contain values that apply to the class as a whole and not to a particular instance. Refer to the
following example:
class StaticVars

public static var totalCount:int = 0;

public static const MAX_NUM:uint = 16;

}
The totalCount and MAX_NUM properties can be referred to the code that is external to the StaticVars class
and any of its sub-classes as given in the following code:
trace(StaticVars.totalCount); // output: 0

trace(StaticVars.MAX_NUM); // output: 16

In this example, the totalCount and MAX_NUM variables are static. Thus, static variables cannot be accessed
through an instance of the class as the code returns errors. Refer to the following example:
var myStaticVars:StaticVars = new StaticVars();

trace(myStaticVars.totalCount); // error

trace(myStaticVars.MAX_NUM); // error

The static and const keywords that are declared by the variables must be initialized while declaring the constant,
similar to how the StaticVars class does for MAX_NUM. A value cannot be assigned to MAX_NUM inside the
constructor or an instance method, thereby generating an error since it is not a valid way to initialize a static
constant. Refer to the following example:
// !! Error to initialize static constant this way

class StaticVars2

public static const UNIQUESORT:uint;

function initializeStatic():void

UNIQUESORT = 16;

} }

■■ Instance variables

Properties declared with the var and const keywords do not contain the static keyword and are included in
instance variables. Instance variables that are attached to class instances are used to store values specific to an
instance. For example, an Array class with an instance property named length helps to store the number of array
elements of a specific instance of the Array class. The var and const keywords cannot be overridden in a sub-
class.

11.2.4 Methods
Functions that are part of a class definition are called methods. A method is bound to an instance. Once it is created, it
cannot be used for instances other than the one for which it is attached.

By using the function keyword, methods can be defined and function statement can be used as follows:
public function sampleFunction():String {}

A variable can also be used to assign a function expression as shown in the following code:
public var sampleFunction:Function = function () {}

However, in most cases a function statement is used more often instead of a function expression for the following
reasons:
¾¾ Function statements are shorter, to the point, and readable.
¾¾ The override and final keywords are allowed by function statements.
¾¾ A strong bond is created by function statements between the identifier that include the function name and the
code within the method body. The connection between a variable and its function expression can be severed at
any time as the value of a variable can be changed with an assignment statement.
¾¾ Function expression is used to attach a function to the prototype object.
The different types of methods are:
¾¾ Constructor methods
¾¾ Static methods
¾¾ Instance methods
¾¾ get and set Accessor methods
¾¾ Bound methods
Click here to know more about different types of methods in detail.

11.2.5 Enumerations with Classes


To sum up a small set of values, custom data types are created called as enumerations. A specific enumeration facility is
not supported by ActionScript 3.0, but enumerations using classes and static constants can be created. In the following
example, the PrintJob class in the Flash Player API uses an enumeration that is named PrintJobOrientation:
public final class PrintJobOrientatio

public static const LANDSCAPE:String = “landscape”

public static const PORTRAIT:String = “portrait”;

An enumeration class is declared with the final attribute as the need to extend the class is not required. There exist only
static members in the class. As shown in the following code, the enumeration values can be accessed directly through
the class object:
var pj:PrintJob = new PrintJob();

if(pj.start())

if (pj.orientation == PrintJobOrientation.PORTRAIT)

}}

This example is used to store the set of values comprising landscape and portrait. Only variables of type String,
int, or uint are in the enumeration classes in the Flash Player API.
■■ Advantages of using enumerations instead of literal string or number values

Following are the advantages:


¾¾ The typographical mistakes are easier to find with enumerations.
¾¾ The ActionScript compiler generates an error, if the name of an enumeration is mistyped.
¾¾ The compiler does not complain if a word is spelled incorrectly or wrong number is mentioned if literal values
are used. The following excerpt shows the example:
if (pj.orientation == PrintJobOrientation.PORTRAI) // compiler error

If a string literal value is spelt wrongly, then the compiler does not generate an error as follows:
if (pj.orientation == “portrai”) // no compiler error

Another technique for creating enumerations is by creating a separate class with static properties for the enumeration.
The static properties contain an instance of the class instead of a string or integer value.

In the following example, the code creates an enumeration class for the days of the week:
public final class Day

public static const MONDAY:Day = new Day();

public static const TUESDAY:Day = new Day();

public static const WEDNESDAY:Day = new Day();

public static const THURSDAY:Day = new Day();

public static const FRIDAY:Day = new Day();

public static const SATURDAY:Day = new Day();

public static const SUNDAY:Day = new Day();

Many developers use the improved type-checking that the technique provides. In the following example, the code
demonstrates a function that returns a day of the week:
function getDay():Day

var date:Date = new Date();

var retDay:Day;

switch (date.day)

case 0:

retDay = Day.MONDAY;

break;

case 1:

retDay = Day.TUESDAY;

break;

case 2:

retDay = Day.WEDNESDAY;

break;

case 3:

retDay = Day.THURSDAY;

break;

case 4:

retDay = Day.FRIDAY;

break;

case 5:

retDay = Day.SATURDAY;

break;

case 6:

retDay = Day.SUNDAY;

break;

return retDay;

var dayOfWeek:Day = getDay();

In this example, the code uses the enumeration type as a type annotation. An integer can be associated with
each day of the week, by enhancing the Day class. A string representation of the day can be returned by providing
a toString() method.

11.2.6 Embedded Asset Classes


Embedded asset classes are special classes used in ActionScript 3.0 that represents assets. For example, image, font,
or sound being included in an SWF file at the time of compiling.

An asset can be embedded by following mentioned steps:


¾¾ Placing the asset into a FLA file’s library.
¾¾ Using the asset’s linkage property to provide a name for the asset’s embedded asset class. A class is automatically
generated, if a class by that name cannot be found in the classpath.
¾¾ Creating an instance of the embedded asset class and using any properties and methods defined or inherited
from that class. For example, the following code can be used to play an embedded sound that is linked to an
embedded asset class named PianoMusic:
var piano:PianoMusic = new PianoMusic();

var sndChannel:SoundChannel = piano.play();

Quick Test 11.1


1. _____________ is a custom attribute that allows total control over codes.
Data type Dot operator Enumeration namespace

2. Internal attribute is the default attribute for code in a package, and it applies to any property.
True False

11.3 Interfaces
A collection of method declarations that allows unrelated objects to communicate with one another is called an interface.
In the following example, the Flash Player API defines the IEventDispatcher interface containing method declarations
that a class can use to handle event objects. A standard way is established by the IEventDispatcher interface for
objects to pass event objects to one another. Refer to the following example:
public interface IEventDispatcher

function addEventListener(type:String, listener:Function,

useCapture:Boolean=false, priority:int=0,

useWeakReference:Boolean = false):void;

function removeEventListener(type:String, listener:Function,

useCapture:Boolean=false):void;

function dispatchEvent(event:Event):Boolean;

function hasEventListener(type:String):Boolean;

function willTrigger(type:String):Boolean; }

The definition of the IEventDispatcher interface is demonstrated in the code. In Flash Player API, the
EventDispatcher class implements the IEventDispatcher interface by defining all of the IEventDispatcher
interface methods and adding method bodies to each of the methods. The following code is an excerpt from the
EventDispatcher class definition:
public class EventDispatcher implements IEventDispatcher

function dispatchEvent(event:Event):Boolean

/* implementation statements */

... }

The IEventDispatcher interface serves as a protocol that EventDispatcher instances use to process event
objects and pass them to other objects that have implemented the IEventDispatcher interface.
11.3.1 Defining an Interface
An interface can contain only methods with no method bodies. By using the interface keyword, an interface can be
defined.

In the following example, the interface IExternalizable is part of the flash.utils package in the Flash Player API
that defines a protocol to serialize an object. In simple terms, it means to convert an object into a format that is suitable
for storage on a device or for transport across a network. Refer to the following example:
public interface IExternalizable

function writeExternal(output:IDataOutput):void;

function readExternal(input:IDataInput):void;

The public access control modifier is declared by the IExternalizable interface. Internal access control specifiers and
public access control specifiers modify the interface definitions. The method declarations inside an interface definition
cannot have any access control specifiers. The interface definitions need to be placed at the top level of a package but
not inside a class definition or inside another interface definition. They can also extend one or more interfaces.

In the following example, the interface IExample extends the IExternalizable interface:
public interface IExample extends IExternalizable

function extra():void;

Implementations must be included in any class that implements the IExample interface not just for the extra() method,
but also for the writeExternal() and readExternal() methods that are inherited from the IExternalizable
interface.

11.3.2 Implementing an Interface in a Class


ActionScript 3.0 language element is the only class that can implement an interface. To implement one or more interfaces,
use the implements keyword in a class declaration.

In the following example, IAlpha and IBeta, are the two interfaces that are defined along with a class alpha that
implements both:
interface IAlpha

function foo(str:String):String;}

interface IBeta

function bar():void;

class Alpha implements IAlpha, IBeta

public function foo(param:String):String {}

public function bar():void {} }

Guidelines for implemented methods in a class that executes an interface include:


¾¾ The public access control identifier must be used.
¾¾ The same name as the interface method must be used.
¾¾ The same number of parameters must be used with data types that match the interface method parameter data
types.
¾¾ The same return type must be used.
There is some flexibility in the way the parameters of methods implemented are named. The data type of each parameter
and the number of parameters in the implemented method should match but the parameter names need not match. As
mentioned in the earlier example, the parameter of the Alpha.foo() method is named param:

public function foo(param:String):String {}

The parameter is named str in the IAlpha.foo() interface method:


function foo(str:String):String;

The default parameter values have some flexibility. Function declarations with default parameter values can be
included in an interface definition.

In the following example, the code defines an interface containing a method with a default parameter value of 3:
interface IGamma

function doSomething(param:int = 3):void;

The Igamma interface is implemented by the following class definition using a different default parameter value:
class Gamma implements IGamma

public function doSomething(param:int = 4):void {}

}
The rules for implementing an interface are designed in a way ensuring data type compatibility. Identical parameter
names and default parameter values are not required to achieve that objective.

11.4 Inheritance
A code that allows programmers to develop new classes that are based on existing classes is called as inheritance.
■■ Advantages of inheritance
¾¾ The code can be reused from a Base class yet it leaves the existing code unmodified.
¾¾ No change is required in the way the classes interact with the Base class.
¾¾ The existing class is thoroughly tested and by using inheritance, the additional properties or methods can be
extended.
¾¾ By using the extend keyword, a class inheriting from another class can be indicated.
¾¾ Inheritance allows taking advantage of polymorphism in the code.
¾¾ Inheritance enables polymorphism by allowing sub-classes to inherit and redefine or override methods from the
Base class.
■■ Polymorphism

The ability to use a single method name for a method that behaves differently when applied to different data types
is termed as polymorphism.

For example, a Base class named Shape with two sub-classes named Circle and Square. The Shape class
defines a method named area(). This returns the area of the shape. The area() method can be called on objects
of type Circle and Square and delivers correct calculations if polymorphism is implemented. The following
example shows how the area() method is redefined by the Circle and Square classes:
class Shape

public function area():Number

return NaN;

}}

class Circle extends Shape

private var radius:Number = 1;

override public function area():Number

return (Math.PI * (radius * radius));

class Square extends Shape

private var side:Number = 1;

override public function area():Number

return (side * side);

} }

var cir:Circle = new Circle();

trace(cir.area()); // output: 3.141592653589793

var sq:Square = new Square();

trace(sq.area()); // output:1

Since a data type is defined by each class, a special relationship is created between a Base class and a class that
extends it. All the properties of Base class are present in a sub-class. In simple terms, an instance of a sub-class
can always be substituted for an instance of the Base class as shown in the following example:
function draw(shapeToDraw:Shape) {}

var myCircle:Circle = new Circle();

draw(myCircle);

In this example, it is legal to pass an argument of type Circle because Circle extends Shape if a method defines
a parameter of type Shape.

11.4.1 Instance Properties and Inheritance


An instance property is inherited by all sub-classes as long as the property is not declared with the private attribute
in the Base class. For example, there are a number of sub-classes that inherit properties common to all event objects
in the Flash Player API. The Event class contains all the properties necessary to define the event and do not require
instance properties beyond those defined in the Event class.

In the following example, the Event class shows how some of the properties and methods are inherited by sub-classes
and how any sub-class can access these properties:
public class Event

public function get type():String;

public function get bubbles():Boolean;

public function stopPropagation():void {}

public function stopImmediatePropagation():void {}

public function preventDefault():void {}

public function isDefaultPrevented():Boolean {}

Some unique properties are required by some types of events that are not available in the Event class. By using
sub-classes of the Event class, these events are defined enabling new properties to be added to the properties as
demonstrated in the following example:
public class MouseEvent extends Event

public static const CLICK:String = “click”

public static const MOUSE_MOVE:String = “mouseMove”;

public function get stageX():Number {}

public function get stageY():Number {}

Here, the MouseEvent class shows the definition of properties that exist on the sub-class but not on the Base class.
■■ Access control specifiers and inheritance

This property is visible in code anywhere, if a property is declared with the public keyword. This means that the
public keyword places no restrictions on property inheritance.

The property is visible only in the class that defines it, if declared with private keyword. This means that it is not
inherited by any sub-classes. Thus, the property is visible not only within the class that defines it, but also to all sub-
classes when indicated by the protected keyword. The internal keyword can be used or any access control
specifier need not be used in order to limit the visibility of a property to the package in which it is defined. A property
marked as internal will be inherited only by a sub-class that resides in the same package.

The following example shows how each of the access control specifiers affect inheritance across package boundaries:
// Base.as in a folder named foo

package foo

public class Base

public var str:String = “hello”; // change public on this line

// Extender.as in a folder named bar

package bar

import foo.Base;
public class Extender extends Base

public function getString():String {

return str;

// main application class in file named ProtectedExample.as

import flash.display.MovieClip;

import bar.Extender;

public class AccessControl extends MovieClip

public function AccessControl()

var myExt:Extender = new Extender();

trace(myExt.testString); // error if str is not public

trace(myExt.getString()); // error if str is private or internal

Here, the code defines a main application class named AccessControl and two other classes named Base
and Extender. The str variable’s access control specifier needs to be changed to private, protected, or
internal to see how the other access control specifiers affect during compilation and execution of the preceding
example. The following line from the AccessControl class can be deleted as follows:
trace(myExt.testString); // error if str is not public

■■ Overriding variables not permitted

Properties cannot be overridden that are declared with the var or const keywords, but they can be inherited. Only
methods can be overridden. A similar functionality can be created by get and set methods for the instance variable
and overriding the methods.

11.4.2 Overriding Methods


To redefine the behavior of an inherited method means to override a method. Static methods cannot be inherited or
overridden but an instance method is inherited by sub-classes and overridden only when the following criteria are met:
¾¾ The final keyword in the Base class is not declared in the instance method. The final keyword indicates
the programmer’s intent to prevent sub-classes from overriding the method when used with an instance
method.
¾¾ The private access control specifier in the Base class is not declared in the instance method. There is no need
to use the override keyword when defining an identically named method in the sub-class. Moreover, a method
marked private in the Base class will not be visible to the sub-class.

The method definition in the sub-class must use the override keyword and match the superclass version of the
method to override an instance method that meets the criteria as shown in the following ways:
¾¾ There should be a same level of access control as the Base class method in the override method.
¾¾ Those methods that are marked internal should have the same level of access control as methods without
access control specifier.
¾¾ The same number of parameters as the Base class method must be present in the override method.
¾¾ The same data annotations as the parameters in the Base class method must be present in the override method
parameters.

¾¾ The same return type as the Base class method must be present in the override method.
As long as the number of parameters and the data type of each parameter matches, it is not necessary that the names
of the parameters in the override method has to match the names of the parameters in the Base class.
■■ Super statement

While overriding a method, the behavior of the superclass method can be added instead of completely replacing
the behavior. This can be done using a mechanism that allows a method in a sub-class to call the superclass
version. This is provided by the super statement that contains a method named thanks() and a sub-class of the
Base class named Extender that overrides the thanks() method. The super statement is used by the Extender.
thanks() method to call Base.thanks(). Refer to the following example:
package

import flash.display.MovieClip;

public class SuperExample extends MovieClip

public function SuperExample()

var myExt:Extender = new Extender()

trace(myExt.thanks()); // output: Mahalo nui loa

class Base {

public function thanks():String

return “Mahalo”;

class Extender extends Base

override public function thanks():String \

return super.thanks() + “ nui loa”;

■■ Overriding Getters and Setters

Getters and setters can be overridden but not variables defined in a superclass. As shown in the following example,
the code overrides a getter named currentLabel defined in the MovieClip class in the Flash Player API:
package

import flash.display.MovieClip;

public class OverrideExample extends MovieClip

public function OverrideExample()

trace(currentLabel)

override public function get currentLabel():String

var str:String = “Override: “;

str += super.currentLabel;

return str;

The output of the trace()statement in the OverrideExample class constructor is Override: null, which
shows that the example was able to override the inherited currentLabel property.

11.4.3 Static Properties not Inherited


Sub-classes do not inherit static properties. In other words, static properties cannot be accessed through an instance of
a sub-class. It can only be accessed through the class object on which it is defined.

For example, the following code defines a Base class named Base and a sub-class that extends Base named Extender.
A static variable named test is defined in the Base class. The code as written in the following excerpt does not compile
in strict mode and generates a run-time error in the standard mode.

package

import flash.display.MovieClip;

public class StaticExample extends MovieClip

public function StaticExample()

var myExt:Extender = new Extender();

trace(myExt.test); // error

class Base {

public static var test:String = “static”;


}

class Extender extends Base { }

The only way to access the static variable test is through the class object, as demonstrated in the following
code:

Base.test;

An instance property can be defined by using the same name as a static property in the same class or in a sub-class.
As given in the example, the Base class could have an instance property named test. This is complied and executed
by the following code as the instance property is inherited by the Extender class. Also, if the definition test instance
variable is moved, but not copied to the Extender class, then the code would compile and execute. Refer to the
following example:

package

import flash.display.MovieClip;

public class StaticExample extends MovieClip

public function StaticExample()

var myExt:Extender = new Extender();

trace(myExt.test); // output: instance

class Base

public static var test:String = “static”;

public var test:String = “instance”;

class Extender extends Base { }

11.4.4 Static Properties and the Scope Chain


Static properties are within the scope chain of the class that defines them and any sub-class of that class, even if they
are not inherited. Static properties are directly reachable within the body of the class that defines the static property and
any sub-class of that class.

In the following example, the classes are modified which are defined in the previous example to show that the static
test variable defined in the Base class is in scope of the Extender class. The static test variable can be accessed
by the Extender class without prefixing the variable with the name of the class that defines test. Refer to the following
example:
package

import flash.display.MovieClip;

public class StaticExample extends MovieClip

public function StaticExample()

var myExt:Extender = new Extender();

class Base {

public static var test:String = “static”;

class Extender extends Base

public function Extender()

trace(test); // output: static

The instance property has higher precedence in the scope chain, if an instance property is defined that uses the same
name as a static property in the same class or a superclass. The static property is said to be shadowed by the instance
property. In simple terms it means that the value of the static property is used rather than the value of the instance
property as shown in the following example:
package

import flash.display.MovieClip;

public class StaticExample extends MovieClip

public function StaticExample()

var myExt:Extender = new Extender();

class Base

public static var test:String = “static”;


}

class Extender extends Base

public var test:String = “instance”; public function Extender()

{ trace(test); // output: instance

As shown in this example, the code demonstrates that if the Extender class defines an instance variable named test,
the trace() statement uses the value of the instance variable instead of the value of the static variable.

For detailed step-by-step procedure, refer to demo OOPs from:

eResources 4 Me>> My Varsity>> Web Animation and Interactivity>> Show Me How>> Inheritance>> Static properties
and the scope chain.

11.5 Summary
In this session, Object-Oriented Programming with ActionScript 3.0, you learned that:
¾¾ The elements of ActionScript that help to support Object-Oriented Programming (OOP).
¾¾ An abstract representation of an object is called a class. The syntax for a class definition is called for the class
keyword followed by the class name.
¾¾ Anything that can be a member of a class is termed as property, and it also includes variables.
¾¾ Variables can be declared with var or const keyboards.
¾¾ By using a combination of the static keyword and var or const keywords, static variables can be declared
which on attaching to a class and not an instance of a class, are used for storing and sharing information that
applies to an entire class of objects.
¾¾ A totalCount variable can be created to track the number of class instantiations and a MAX_NUM constant to
store the maximum number of instantiations.
¾¾ Instance variables that are attached to class instances are used to store values specific to an instance.
¾¾ Functions that are part of a class definition are called methods. A method is bound to an instance once instance
of the class is created and it cannot be used other than the instance to which it is attached.
¾¾ Constructor methods are also called as constructors. These functions share the same name as the class in
which they are defined.
¾¾ Static methods are also called class methods that are declared with the static keyword. They are useful for
encapsulating functionality that affects something and not the state of an individual instance.
¾¾ Methods that are declared without the static keyword are called instance methods. Instance methods attached
to instances of a class are useful for implementing functionality affecting individual instances of a class.
¾¾ get and set accessor methods allows follow of the programming principles and provides a user-friendly
programming interface for the classes created.
¾¾ To summarize a small set of values, create custom data types called as enumerations. A specific enumeration
facility is not supported by ActionScript 3.0, but enumerations using classes and static constants can be created.
¾¾ Embedded asset classes are special classes used in ActionScript 3.0 that represents assets. For example,
image, font, or sound being included in an SWF file at the time of compiling.
¾¾ A collection of method declarations that allows unrelated objects to communicate with one another is called an
interface.
¾¾ A code that allows programmers to develop new classes that are based on existing classes is called as
inheritance. The existing classes are called base classes or superclasses, and the new classes are known as
sub-classes.
¾¾ The ability to use a single method name for a method that behaves differently when applied to different data
types is termed as polymorphism.
¾¾ Whether an instance property is defined with the function, var, or const keywords, inherits all sub-classes
unless not declared with the private attribute in the Base class.
¾¾ Override a method means to redefine the behavior of an inherited method.
¾¾ While overriding a method, the behavior of the superclass method can be added instead of completely
replacing the behavior. This can be done using a mechanism that allows a method in a sub-class to call the
superclass version of it.
¾¾ Getters and setters can be overridden but not variables defined in a superclass.
¾¾ Static properties can be accessed through an instance of a sub-class. It can only be accessed through the class
object on which it is defined.
¾¾ Static properties are within the scope chain of the class that defines them and any sub-class of that class, even
if they are not inherited.

11.6 Exercise
1. Which of these stores information about the types of data that an object can hold and the behaviors that an object
can exhibit?

Variables

Classes

Array

Inheritance

2. A code that allows programmers to develop new classes that are based on existing classes is called as __________.

Interface

Polymorphism

Access control specifier

Inheritance

3. An instance property is inherited by all sub-classes as long as the property is not declared with the __________
attribute in the Base class.

private

public

static

protected

4. Properties can be overridden that are declared with the var or const keywords, but they can be inherited.

True

False

5. Attempting to access a private variable will not result in a run-time error when classes are declared with the dynamic
attribute.

True

False
Session 12
Working with ActionScript 3.0 Objects
Learning Outcomes
In this session, you will learn to:
¾¾ Understand the basic concept of Objects in AS 3.0 programming
¾¾ Identify properties in AS 3.0 programming
¾¾ Determine methods in AS 3.0 programming
¾¾ Understand Event Handling and process in AS 3.0 programming

12.1 Introduction
ActionScript is an object-oriented programming language. It helps in managing code by organizing it into logical chunks
known as objects. Objects are logical containers that have chunks of code providing similar functionality. In addition,
they may contain supporting information required by the code to provide this functionality.

In ActionScript 3.0, an object consists of the following three components:


¾¾ Properties
¾¾ Methods
¾¾ Events
These components help an object to manage the data, which is used by the code. They help in defining the order in
which data is to be processed and the actions are to be performed.

12.2 Properties
Properties represent pieces of data that is bundled together in an object. For example, a song object may have the name
of the artist and title of the song as its properties. In ActionScript 3.0, the MovieClip class has properties like width,
rotation, and alpha.

Properties are individual variables and are considered ‘child’ variables of an object.

A property can be accessed or modified by first mentioning the name of the object followed by a period (.) and then
mentioning the name of the property. Following are some examples of ActionScript code that uses property ‘x’ to move
the MovieClip object named ‘square’ to the ‘x’ coordinate by 110 pixels:

square.x = 110;

To match with the rotation of the triangle MovieClip, the following code uses the rotation property to make the
square MovieClip rotate accordingly.

square.rotation = triangle.rotation;

To change the size of the square MovieClip to one-and-a-half times wider than its original size, this code alters the
horizontal scale of the square MovieClip.

square.scaleX = 1.5;

A variable (square, triangle) is used as the name of the object which is followed by a period (.) and then the name
of the property (x, rotation, scaleX) is mentioned. The period is known as dot operator, which is used to specify
that one of the child elements of an object is being accessed.
12.3 Methods
An action that can be performed by an object is called as a method. For example, if a movie clip symbol in Flash is made
with some keyframes and animation on its timeline, then the MovieClip can be instructed either to play, stop, or move
the playhead to a particular frame.

The following code directs the MovieClip named shortFilm to start playing:

shortFilm.play();

The following code instructs the MovieClip named shortFilm to stop playing:

shortFilm.stop();

Here, the playhead stops in place, like pausing a video.

The following code directs a MovieClip named shortFilm to move its playhead to Frame 1 and stop playing:

shortFilm.gotoAndStop(1);

This code functions just like rewinding a video.

Just like properties, methods are accessed by writing the object’s name (variable), followed by a period, and the name
of the method, followed by parentheses. The parentheses indicate that the method has been called or the object has
been directed to execute an action. Values or variables can be placed in the parentheses to convey extra information
required to carry out an action by the method. These values or variables are called method parameters. For example,
the gotoAndStop() method requires a single parameter in the parentheses so as to know which frame it should go to.
The play() and stop() methods are easy to understand and are written with parentheses.

Methods are not used as value placeholders. Some methods can perform calculations and return a result that can be used
like a variable. For example, to convert the numeric value to its text representation, the Number class’s toString()
method is used as follows:
var numericData:Number = 9;

var textData:String = numericData.toString();

The actual text content displayed on the screen, which is the TextField class’s text property, is defined as a String
that contains only text values.
The numeric value in the variable numericData to text is converted by the line of code to show up on the screen in
the TextField object as follows:

calculatorDisplay:

calculatorDisplay.text = numericData.toString();

12.4 Events and Handling Events


An event is an important occurrence that triggers a response in a program, such as clicking or loading of a frame. In
ActionScript, events are split in two categories. Refer to Figure 12.1.

Figure 12.1: Categories of events


For detailed step-by-step procedure, refer to demo Custom events Demo, Use in-Build mouse event from:

eResources 4 Me>> My Varsity>> Web Animation and Interactivity>> Show Me How >> Events and Handling Events

12.4.1 Basics of Handling Events


The technique for specifying certain actions that should be performed in response to a particular event is known as
Event Handling.

In ActionScript 3.0, an event object represents each event that belongs to an instance of the Event class or one of
its sub-classes. An event object contains methods that assist in manipulation of the object and also stores information
about a specific event. It is similar to the Flash Player, which creates an event object on detecting a click. This event
object is an instance of the MouseEvent class that represents a particular mouse-click event.

Flash Player dispatches or passes an event object to the object which is the target of the event.

Even though the event target is on the display list, the event object passes down through the hierarchy until it reaches
the event target. Sometimes the event object ‘bubbles’ back the display list hierarchy along the same route. This display
list hierarchy is called the event flow.

By using event listeners, event objects can be listened. The functions or methods that are written to respond to specific
events are called event listeners. By adding event listeners to the event target or to any display list object, which is a
part of an event flow ensures that the program responds to events. Event listener code follows a basic structure, where
the elements in bold are the placeholders to be filled in for a specific case:
function eventResponse(eventObject:EventType):void

// Actions performed in response to the event go here.

eventTarget.addEventListener(EventType.EVENT_NAME, eventResponse);

Two things that the code does are as follows:


¾¾ It first defines a function specifying the actions that will be performed in response to the event.
¾¾ Secondly, it calls the addEventListener()method of the source object to ‘subscribe’ the function to the
specified event. This enables the function’s actions to be carried out when the event happens. The event target
checks its list of all the functions and methods that are registered as event listeners when the event actually
happens.
¾¾ Lastly, it calls each function, one by one, passing the event object as a parameter.
Click here to know more about handling events.

12.4.2 Difference between ActionScript 3.0 Event Handling and Earlier Versions
There is only one system for Event Handling in ActionScript 3.0 as compared to the previous versions of ActionScript 1.0
and 2.0. Following are the differences:
■■ Event Handling in previous versions of ActionScript

It described diverse ways to handle events as follows:


¾¾ The on() event handlers can be placed directly on Button and MovieClip instances.
¾¾ The onClipEvent() handlers can be placed directly on MovieClip instances.
¾¾ The Callback function has properties such as XML.onload and Camera.onActivity.
¾¾ The event listeners are registered using the addListener() method.
¾¾ The UIEventDispatcher class implemented the Document Object Model (DOM) event model partially.

These mechanisms have their own individual set of advantages and disadvantages that are as follows:
¾¾ It is easy to use the on() and onClipEvent() handlers, but maintenance of projects is hectic as it is difficult
to find the codes placed directly on the buttons.
¾¾ It is simple to implement Callback functions, but it allows only one function for any given event.
¾¾ Apparently, event listeners are more complicated to apply as they need the registration of the listener with the
object that generates the event along with the creation of a listener object and function. This creates some
listener objects and registers them all for the same event.

ActionScript 2.0 developed another event model that was embodied in the UIEventDispatcher class, which was
based on a sub-set of the DOM Events Specification. The transition to the new ActionScript 3.0 event model was
effortless.

The syntax used by the event models overlaps and differs. For example, some properties like TextField.
onChanged in ActionScript 2.0 can be used as a Callback function or as an event listener.

The syntax for registering listener objects varies depending on whether the UIEventDispatcher class or one of
the six classes that support listeners is being used. The Mouse, Key, MovieClipLoader, Selection, TextField
classes, and Stage can be used for using the addEventListener() method for Event Handling.
■■ Event Handling in ActionScript 3.0

A single Event Handling model was introduced in ActionScript 3.0 replacing the different Event Handling mechanisms
that existed in the previous versions of the language. This is based on the DOM Level 3 Events Specification. There
are adequate similarities between the display list and the structure of the DOM that makes the implementation of
the DOM event model possible. An object on the display list is similar to a node in the DOM hierarchical structure,
and the terms display list object and node that are used throughout. One such concept named default behaviors is
included in the Flash Player implementation of the DOM event model.
■■ Default behaviors

Flash Player is commonly associated with a behavior of an event that it involuntarily executes unless the developer
adds code to cancel it. Such behaviors are called default behaviors as Flash Player automatically exhibits them.
For example, when a text is entered into a TextField object, the behavior is built into Flash Player. This default
behaviour can be cancelled using the new Event Handling system. Flash Player creates an instance of the
TextEvent class when the user inputs text into a TextField object. To prevent this, the specific TextEvent
instance must be accessed and that instance’s preventDefault() method should be called.

Not all default behaviors can be prevented. For example, Flash Player generates a MouseEvent object when a user
double-clicks a word in the TextField object. This default behavior cannot be prevented and also the word under
the cursor gets highlighted. When a network connection is established, Flash Player dispatches a connect event
object, but a default behavior is not associated with it. Each type of event is listed by the API documentation for the
Event class and its sub-classes. It also describes any associated default behavior, and whether that behavior can
be prevented.

Default behaviors are associated only with event objects that are dispatched by the Flash Player. They do not exist
for event objects that are dispatched programmatically through ActionScript. For example, the methods of the
EventDispatcher class can be used to dispatch an event object of type textInput without a default behavior
associated with it. This means that a character in a TextField object will not be displayed by Flash Player due to
a textInput event being dispatched programmatically.
■■ Event listeners in ActionScript 2.0 and ActionScript 3.0

Refer to Table 12.1 that shows some key differences between the two event models.

ActionScript 2.0 ActionScript 3.0


To add event listeners in ActionScript 2.0, In ActionScript 3.0 only addEventListener() is used in
AddListeners() or addEventListener() is used. all situations.
Since the event flow is not there in ActionScript 2.0, the In ActionScript 3.0, any object can be called that is part
addListener() method can be called only on the of the event flow by using the addEventListener()
object that broadcasts the event. method.
Event listeners in ActionScript 2.0 can either be functions, In ActionScript 3.0, only functions or methods can be
methods, or objects. event listeners.
Table 12.1: Difference between ActionScript 2.0 and ActionScript 3.0
12.4.3 Event Flow
Whenever an event occurs, Flash Player dispatches event objects. It dispatches them directly to the event target, if it is
not on the display list. For example, the progress event object is dispatched directly by Flash Player to an URLStream
object. Flash Player dispatches the event object into the display list if the event target is on the display list and it travels
through it to the event target.

The way the event object moves through the display list is described by the event flow. The display list is arranged in a
hierarchy that starts with the Stage, which is a special display object container that serves as the root of the display list.
The flash.display.Stage class represents the Stage and is accessed through a display object. Each display object
has a property named Stage that refers to the Stage for that application.

When an event object is dispatched by the Flash Player, it moves from the Stage to the target node. The node representing
the event target is defined by the DOM Events Specification that defines the target node. In simpler terms, the target
node is the display list object where the event occurs. For example, Flash Player dispatches an event object using
Child1 as the target node, when a user displays list object named Child1.

The event flow is split into three parts. Refer to Figure 12.2.

Figure 12.2: Three parts of event flow

Refer to Figure 12.3 that shows a display list as a vertical hierarchy with the Stage at the top.

Figure 12.3: Event flow displaying a vertical hierarchy

Flash Player dispatches an event object into the event flow when a user clicks Child1 Node.

Refer to Figure 12.4, where the object begins at Stage, next it moves to Parent Node, and then finally to Child1 Node,
and then it goes again to Stage, repeating the same procedure. In this example, Stage and Parent Node are the
‘Capture Phases’. The time spent at Child1 Node is the ‘Target Phase’. The Parent Node and Stage are the ‘Bubbling
Phase’ and they are encountered while going up to the root node.
Figure 12.4: Event flow displaying Capture, Bubbling, and Target Phases

A more powerful Event Handling System is contributed by the event flow. However, it does not exist in the previous
versions of ActionScript.

When a user interface component comprises more than one object, then it is useful to add event listeners along with the
event flow. In the example, a button object that serves as the button’s label often contains a text object. In case a listener
is not added to the event flow, then both the button and the text objects need to be added to ensure that notification
is received about click events that occur anywhere on the button. Nevertheless, the event flow allows placing a single
event listener on the button object that handles click events.

Not all event objects take part in all three phases of the event flow. The enterFrame and init event types are some
of the types of events that are dispatched directly to the target node and participate in neither the Capture Phase nor the
Bubbling Phase. Events that are dispatched to an instance of the Socket class may not be present on the display list
and without participating in the Capture and Bubbling Phases these event objects will flow directly to the target object.

By either checking the API documentation or examining the event object’s properties, the behavior of a particular event
type can be found.

Quick Test 12.1


1. An action that can be performed by an object is called as a __________.

Handlers Listeners Events Method

2. There are two systems for event handling in ActionScript 3.0.


True False

12.4.4 Event Objects


There are two main purposes of the event objects in the new Event Handling System as follows:
¾¾ Actual events are represented by the event objects by storing information about specific events in a set of
properties.

¾¾ Event objects include a set of methods that provide its manipulation and also affect the behavior of the Event
Handling System.

The Flash Player API defines an Event class that serves as the base class for all event objects, enabling accessibility to
these properties and methods. Thus, a fundamental set of properties and methods that are common to all event objects
is defined by the Event class.

Click here to know more about event objects.

12.4.5 Event Listeners


Event listeners are also called as event handlers. These are functions that Flash Player executes in response to specific
events. A two step process is required for adding an event listener as follows:
¾¾ A function or class method is created for Flash Player to execute in response to the event, which is also
sometimes referred as the listener function or the event handler function.
¾¾ By using the addEventListener() method, the listener function can be registered with the target of the event
or any display list object that lies along the appropriate event flow.
■■ Creating a listener function

ActionScript 3.0 event model deviates from the DOM event model as it creates the listener functions.
¾¾ There is a clear difference between an event listener and a listener function in the DOM event model. An event
listener is an instance of a class that implements the EventListener interface. A listener function is a method
of a class named handleEvent(). However, there is no difference between an event listener and a listener
function in the ActionScript 3.0 event model. Moreover, it does not have an EventListener interface but the
listener functions can be defined outside a class or as a part of a class.
¾¾ In the DOM event model, the class instance is registered that contains the listener function. In ActionScript 3.0,
the name of the actual listener function is registered. Listener functions can be named with any valid identifier.
■■ Adding event listeners

The IEventDispatcher interface relies on the addEventListener() method, which is used to register listener
function. It requires two parameters:
¾¾ Type: This parameter is used to specify the type of event.
¾¾ Listener: This parameter is used to specify the listener function that will be implemented when the event occurs.
It can also be a reference to a function or a class method.

For specifying the listener parameter, do not use parentheses.

Click here to know more about adding event listeners.


■■ Removing event listeners

To remove an event listener, the removeEventListener() method can be used. It is advisable to remove any
listeners that will no longer be used. The necessary parameters are the eventName and listener parameters similar
to the parameters for the addEventListener() method. By calling addEventListener() twice, events can
be listened during all event phases; once by using useCapture, it can be set to true and later to false. By calling
removeEventListener() twice, both event listeners can be removed; once by using useCapture set to true,
and then by setting useCapture to false.

Click here to know more about event listeners.

12.5 Creating Object Instances


An object must exist before using it in ActionScript. An object can be created by declaring a variable, which in turn
creates an empty space in the computer’s memory. An actual variable must be assigned to the variable by creating an
object and storing the variable before using it. This is called as instantiating the object, which also means creating an
instance of a particular class.

Another easy method of creating an object instance does not require ActionScript. In Flash, when a movie clip symbol,
text field on the Stage, or button symbol, assign an instance name in the Property inspector, then Flash declares a
variable with that instance name and creates an object instance, which stores that object in the variable.

Object instances can also be created using only ActionScript. By using many ActionScript data types, an instance using
a literal expression can be created, which is the value written in the ActionScript code. For example,
■■ Literal numeric value (the number is entered directly):
var someNumber:Number = 17.239;

var someNegativeInteger:int = -53;

var someUint:uint = 22;

■■ Literal String value (these are surrounded by double quotation marks):


var firstName:String = “George”;

var soliloquy:String = “To be or not to be, that is the question...”;

■■ Literal Boolean value (literal values true or false should be used):


var niceWeather:Boolean = true;

var playingOutside:Boolean = false;

■■ Literal XML value (enter the XML directly):


<lastName>Webster</lastName>

</employee>;

■■ Literal expressions such as Array, RegExp, Object, and Function data types are defined in
ActionScript. The new operator with the class name can be used for any other data type
as follows:
var raceCar:MovieClip = new MovieClip();

var birthday:Date = new Date(2006, 7, 9);

“Calling the class’s constructor” is referred to by creating an object using the new operator. A special method known as
a constructor is called as part of the process of creating an instance of a class. It is important to note, that parentheses
should be put after the class name when creating an instance, and also parameter values should be specified.

The new operator can be used to create an object instance for data types that create instances using a literal
expression.

For example, refer to the following two lines:


var someNumber:Number = 6.33;

var someNumber:Number = new Number(6.33);

An instance can be created of any ActionScript data type that does not have a visual representation by creating the
object directly in ActionScript using the new operator.

The new operator, in Flash, can be used to create an instance of a movie clip symbol by defining it in the Library but not
placing on the Stage.

12.6 Toolkit for CreateJS


Flash Professional authoring environment is familiar to most of the designers. The Toolkit for CreateJS will enable
influencing the core animation and illustration capabilities of Flash Professional including vectors, bitmaps, tweens,
and sounds. Version 1.2 also provides support for buttons. This Toolkit is designed particularly to use efficiently the
Web development workflow. These assets and animations created in Flash Professional CS6, can be previewed in the
browser before exporting. Once developers receive the assets, they can leverage them as reusable JavaScript symbols
and interactivity can be added using the familiar CreateJS framework.

12.6.1 Convert Library to JavaScript in One Click


Traditionally, interactive designers have roped in Flash Professional for creating assets that target both the Flash Player
and Adobe AIR run-times. With the Flash Professional Toolkit for CreateJS, assets and animations can be exported to
JavaScript using the open source CreateJS framework. This output generates nicely formatted, readable, and editable
JavaScript code. This can kick-off designing for highly expressive content that runs on HTML5-compatible mobile or
desktop browser.

12.7 Summary
In this session, Working with ActionScript 3.0 Objects, you learned that:
¾¾ ActionScript is an object-oriented programming language. It helps in managing code by organizing it into
logical chunks known as objects. The three components in ActionScript 3.0 object-oriented programming are:
Properties, Methods, and Events.
¾¾ An event is an important occurrence that triggers a response in a program, such as mouse click or loading of a
frame. In ActionScript, events are split in two categories — namely, Built-in and Custom.
¾¾ The things that happen and the way they are responded to in ActionScript 3.0 are called events.
¾¾ An event object contains methods that assist in manipulation of the object and also stores information about a
specific event.
¾¾ Sometimes the event object ‘bubbles’ back the display list hierarchy along the same route. The display list
hierarchy is called the event flow.
¾¾ The functions or methods that are written to respond to specific events are called event listeners.
¾¾ The technique for specifying certain actions that should be performed in response to particular events is known
as Event Handling.
¾¾ Flash Player is commonly associated with a behavior with an event that it involuntarily executes unless the
developer adds code to cancel it. Such behavior is called as default behavior.
¾¾ Whenever an event occurs, Flash Player dispatches event objects directly to the event target if the event target
is not on the display list. The way the event object moves through the display list is described by the event flow.
The three parts of event flow are: Capture Phase, Target Phase, and Bubbling Phase.
¾¾ A number of read-only properties and constants that provide important information about an event object are
defined by the Event class.
¾¾ Event listeners are also called event handlers. These are functions that Flash Player executes in response to
specific events.
¾¾ An object can be created by declaring a variable, which in turn creates an empty space in the computer’s
memory. The objects can also be created using only ActionScript.
¾¾ The Toolkit for CreateJS will enable influencing the core animation and illustration capabilities of Flash
Professional including vectors, bitmaps, tweens, and sounds. Once developers receive the assets, they can
leverage them as reusable JavaScript symbols, and interactivity can be added using the familiar CreateJS
framework.
12.8 Exercise
1. The technique for specifying certain actions that should be performed in response to a particular event is known as
___________.

Event Handling

Event flow

Event listeners

Event method

2. Event listeners are also called as __________ .

Event flow

Event handlers

Event class

Event object

3. The functions or methods that are written to respond to specific events are called _________.

Event flow

Event class

Event listeners

Event object

4. The IEventDispatcher interface relies on the addEventListener() method, which is used to register listener
functions.

True

False

5. In ActionScript 2.0 only addEventListener() is used in all situations.

True

False
Answer Key

Quick Answers Exercise Answers


Quick Test 1.1 Exercise 1.6
1. False 2. True 1. Make default 2. Window
3. True 3. Join 4. Primitive objects
5. The layer can be
Quick Test 1.2
edited
1. False 2. False
3. False Exercise 2.7
1. False 2. The color swatch is
Quick Test 2.1
selected
1. False 2. False
3. Overflow modes 4. Four arrows in the
3. Fill Lock
shape of a circle
Quick Test 2.2 5. True
1. Paint Behind 2. False
Exercise 3.7
3. False
1. False 2. Classic input
Quick Test 3.1 3. Letter spacing 4. True
1. False 2. False 5. Input method
3. False editors

Quick Test 3.2 Exercise 4.10


1. False 2. True 1. True 2. Buttons
3. Compositing 4. Even if they are not
Quick Test 4.1
on the same layer
1. True 2. False
5. True 6. Filter presets
Quick Test 4.2 7. Window 8. Symmetry
1. False 2. False 9. False
Quick Test 5.1 Exercise 5.9
1. False 2. True 1. Timing 2. By increasing the
3. False frame rate
Quick Test 6.1 3. Number of frames, 4. Onion skinning mode
frame rate can be activated from
1. False 2. True
the Modify menu
3. False
5. Shape hints
Quick Test 7.1
Exercise 6.5
1. True 2. F LV P l a y b a c k
1. Tween span 2. Motion Editor
Component
3. False 4. Motion Editor
Quick Test 8.1 5. False
1. PNG 2. Smooth

Quick Test 9.1


1. Instantiating 2. False
Quick Answers Exercise Answers
Quick Test 10.1 Exercise 7.4
1. restrict 2. True 1. Skinning 2. True
3. False 4. Event
Quick Test 11.1
5. ScaleMode
1. namespace 2. True
Exercise 8.5
Quick Test 12.1
1. Adobe AIR 2. Mobile Content
1. Method 2. False
Simulator
3. AVI 4. False
5. True

Exercise 9.7
1. Compiling a 2. String
program
3. Constructor 4. True
parameter
5. False

Exercise 10.5
1. Dynamic text 2. Capture input from
the user’s camera

3. True 4. SoundChannel
4. False

Exercise 11.6
1. Classes 2. Inheritance
3. private 4. False
3. True

Exercise 12.8
1. Event Handling 2. Event handlers
3. Event listeners 4. True
5. False
Bibliography
Web Animation & Interactivity
- Christine Saucier

SVG for Web Developers


- Ellen Pearlman and Lorien House

Macromedia Flash MX Creative Web Animation and Interactivity


- Derek Franklin

You might also like