actionscript 3.0 bible_2nd_edition
TRANSCRIPT
-
www.it-ebooks.info
http://www.it-ebooks.info/
-
www.it-ebooks.info
http://www.it-ebooks.info/
-
ActionScript 3.0 Bible
www.it-ebooks.info
http://www.it-ebooks.info/
-
www.it-ebooks.info
http://www.it-ebooks.info/
-
ActionScript 3.0 BibleSecond Edition
Roger Braunstein
Wiley Publishing, Inc.
www.it-ebooks.info
http://www.it-ebooks.info/
-
ActionScript 3.0 Bible
Published byWiley Publishing, Inc.10475 Crosspoint BoulevardIndianapolis, IN 46256www.wiley.com
Copyright 2010 by Wiley Publishing, Inc., Indianapolis, Indiana
Published simultaneously in Canada
ISBN: 978-0-470-52523-4
Manufactured in the United States of America
10 9 8 7 6 5 4 3 2 1
No part of this publication may be reproduced, stored in a retrieval system or transmitted in any form or by anymeans, electronic, mechanical, photocopying, recording, scanning or otherwise, except as permitted under Sections107 or 108 of the 1976 United States Copyright Act, without either the prior written permission of the Publisher,or authorization through payment of the appropriate per-copy fee to the Copyright Clearance Center, 222 RosewoodDrive, Danvers, MA 01923, (978) 750-8400, fax (978) 646-8600. Requests to the Publisher for permission shouldbe addressed to the Permissions Department, John Wiley & Sons, Inc., 111 River Street, Hoboken, NJ 07030, (201)748-6011, fax (201) 748-6008, or online at http://www.wiley.com/go/permissions.
Limit of Liability/Disclaimer of Warranty: The publisher and the author make no representations or warrantieswith respect to the accuracy or completeness of the contents of this work and specifically disclaim all warranties,including without limitation warranties of fitness for a particular purpose. No warranty may be created or extendedby sales or promotional materials. The advice and strategies contained herein may not be suitable for every situation.This work is sold with the understanding that the publisher is not engaged in rendering legal, accounting, or otherprofessional services. If professional assistance is required, the services of a competent professional person should besought. Neither the publisher nor the author shall be liable for damages arising herefrom. The fact that an organi-zation or Web site is referred to in this work as a citation and/or a potential source of further information does notmean that the author or the publisher endorses the information the organization or Web site may provide or rec-ommendations it may make. Further, readers should be aware that Internet Web sites listed in this work may havechanged or disappeared between when this work was written and when it is read.
For general information on our other products and services please contact our Customer Care Department within theUnited States at (877) 762-2974, outside the United States at (317) 572-3993 or fax (317) 572-4002.
Wiley also publishes its books in a variety of electronic formats. Some content that appears in print may not be avail-able in electronic books.
Library of Congress Control Number: 2009943640
Trademarks: Wiley and the Wiley logo are trademarks or registered trademarks of John Wiley & Sons, Inc. and/orits affiliates, in the United States and other countries, and may not be used without written permission. ActionScriptis a registered trademark of Adobe Systems Incorporated. All other trademarks are the property of their respectiveowners. Wiley Publishing, Inc. is not associated with any product or vendor mentioned in this book.
www.it-ebooks.info
http://www.wiley.comhttp://www.wiley.com/go/permissionshttp://www.it-ebooks.info/
-
About the AuthorRoger Braunstein is a multidisciplinary programmer and the Chief Roger Officer of partlyhuman inc.,an independent development and design shop in Brooklyn, NY. Roger is an author of the first editionof ActionScript 3.0 Bible, and a short e-book, Introduction to Flex 2. Roger builds games, mobile apps,interactive art, tools, web apps, and websites using any technology he can wrap his head around. Injust the past two years hes built stuff for LEGO, MoMA, Tim Burton, Antony and the Johnsons, AOL,HBO, Puma, General Mills, Sport Chalet, Pepsi, Coke, OMGPOP, the French Culinary Institute, andmore. Additionally, he keeps busy with a series of independent projects. When not in front of a com-puter, Roger enjoys normal human activities such as biking, cooking, reading, traveling, taking photos,roller-skating, and dancing to music made on GameBoys. He is perpetually too preoccupied to putanything interesting on his site http://partlyhuman.com/, but you can use it to get in touchwith him.
www.it-ebooks.info
http://partlyhuman.com/http://www.it-ebooks.info/
-
www.it-ebooks.info
http://www.it-ebooks.info/
-
Credits
Acquisitions EditorScott Meyers
Project EditorBrian MacDonald
Technical EditorCaleb Johnston
Production EditorDaniel Scribner
Copy EditorKaren Gill
Editorial DirectorRobyn B. Siesky
Editorial ManagerMary Beth Wakefield
Marketing ManagerDavid Mayhew
Production ManagerTim Tate
Vice President and ExecutiveGroup PublisherRichard Swadley
Vice President and ExecutivePublisherBarry Pruett
Associate PublisherJim Minatel
Project Coordinator, CoverLynsey Stanford
ProofreaderNancy Bell
IndexerRobert Swanson
Cover ImageJoyce Haughey
Cover DesignerMichael E. Trent
www.it-ebooks.info
http://www.it-ebooks.info/
-
www.it-ebooks.info
http://www.it-ebooks.info/
-
This book, like all gargantuan projects, was a team effort. Its pages were touched by manyhands, at Wiley and elsewhere. Losing even a single pair of these hands would mean youwouldnt have this book in yours right now, so I want to thank each and every person onmy team, whether I sent you 20 e-mails a day or never met you.
My most heartfelt thanks go to my project editor Brian MacDonald, and my acquisitions editorScott Meyers, who were nothing short of bodacious to work with. When I think of how many times Ipushed for some new, unconventional feature or change to the established Bible series, and then lookat this book and see all of my ideas in print, I know its Brian and Scott who have somehow donetheir magic, convinced the right people, and made it happen. Thank you.
Perhaps every author forms a good relationship with his project editor just because hes the personwhos there from the first day of writing through the last, exhausted round of edits. But I think BrianMacDonald is exceptional. Ive never worked with an editor half as good. He had the right solutionfor every problem. He was behind me and my ideas through thick and thin. His edits were alwaysspot-on. He was always available, always funny, and he even got my nerdy jokes. Trust me, if yourewriting a programming book, bribe whoever you need to hire Brian.
I cant talk about my team without mentioning the exhaustive copy editing done by Karen Gill. Shekept tabs on all my writing, cut down my useless tiresome redundant logorrhea, and made this bookless of a slog to get through. Trust me, you owe her one. I have the feeling her job is a little thankless,but I do thank her.
Caleb Johnston, besides being a good friend, was a terrific technical editor. Somehow, with a fullcourse load for his masters degree, he managed to find the time to review this entire book by him-self. (The previous edition, although smaller, had three technical editors!) More than just scrutinizingit, he made detailed and thoughtful criticisms, with as much ruthlessness as I demanded of him. Hefound some quirky errors, and because he found them, you wont have to.
Special thanks go out to my friend Corey Lucier at Adobe, who was kind enough to answer a fewquestions about the internal workings of Flash Player or forward them on to Flash Player engineers.Their additions helped me be even more accurate in this book, and Coreys help was invaluable.
Special thanks also go to Whitney Gardner, who made two sublime illustrations for this book when Iwas at my wits end.
Thanks to the U.S. economy for making my day job so unprofitable it made sense to sit in myroom and write for nine months. Thanks to coffee: you complete me. Thanks to my crazy SafeTypekeyboard, which saved me from crippling arm pain. Thanks to my friends for, I dunno, whatever,I like you.
Last but not least, thanks and lotsa lotsa love to my parents.
ix
www.it-ebooks.info
http://www.it-ebooks.info/
-
www.it-ebooks.info
http://www.it-ebooks.info/
-
Introduction ..............................................................................................................................................xli
Part I: ActionScript 3.0 Language Basics . . . . . . . . . . . . . . . . . . . . 1Chapter 1: Introducing ActionScript 3.0 ...................................................................................................3Chapter 2: ActionScript 3.0 Language Basics ..........................................................................................15Chapter 3: Functions and Methods .........................................................................................................39Chapter 4: Object Oriented Programming ..............................................................................................51Chapter 5: Validating Your Program .....................................................................................................103
Part II: Core ActionScript 3.0 Data Types . . . . . . . . . . . . . . . . . 111Chapter 6: Text, Strings, and Characters ..............................................................................................113Chapter 7: Numbers, Math, and Dates .................................................................................................125Chapter 8: Arrays ...................................................................................................................................145Chapter 9: Vectors .................................................................................................................................167Chapter 10: Objects and Dictionaries ...................................................................................................181Chapter 11: XML and E4X ....................................................................................................................191Chapter 12: Regular Expressions ...........................................................................................................225Chapter 13: Binary Data and ByteArrays ..............................................................................................257
Part III: The Display List . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 271Chapter 14: Visual Programming with the Display List .......................................................................273Chapter 15: Working in Three Dimensions ..........................................................................................301Chapter 16: Working with DisplayObjects in Flash Professional ........................................................321Chapter 17: Text, Styles, and Fonts ......................................................................................................329Chapter 18: Advanced Text Layout .......................................................................................................367Chapter 19: Printing ..............................................................................................................................399
Part IV: Event-Driven Programming . . . . . . . . . . . . . . . . . . . . . 407Chapter 20: Events and the Event Flow ...............................................................................................409Chapter 21: Interactivity with the Mouse and Keyboard .....................................................................429Chapter 22: Timers and Time-Driven Programming ............................................................................461Chapter 23: Multitouch and Accelerometer Input ................................................................................473
Part V: Error Handling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .489Chapter 24: Errors and Exceptions .......................................................................................................491Chapter 25: Using the AVM2 Debugger ...............................................................................................505Chapter 26: Making Your Application Fault-Tolerant ..........................................................................523
Part VI: External Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 531Chapter 27: Networking Basics and Flash Player Security ...................................................................533Chapter 28: Communicating with Remote Services .............................................................................561
xi
www.it-ebooks.info
http://www.it-ebooks.info/
-
Contents at a Glance
Chapter 29: Storing and Sending Data with SharedObject ..................................................................571Chapter 30: File Access .........................................................................................................................589
Part VII: Sound and Video . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 603Chapter 31: Playing and Generating Sound ......................................................................................... 605Chapter 32: Playing Video .....................................................................................................................625Chapter 33: Capturing Sound and Video .............................................................................................643
Part VIII: Graphics Programming and Animation . . . . . . . . . .655Chapter 34: Geometric and Color Transformations .............................................................................657Chapter 35: Programming Vector Graphics ..........................................................................................687Chapter 36: Programming Bitmap Graphics .........................................................................................733Chapter 37: Applying Filters .................................................................................................................769Chapter 38: Writing Shaders with Pixel Bender ...................................................................................803Chapter 39: Scripting Animation ...........................................................................................................835Chapter 40: Advanced 3D .....................................................................................................................855
Part IX: Flash in Context . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .877Chapter 41: Globalization, Accessibility, and Color Correction ..........................................................879Chapter 42: Deploying Flash on the Web ............................................................................................897Chapter 43: Interfacing with JavaScript ................................................................................................905Chapter 44: Local Connections between Flash Applications ...............................................................911
Index .......................................................................................................................................................921
xii
www.it-ebooks.info
http://www.it-ebooks.info/
-
Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xli
Part I: ActionScript 3.0 Language Basics 1
Chapter 1: Introducing ActionScript 3.0 . . . . . . . . . . . . . . . . . . . . . . . . . 3What Is ActionScript 3.0? ...............................................................................................................3Exploring the Flash Platform ..........................................................................................................4
A Programmers Perspective ................................................................................................. 5Language .....................................................................................................................5API .............................................................................................................................6
Libraries ......................................................................................................................7Compilers, Tools, and IDEs .......................................................................................7SWFs .........................................................................................................................8
Flex .............................................................................................................................9In Short .......................................................................................................................9
A Users Perspective ..............................................................................................................9Runtimes .....................................................................................................................9Platforms and Platform Independence ....................................................................10The Flash Player Zoo ...............................................................................................10In Short .....................................................................................................................11
From ActionScript 2.0 to ActionScript 3.0 ...................................................................................11Display List ..........................................................................................................................11Runtime Errors ....................................................................................................................12Runtime Data Types ............................................................................................................12Method Closures .................................................................................................................12Intrinsic Event Model .........................................................................................................12Regular Expressions ............................................................................................................12E4X ......................................................................................................................................12
Summary ........................................................................................................................................13
Chapter 2: ActionScript 3.0 Language Basics . . . . . . . . . . . . . . . . . . . . . 15The Bare Essentials ........................................................................................................................15Using Variables ..............................................................................................................................17
Anatomy of a Variable Declaration .....................................................................................17Constants in This Changing World ...................................................................................18Taking It Literally ...............................................................................................................18
xiii
www.it-ebooks.info
http://www.it-ebooks.info/
-
Contents
Commenting Your Code ................................................................................................................20Types of Comments ............................................................................................................20
Single-Line Comment ...............................................................................................20Block Comments ......................................................................................................20XML Comments .......................................................................................................20Javadoc Comments ...................................................................................................21
When to Use Comments ....................................................................................................21Self-Commenting Code .......................................................................................................21
Introducing Scope ......................................................................................................................... 22Introducing the Data Types ..........................................................................................................23
Declaring Types ...................................................................................................................23Using Untyped Variables ....................................................................................................23
Connecting You to an Operator ....................................................................................................23Unary vs. Binary Operators ................................................................................................24Order of Operations ........................................................................................................... 24Some Commonly Used Operators ......................................................................................24
Assignment (=) ........................................................................................................24Arithmetic (+, , *, /) .............................................................................................24Modulo (%) ..............................................................................................................25Increment (++) and Decrement ( ) ....................................................................25Compound Assignment Operators (+ =, =, *=, /=, and % =) .......................25Comma Operator (,) ................................................................................................26
Making Logical Choices with Conditionals ..................................................................................26if Statements ........................................................................................................................26Equality (==) .....................................................................................................................27Testing Other Comparisons ................................................................................................27
Greater Than (>) and Less Than (
-
Contents
Chapter 3: Functions and Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39Calling Functions ...........................................................................................................................39Creating Custom Functions ..........................................................................................................40
Defining a Function ............................................................................................................40Passing Arguments to Your Function .................................................................................41
Passing by Reference or by Value ............................................................................41Setting Default Values ..............................................................................................43Using the Rest Parameter (...) ..................................................................................43
Returning Results ...........................................................................................................................44Returning a Value Using a return Statement .....................................................................45
Defining a Return Type for Your Function .............................................................46Returning Void .........................................................................................................46
Anonymous Functions ...................................................................................................................46Functions as Objects .....................................................................................................................47Recursive Functions .......................................................................................................................48Summary ........................................................................................................................................50
Chapter 4: Object Oriented Programming . . . . . . . . . . . . . . . . . . . . . . 51Understanding Classes ...................................................................................................................51
Classes Can Model the Real World ....................................................................................51Classes Contain Data and Operations ................................................................................52Classes Separate Responsibilities ........................................................................................52Classes Are Types ................................................................................................................52Classes Contain Your Program ...........................................................................................53
Object Oriented Terminology .......................................................................................................53Object ..................................................................................................................................53Class ....................................................................................................................................54Instance ...............................................................................................................................54Type .....................................................................................................................................54
Encapsulation: Classes Are Like, So Selfish ..................................................................................55The Black Box Principle ..................................................................................................... 55Encapsulation and Polymorphism ......................................................................................56
Packages: Classes, Functions, and Packing Peanuts .....................................................................56Class Uniqueness and Namespaces ....................................................................................56Hierarchy .............................................................................................................................57Controlling Visibility ...........................................................................................................58Code Allowed in Packages ..................................................................................................58Using Code from Packages .................................................................................................59
Using Inheritance ...........................................................................................................................61Structuring Code with Inheritance .....................................................................................64Inheritance, Types, Polymorphism, and You .....................................................................66Inheritance vs. Composition ...............................................................................................67Preventing Inheritance ........................................................................................................69
Access Control Attributes ..............................................................................................................70Public and Private ...............................................................................................................71Protected ..............................................................................................................................73Internal ................................................................................................................................74Custom Access Control with Namespaces .........................................................................75
Methods and Constructors ............................................................................................................77
xv
www.it-ebooks.info
http://www.it-ebooks.info/
-
Contents
Properties .......................................................................................................................................78Accessors .............................................................................................................................79Avoid Side Effects ...............................................................................................................81Self-Referential Code ...........................................................................................................82
Using Static Methods and Properties ............................................................................................83Static Variables ....................................................................................................................84Static Constants ...................................................................................................................85Enumerations ......................................................................................................................87Static Methods .....................................................................................................................87
Overriding Behavior ......................................................................................................................89Accessing the Superclass .....................................................................................................90
Designing Interfaces .......................................................................................................................92Manipulating Types .......................................................................................................................96
Type Compatibility and Coercion ......................................................................................97Explicit Type Conversion ...................................................................................................98Determining Types ............................................................................................................100
Creating Dynamic Classes ...........................................................................................................100Summary ......................................................................................................................................101
Chapter 5: Validating Your Program . . . . . . . . . . . . . . . . . . . . . . . . . . 103Introducing Errors .......................................................................................................................103
Compile-Time Errors vs. Runtime Errors ........................................................................104Compile-Time Errors .............................................................................................104Runtime Errors .......................................................................................................104
Warnings ...........................................................................................................................104Getting Feedback from Flash Professional and Flash Builder .........................................104
Debugging in Flash Professional ............................................................................104Debugging in Flash Builder ...................................................................................106
Fixing Errors ................................................................................................................................108Summary ......................................................................................................................................110
Part II: Core ActionScript 3.0 Data Types 111
Chapter 6: Text, Strings, and Characters . . . . . . . . . . . . . . . . . . . . . . . 113Working with String Literals .......................................................................................................113
Using Escaped Characters .................................................................................................114Converting to and from Strings ..................................................................................................115
Using toString() .................................................................................................................115Casting and Converting to Strings ...................................................................................116Converting Strings into Other Types ...............................................................................116
Converting Strings to Numbers .............................................................................116Converting Strings to Arrays ..................................................................................117
Combining Strings .......................................................................................................................118Converting the Case of a String ..................................................................................................118Using the Individual Characters in a String ...............................................................................119
Getting the Number of Characters in a String ................................................................119Getting a Particular Character ..........................................................................................120Converting a Character to a Character Code ...................................................................120
Searching within a String ............................................................................................................120
xvi
www.it-ebooks.info
http://www.it-ebooks.info/
-
Contents
Searching by Substring .....................................................................................................120Searching with Regular Expressions .................................................................................121
String Dissection ..........................................................................................................................122String Encoding and International Text .....................................................................................123Summary ......................................................................................................................................123
Chapter 7: Numbers, Math, and Dates . . . . . . . . . . . . . . . . . . . . . . . . 125Understanding Numeric Types ...................................................................................................125
Sets of Numbers ................................................................................................................125Representing Numbers ......................................................................................................126Digital Representations of Numbers .................................................................................126
Unsigned Integers ...................................................................................................126Signed Integers .......................................................................................................127Floating-Point Numbers .........................................................................................127
Using Numbers in ActionScript ..................................................................................................128Number .............................................................................................................................128int ......................................................................................................................................129uint ....................................................................................................................................129Literals ...............................................................................................................................130Edge Cases ........................................................................................................................130
Not a Number ........................................................................................................131Infinity ....................................................................................................................131Minimum and Maximum Values ...........................................................................131
Manipulating Numbers ................................................................................................................132Numeric Conversions .......................................................................................................132String Conversions ............................................................................................................132
Performing Arithmetic .................................................................................................................133Performing Trigonometric Calculations ......................................................................................135Generating Randomness ..............................................................................................................137Manipulating Dates and Times ...................................................................................................138
Creating a Date .................................................................................................................138Epoch Time .......................................................................................................................139Time zones ........................................................................................................................140Accessing and Modifying a Date ......................................................................................141Date Arithmetic .................................................................................................................142Execution Time .................................................................................................................142Formatting a Date .............................................................................................................143
Summary ......................................................................................................................................144
Chapter 8: Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 145Array Basics ..................................................................................................................................145
Using the Array Constructor ............................................................................................145Creating an Array by Using an Array Literal ...................................................................147Referencing Values in an Array ........................................................................................147Finding the Number of Items in an Array .......................................................................148
Converting Arrays to Strings .......................................................................................................148Adding and Removing Items from an Array ..............................................................................149
Appending Values to the End of Your Array with concat() ............................................149Applying Stack Operations push() and pop() .................................................................150Applying Queue Operations shift() and unshift() ...........................................................151
xvii
www.it-ebooks.info
http://www.it-ebooks.info/
-
Contents
Slicing, Splicing, and Dicing .......................................................................................................152Inserting and Removing Values with splice() ..................................................................152Working with a Subset of your Array with slice() ..........................................................152
Iterating through the Items in an Array .....................................................................................153Using a for Loop ...............................................................................................................153Using for each..in ..............................................................................................................154Using the forEach() Method .............................................................................................154
Searching for Elements ................................................................................................................155Reordering Your Array ................................................................................................................155
Using Sorting Functions ...................................................................................................156Flipping the Order of Your Array Using Reverse() .........................................................159
Applying Actions to All Elements of an Array ...........................................................................159Conditional Processing with every(), some(), and filter() ...............................................159Getting Results with the map() Method ..........................................................................162
Alternatives to Arrays ..................................................................................................................162Associative Arrays .............................................................................................................162Multidimensional Arrays ...................................................................................................163
Amazing Properties of Arrays ......................................................................................................165Summary ......................................................................................................................................165
Chapter 9: Vectors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 167Vector Basics ................................................................................................................................167
Why Do We Need Another Datatype? .............................................................................168Array: More Functionality Than You Require .................................................................169Vectors: Arrays with Benefits ............................................................................................170Fixed-Size Vectors .............................................................................................................172
Generics and Parameterized Types .............................................................................................173Vector as a Generic ...........................................................................................................173No Generics for You .........................................................................................................174
Generic Methods of Vector .........................................................................................................176Creating and Converting Vectors ................................................................................................178
Vector literals ....................................................................................................................179Converting Types of Vectors ............................................................................................179Converting a Vector into an Array ...................................................................................180
Summary ......................................................................................................................................180
Chapter 10: Objects and Dictionaries . . . . . . . . . . . . . . . . . . . . . . . . . 181Working with Objects .................................................................................................................181
Dynamic Classes ...............................................................................................................181Creating Objects ............................................................................................................... 182Accessing Object Properties ..............................................................................................182toString() ...........................................................................................................................183
Using Objects and Dictionaries as Associative Arrays ................................................................183Comparing Arrays, Objects, and Dictionaries ..................................................................184Testing for Existence .........................................................................................................186Removing Properties .........................................................................................................187Iterating .............................................................................................................................188
xviii
www.it-ebooks.info
http://www.it-ebooks.info/
-
Contents
Using Objects for Named Arguments .........................................................................................188Using Objects as Nested Data .....................................................................................................189
XML as Objects ............................................................................................................... 189JSON ................................................................................................................................190
Summary ......................................................................................................................................190
Chapter 11: XML and E4X . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 191Getting Started with XML in ActionScript .................................................................................191
XML References ...............................................................................................................191E4X References ..................................................................................................................192XML Literals .....................................................................................................................192
A Brief Introduction to E4X Operators and Syntax ........................................................194Legacy XML Handling ......................................................................................................195
Querying XML .............................................................................................................................196The Child Axis ..................................................................................................................196The Wildcard Operator ....................................................................................................197Indexed Elements ..............................................................................................................197The Attribute Axis .............................................................................................................198The Text Axis ....................................................................................................................199The Descendant Axis ........................................................................................................200The Parent Axis .................................................................................................................201Custom Filter Axes ...........................................................................................................201Quick Reference ................................................................................................................203
Modifying XML ............................................................................................................................203Inserting Nodes .................................................................................................................203
Inserting with E4X Operators ................................................................................204Inserting with E4X Methods ..................................................................................206
Removing Nodes and Attributes ...................................................................................... 207Duplicating XML ...............................................................................................................208Replacing Nodes ...............................................................................................................209
Converting to and from Strings ..................................................................................................209Converting Strings to XML ...............................................................................................210Converting XML to Strings ...............................................................................................210
Printing Pretty ........................................................................................................211Setting the Number of Spaces per Indentation .....................................................211Normalizing Text Nodes ........................................................................................212
Loading XML Data from External Sources .................................................................................212Gathering Meta-Information about XML Nodes .........................................................................213
Finding Node Types .........................................................................................................213Determining the Type of Content in a Node ..................................................................214
Using Namespaces .......................................................................................................................215Creating XML Namespaces in ActionScript .....................................................................216
Using the Namespace Class ...................................................................................216Using the Namespace Keyword .............................................................................217Making Namespaces Available ...............................................................................217
xix
www.it-ebooks.info
http://www.it-ebooks.info/
-
Contents
Querying Namespaced XML Nodes .................................................................................217Opening Namespaces .............................................................................................218Using the Scope Resolution Operator ...................................................................219Setting the Default XML Namespace .....................................................................220
Querying XML for Namespaces ....................................................................................... 221Additional Namespace Operations ...................................................................................222
Setting XML Options ...................................................................................................................223Summary ......................................................................................................................................223
Chapter 12: Regular Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 225Introducing Regular Expressions ................................................................................................225Writing a Regular Expression .....................................................................................................226Applying Regular Expressions .....................................................................................................226
String Methods and RegExp Methods ..............................................................................226Testing ...............................................................................................................................227Locating .............................................................................................................................228Identifying .........................................................................................................................229Extracting ..........................................................................................................................231Replacing ...........................................................................................................................233Splitting .............................................................................................................................235
Constructing Expressions ............................................................................................................235Normal Characters ............................................................................................................236Dot Character ....................................................................................................................236Escaped Characters ...........................................................................................................236Metacharacters and Metasequences Demystified .............................................................237Character Classes ..............................................................................................................238Quantifiers .........................................................................................................................239Anchors and Boundaries ...................................................................................................240Alternation .........................................................................................................................242Groups ...............................................................................................................................242
Regular Expression Flags .............................................................................................................243Global ................................................................................................................................243Ignore Case .......................................................................................................................244Multiline ............................................................................................................................244Dotall .................................................................................................................................245Extended ...........................................................................................................................246
Constructing Advanced Expressions ...........................................................................................246Greedy and Lazy Matching ...............................................................................................247Backreferences ...................................................................................................................248Lookahead and Noncapturing Groups .............................................................................249
Noncapturing Groups ............................................................................................249Positive Lookahead Groups ...................................................................................249Negative Lookahead Groups ..................................................................................250
Named Groups ..................................................................................................................250International Concerns .....................................................................................................252
Using the RegExp Class ...............................................................................................................252Building Dynamic Expressions with String Operations .................................................. 252RegExp Public Properties ..................................................................................................253
Summary ......................................................................................................................................253
xx
www.it-ebooks.info
http://www.it-ebooks.info/
-
Contents
Chapter 13: Binary Data and ByteArrays . . . . . . . . . . . . . . . . . . . . . . . . 257Binary Concepts ...........................................................................................................................257Bit Math and Operators ...............................................................................................................260
Basic Arithmetic ................................................................................................................260Bit Shifting ........................................................................................................................ 260Bitwise Logic .....................................................................................................................262
Binary Types in ActionScript ......................................................................................................263Using ByteArray ...........................................................................................................................265
Creating a ByteArray .........................................................................................................265Writing Data ......................................................................................................................265Reading Data .....................................................................................................................265Compressing and Decompressing ....................................................................................266
Common Uses of ByteArrays ...................................................................................................... 266Loading Images .................................................................................................................266Copying Objects ............................................................................................................... 267
Summary ......................................................................................................................................268
Part III: The Display List 271
Chapter 14: Visual Programming with the Display List . . . . . . . . . . . . . 273Introducing Display Lists and Display Objects ..........................................................................273
Structure of the Display List .............................................................................................274Coordinate Spaces .............................................................................................................274Manipulating the Display List ..........................................................................................276
Creating a New Display Object .............................................................................276Adding an Object to a Display List .......................................................................277Removing an Object from a Display List ..............................................................278Re-sorting Depths ...................................................................................................278Reparenting Display Objects ..................................................................................279Examining Display Lists .........................................................................................279
Display Object Classes ................................................................................................................ 280DisplayObject ....................................................................................................................280InteractiveObject ...............................................................................................................283DisplayObjectContainer ....................................................................................................283Shape .................................................................................................................................284Bitmap ...............................................................................................................................284Video .................................................................................................................................284AVM1Movie .....................................................................................................................284
SimpleButton .....................................................................................................................284TextField ...........................................................................................................................285Sprite .................................................................................................................................285MovieClip ..........................................................................................................................285Loader ................................................................................................................................286Stage ..................................................................................................................................286
Resizing ...................................................................................................................286Changing SWF Properties ......................................................................................286Going Full-Screen ...................................................................................................287
xxi
www.it-ebooks.info
http://www.it-ebooks.info/
-
Contents
Device Orientation .................................................................................................288Event Source and Focus Manager .........................................................................289Color Correction ....................................................................................................289
Geometry Classes .........................................................................................................................289Point ..................................................................................................................................289Rectangle ...........................................................................................................................290
Putting the Display List to Use ...................................................................................................292Drag-and-Drop, Hit Testing .............................................................................................292Nesting and Cumulative Transformations .......................................................................294Full-Screen and Stage Resizing .........................................................................................295
Rendering and Performance ........................................................................................................297Stage Size and Dirty Rectangles ........................................................................................297Number of Display Objects ..............................................................................................297Alpha, Blend Modes, Masking, and Filters ......................................................................297Text ................................................................................................................................... 298Bitmaps, Vectors, and Bitmap Caching ............................................................................298More on Rendering ...........................................................................................................299
Summary ......................................................................................................................................299
Chapter 15: Working in Three Dimensions . . . . . . . . . . . . . . . . . . . . . 301Introducing 3D in ActionScript 3.0 ............................................................................................301
The 3D Coordinate System ..............................................................................................3033D in Flash Professional ...................................................................................................304Limitations of 3D Display Objects ...................................................................................304
Display Objects are Flat .........................................................................................305A Viewport Isnt a Camera .....................................................................................305Depths Are Managed by the DisplayObjectContainer ..........................................305Other Missing Stuff ................................................................................................305
DisplayObject Revisited ...............................................................................................................306Geometry Revisited ......................................................................................................................309Mouse and Point Translation in 3D ...........................................................................................311
Translating Points in Code ...............................................................................................312Modifying the Projection .............................................................................................................314Software 3D Libraries ..................................................................................................................318Summary ......................................................................................................................................319
Chapter 16: Working with DisplayObjects in Flash Professional . . . . . . 321The Stage, Symbols, and the Library ..........................................................................................321
Creating Symbols ..............................................................................................................322Named Instances ...............................................................................................................323Nested Instances ...............................................................................................................324Associating Symbols to Classes ........................................................................................324Writing an Associated Class .............................................................................................326Nongraphic Symbol Types ...............................................................................................326
Exporting and Using Assets ........................................................................................................327Using Assets from a SWC .................................................................................................327Using Assets from a SWF .................................................................................................327
Summary ......................................................................................................................................328
xxii
www.it-ebooks.info
http://www.it-ebooks.info/
-
Contents
Chapter 17: Text, Styles, and Fonts . . . . . . . . . . . . . . . . . . . . . . . . . . . 329Introducing TextFields ................................................................................................................329
Creating a New TextField .................................................................................................330Adding and Replacing Text ..............................................................................................330Setting a TextFields Size ..................................................................................................330Setting a TextFields Scaling and Rotation .......................................................................332Wrapping Text ..................................................................................................................332Preventing User Selection .................................................................................................333Displaying Multilingual Text and Symbols ......................................................................334
Text with HTML and CSS ...........................................................................................................334HTML Support in TextField ...........................................................................................334
Adding Images or SWF Files to a TextField with .............................................335Supported CSS Properties .................................................................................................336The StyleSheet Object and CSS Parsing ...........................................................................337
Background and Border Treatments ...........................................................................................339Styling Text with TextFormats ....................................................................................................339
align ...................................................................................................................................341blockIndent .......................................................................................................................341bold ...................................................................................................................................341bullet .................................................................................................................................341color ..................................................................................................................................341font ....................................................................................................................................342indent ................................................................................................................................342italic ...................................................................................................................................342leading ...............................................................................................................................342letterSpacing ......................................................................................................................342leftMargin ..........................................................................................................................342rightMargin ........................................................................................................................343size .....................................................................................................................................343tabStops .............................................................................................................................343target ..................................................................................................................................343underline ...........................................................................................................................343url ......................................................................................................................................344
Input TextFields ..........................................................................................................................344The Three Kinds of Text Fields .......................................................................................344Making a TextField an Input Field ..................................................................................345Restricting User Input .......................................................................................................345Tab-Accessible Input Text Fields .....................................................................................347Password Text Fields ........................................................................................................347
Interaction with TextField Events ...............................................................................................347focusIn and focusOut Events ...........................................................................................347Text Input Events .............................................................................................................349Link Events .......................................................................................................................352Scroll Events ......................................................................................................................354
Interactive Typography ................................................................................................................354Text by Lines and Paragraphs ..........................................................................................354Finding Text by Location .................................................................................................356
xxiii
www.it-ebooks.info
http://www.it-ebooks.info/
-
Contents
Locating and Measuring Text ...........................................................................................356Scrolling Text ....................................................................................................................358
Fonts ............................................................................................................................................360Device Fonts and Embedded Fonts .................................................................................360Managing Active Fonts and the Font Object ...................................................................362Embedding Fonts ..............................................................................................................362
Flash Builder, Flex Builder, Flex SDK, mxmlc .....................................................362Flash Professional ...................................................................................................363
Loading Fonts Dynamically ..............................................................................................364Using Embedded Fonts ....................................................................................................364Anti-aliasing ...................................................................................................................... 365
Fitting Edges to a Grid ..........................................................................................366Sharpness and Thickness .......................................................................................366
Summary ......................................................................................................................................366
Chapter 18: Advanced Text Layout . . . . . . . . . . . . . . . . . . . . . . . . . . . 367Understanding Advanced Text Controls .....................................................................................367
Advanced Text Controls in Development Tools ..............................................................369Why There Are Two Engines ...........................................................................................369Where to Go from Here ...................................................................................................369
The Flash Text Engine ................................................................................................................370The Text Layout Framework .......................................................................................................372
Storing Content and Formatting with Models .................................................................373Laying Out Text with Controllers ....................................................................................375
Simple Composition with TextLine Factories .......................................................375Linked Container Composition with ContainerControllers and
FlowComposers ...................................................................................................378Text Layout Markup .........................................................................................................381
Setting Up TLF Markup .........................................................................................382TLF Tags ...............................................................................................................383
Importing and Exporting Markup .........................................................................384Available Formatting Options ...........................................................................................386Editing Features ................................................................................................................386Undo and Redo History ....................................................................................................388Programmatic Editing .......................................................................................................389
Clipboard ................................................................................................................389Events .....................................................................................................................393
Flow and Container Configuration ..................................................................................394A TextField Adapter Class ................................................................................................394
Fonts Revisited .............................................................................................................................394Embedding CFF Fonts ......................................................................................................395
Using Flash Professional ........................................................................................395Using the Embed Tag ............................................................................................ 396
Font Lookup .....................................................................................................................397Summary ......................................................................................................................................397
Chapter 19: Printing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 399Why Print from Flash? ................................................................................................................399Controlling Printer Output from Flash .......................................................................................400
xxiv
www.it-ebooks.info
http://www.it-ebooks.info/
-
Contents
Introducing the PrintJob Class .........................................................................................400Starting a Print Request ....................................................................................................400Determining the Print Target and Its Formatting Options .............................................401
Printing Targets as Vectors ....................................................................................402Printing Targets as Bitmaps ...................................................................................402Scaling Screen Dimensions to Print Dimensions ..................................................403
Potential Issues with the Flash-Printed Output ...............................................................403Adding Print Functionality to Applications ................................................................................403Summary ......................................................................................................................................406
Part IV: Event-Driven Programming 407
Chapter 20: Events and the Event Flow . . . . . . . . . . . . . . . . . . . . . . . . 409Introducing Events ......................................................................................................................409
Saturday Morning Events .................................................................................................410Event Terminology ............................................................................................................411
Event .......................................................................................................................411Type ........................................................................................................................411Target ......................................................................................................................412Dispatcher ...............................................................................................................412Listener ...................................................................................................................412Handler ...................................................................................................................412Flow ........................................................................................................................412Phase .......................................................................................................................412
The EventDispatcher Class ..........................................................................................................413Using EventDispatcher ......................................................................................................413Using EventDispatcher by Composition ..........................................................................417
Working with Event Objects .......................................................................................................418Adding and Removing Event Listeners .......................................................................................419The Event Flow ...........................................................................................................................421
The Phases of Event Flow ................................................................................................422Capture Phase .........................................................................................................423Target Phase ...........................................................................................................423Bubble Phase ..........................................................................................................423
Event Flow in Action ........................................................................................................424Preventing Default Behaviors ......................................................................................................426Summary ......................................................................................................................................427
Chapter 21: Interactivity with the Mouse and Keyboard . . . . . . . . . . . . 429Mouse and Keyboard Event Handling ........................................................................................429
Finding the Target ............................................................................................................430Bubbling and Nested Clips ...............................................................................................431Listening for All Events ....................................................................................................432
Mouse Interactions ......................................................................................................................432Clicking .............................................................................................................................433Button Mode and the Hand Cursor .................................................................................434
xxv
www.it-ebooks.info
http://www.it-ebooks.info/
-
Contents
Complex Clicking .............................................................................................................435Keyboard Modifiers ................................................................................................436Double-Clicking .....................................................................................................436
Rollovers ..................................................