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 engi
Trang 610475 Crosspoint Boulevard
Indianapolis, IN 46256
www.wiley.com
Copyright©2010 by Wiley Publishing, Inc., Indianapolis, Indiana
Published simultaneously in Canada
107 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 should
be 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 extended
by 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 able in electronic books
avail-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 ActionScript
is 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
Trang 7an independent development and design shop in Brooklyn, NY Roger is an author of the first edition
of 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 he’s 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 sitehttp://partlyhuman.com/, but you can use it to get in touchwith him
Trang 11My 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 look
at this book and see all of my ideas in print, I know it’s 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 he’s the personwho’s there from the first day of writing through the last, exhausted round of edits But I think BrianMacDonald is exceptional I’ve 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 you’rewriting a programming book, bribe whoever you need to hire Brian
I can’t 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 master’s 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 scrutinizing
it, 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 won’t 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 Corey’s help was invaluable.Special thanks also go to Whitney Gardner, who made two sublime illustrations for this book when Iwas at my wit’s 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
Trang 13Chapter 1: Introducing ActionScript 3.0 3
Chapter 2: ActionScript 3.0 Language Basics 15
Chapter 3: Functions and Methods 39
Chapter 4: Object Oriented Programming 51
Chapter 5: Validating Your Program 103
Part II: Core ActionScript 3.0 Data Types 111
Chapter 6: Text, Strings, and Characters 113
Chapter 7: Numbers, Math, and Dates 125
Chapter 8: Arrays 145
Chapter 9: Vectors 167
Chapter 10: Objects and Dictionaries 181
Chapter 11: XML and E4X 191
Chapter 12: Regular Expressions 225
Chapter 13: Binary Data and ByteArrays 257
Part III: The Display List 271
Chapter 14: Visual Programming with the Display List 273
Chapter 15: Working in Three Dimensions 301
Chapter 16: Working with DisplayObjects in Flash Professional 321
Chapter 17: Text, Styles, and Fonts 329
Chapter 18: Advanced Text Layout 367
Chapter 19: Printing 399
Part IV: Event-Driven Programming 407
Chapter 20: Events and the Event Flow 409
Chapter 21: Interactivity with the Mouse and Keyboard 429
Chapter 22: Timers and Time-Driven Programming 461
Chapter 23: Multitouch and Accelerometer Input 473
Part V: Error Handling 489
Chapter 24: Errors and Exceptions 491
Chapter 25: Using the AVM2 Debugger 505
Chapter 26: Making Your Application Fault-Tolerant 523
Part VI: External Data 531
Chapter 27: Networking Basics and Flash Player Security 533
Chapter 28: Communicating with Remote Services 561
Trang 14Chapter 29: Storing and Sending Data with SharedObject 571
Chapter 30: File Access 589
Part VII: Sound and Video 603
Chapter 31: Playing and Generating Sound 605
Chapter 32: Playing Video 625
Chapter 33: Capturing Sound and Video 643
Part VIII: Graphics Programming and Animation 655
Chapter 34: Geometric and Color Transformations 657
Chapter 35: Programming Vector Graphics 687
Chapter 36: Programming Bitmap Graphics 733
Chapter 37: Applying Filters 769
Chapter 38: Writing Shaders with Pixel Bender 803
Chapter 39: Scripting Animation 835
Chapter 40: Advanced 3D 855
Part IX: Flash in Context 877
Chapter 41: Globalization, Accessibility, and Color Correction 879
Chapter 42: Deploying Flash on the Web 897
Chapter 43: Interfacing with JavaScript 905
Chapter 44: Local Connections between Flash Applications 911
Index 921
xii
Trang 15Chapter 1: Introducing ActionScript 3.0 3
What Is ActionScript 3.0? 3
Exploring the Flash Platform 4
A Programmer’s Perspective 5
Language 5
API 6
Libraries 7
Compilers, Tools, and IDEs 7
SWFs 8
Flex 9
In Short 9
A User’s Perspective 9
Runtimes 9
Platforms and Platform Independence 10
The Flash Player Zoo 10
In Short 11
From ActionScript 2.0 to ActionScript 3.0 11
Display List 11
Runtime Errors 12
Runtime Data Types 12
Method Closures 12
Intrinsic Event Model 12
Regular Expressions 12
E4X 12
Summary 13
Chapter 2: ActionScript 3.0 Language Basics 15
The Bare Essentials 15
Using Variables 17
Anatomy of a Variable Declaration 17
Constants in This Changing World 18
Taking It Literally 18
Trang 16Commenting Your Code 20
Types of Comments 20
Single-Line Comment 20
Block Comments 20
XML Comments 20
Javadoc Comments 21
When to Use Comments 21
Self-Commenting Code 21
Introducing Scope 22
Introducing the Data Types 23
Declaring Types 23
Using Untyped Variables 23
Connecting You to an Operator 23
Unary vs Binary Operators 24
Order of Operations 24
Some Commonly Used Operators 24
Assignment (=) 24
Arithmetic (+, –, *, /) 24
Modulo (%) 25
Increment (++) and Decrement (– –) 25
Compound Assignment Operators (+ =, − =, *=, /=, and % =) 25
Comma Operator (,) 26
Making Logical Choices with Conditionals 26
if Statements 26
Equality (= =) 27
Testing Other Comparisons 27
Greater Than (>) and Less Than (<) 28
Not Equal to (!=) 28
And (&&) and Or (||) Operators 28
Checking for Null Values 29
if else 30
switch 30
The Conditional Operator 31
Repeating Actions Using Loops 33
Using for Loops 33
Using for in and for each in 34
for in 34
for each in 34
Using while and do while 35
while 35
do while 36
Battle of the Loop Structures: for vs while 37
Avoiding Infinite Loops 37
Using break and continue 37
continue 37
break 37
Summary 38
xiv
Trang 17Chapter 3: Functions and Methods 39
Calling Functions 39
Creating Custom Functions 40
Defining a Function 40
Passing Arguments to Your Function 41
Passing by Reference or by Value 41
Setting Default Values 43
Using the Rest Parameter ( ) 43
Returning Results 44
Returning a Value Using a return Statement 45
Defining a Return Type for Your Function 46
Returning Void 46
Anonymous Functions 46
Functions as Objects 47
Recursive Functions 48
Summary 50
Chapter 4: Object Oriented Programming 51
Understanding Classes 51
Classes Can Model the Real World 51
Classes Contain Data and Operations 52
Classes Separate Responsibilities 52
Classes Are Types 52
Classes Contain Your Program 53
Object Oriented Terminology 53
Object 53
Class 54
Instance 54
Type 54
Encapsulation: Classes Are Like, So Selfish 55
The Black Box Principle 55
Encapsulation and Polymorphism 56
Packages: Classes, Functions, and Packing Peanuts 56
Class Uniqueness and Namespaces 56
Hierarchy 57
Controlling Visibility 58
Code Allowed in Packages 58
Using Code from Packages 59
Using Inheritance 61
Structuring Code with Inheritance 64
Inheritance, Types, Polymorphism, and You 66
Inheritance vs Composition 67
Preventing Inheritance 69
Access Control Attributes 70
Public and Private 71
Protected 73
Internal 74
Custom Access Control with Namespaces 75
Methods and Constructors 77
Trang 18Properties 78
Accessors 79
Avoid Side Effects 81
Self-Referential Code 82
Using Static Methods and Properties 83
Static Variables 84
Static Constants 85
Enumerations 87
Static Methods 87
Overriding Behavior 89
Accessing the Superclass 90
Designing Interfaces 92
Manipulating Types 96
Type Compatibility and Coercion 97
Explicit Type Conversion 98
Determining Types 100
Creating Dynamic Classes 100
Summary 101
Chapter 5: Validating Your Program 103
Introducing Errors 103
Compile-Time Errors vs Runtime Errors 104
Compile-Time Errors 104
Runtime Errors 104
Warnings 104
Getting Feedback from Flash Professional and Flash Builder 104
Debugging in Flash Professional 104
Debugging in Flash Builder 106
Fixing Errors 108
Summary 110
Part II: Core ActionScript 3.0 Data Types 111 Chapter 6: Text, Strings, and Characters 113
Working with String Literals 113
Using Escaped Characters 114
Converting to and from Strings 115
Using toString() 115
Casting and Converting to Strings 116
Converting Strings into Other Types 116
Converting Strings to Numbers 116
Converting Strings to Arrays 117
Combining Strings 118
Converting the Case of a String 118
Using the Individual Characters in a String 119
Getting the Number of Characters in a String 119
Getting a Particular Character 120
Converting a Character to a Character Code 120
Searching within a String 120
xvi
Trang 19Searching by Substring 120
Searching with Regular Expressions 121
String Dissection 122
String Encoding and International Text 123
Summary 123
Chapter 7: Numbers, Math, and Dates 125
Understanding Numeric Types 125
Sets of Numbers 125
Representing Numbers 126
Digital Representations of Numbers 126
Unsigned Integers 126
Signed Integers 127
Floating-Point Numbers 127
Using Numbers in ActionScript 128
Number 128
int 129
uint 129
Literals 130
Edge Cases 130
Not a Number 131
Infinity 131
Minimum and Maximum Values 131
Manipulating Numbers 132
Numeric Conversions 132
String Conversions 132
Performing Arithmetic 133
Performing Trigonometric Calculations 135
Generating Randomness 137
Manipulating Dates and Times 138
Creating a Date 138
Epoch Time 139
Time zones 140
Accessing and Modifying a Date 141
Date Arithmetic 142
Execution Time 142
Formatting a Date 143
Summary 144
Chapter 8: Arrays 145
Array Basics 145
Using the Array Constructor 145
Creating an Array by Using an Array Literal 147
Referencing Values in an Array 147
Finding the Number of Items in an Array 148
Converting Arrays to Strings 148
Adding and Removing Items from an Array 149
Appending Values to the End of Your Array with concat() 149
Applying Stack Operations push() and pop() 150
Applying Queue Operations shift() and unshift() 151
Trang 20Slicing, Splicing, and Dicing 152
Inserting and Removing Values with splice() 152
Working with a Subset of your Array with slice() 152
Iterating through the Items in an Array 153
Using a for Loop 153
Using for each in 154
Using the forEach() Method 154
Searching for Elements 155
Reordering Your Array 155
Using Sorting Functions 156
Flipping the Order of Your Array Using Reverse() 159
Applying Actions to All Elements of an Array 159
Conditional Processing with every(), some(), and filter() 159
Getting Results with the map() Method 162
Alternatives to Arrays 162
Associative Arrays 162
Multidimensional Arrays 163
Amazing Properties of Arrays 165
Summary 165
Chapter 9: Vectors 167
Vector Basics 167
Why Do We Need Another Datatype? 168
Array: More Functionality Than You Require 169
Vectors: Arrays with Benefits 170
Fixed-Size Vectors 172
Generics and Parameterized Types 173
Vector as a Generic 173
No Generics for You 174
Generic Methods of Vector 176
Creating and Converting Vectors 178
Vector literals 179
Converting Types of Vectors 179
Converting a Vector into an Array 180
Summary 180
Chapter 10: Objects and Dictionaries 181
Working with Objects 181
Dynamic Classes 181
Creating Objects 182
Accessing Object Properties 182
toString() 183
Using Objects and Dictionaries as Associative Arrays 183
Comparing Arrays, Objects, and Dictionaries 184
Testing for Existence 186
Removing Properties 187
Iterating 188
xviii
Trang 21Using Objects for Named Arguments 188
Using Objects as Nested Data 189
XML as Objects 189
JSON 190
Summary 190
Chapter 11: XML and E4X 191
Getting Started with XML in ActionScript 191
XML References 191
E4X References 192
XML Literals 192
A Brief Introduction to E4X Operators and Syntax 194
Legacy XML Handling 195
Querying XML 196
The Child Axis 196
The Wildcard Operator 197
Indexed Elements 197
The Attribute Axis 198
The Text Axis 199
The Descendant Axis 200
The Parent Axis 201
Custom Filter Axes 201
Quick Reference 203
Modifying XML 203
Inserting Nodes 203
Inserting with E4X Operators 204
Inserting with E4X Methods 206
Removing Nodes and Attributes 207
Duplicating XML 208
Replacing Nodes 209
Converting to and from Strings 209
Converting Strings to XML 210
Converting XML to Strings 210
Printing Pretty 211
Setting the Number of Spaces per Indentation 211
Normalizing Text Nodes 212
Loading XML Data from External Sources 212
Gathering Meta-Information about XML Nodes 213
Finding Node Types 213
Determining the Type of Content in a Node 214
Using Namespaces 215
Creating XML Namespaces in ActionScript 216
Using the Namespace Class 216
Using the Namespace Keyword 217
Making Namespaces Available 217
Trang 22Querying Namespaced XML Nodes 217Opening Namespaces 218Using the Scope Resolution Operator 219Setting the Default XML Namespace 220Querying XML for Namespaces 221Additional Namespace Operations 222Setting XML Options 223Summary 223
Chapter 12: Regular Expressions 225
Introducing Regular Expressions 225Writing a Regular Expression 226Applying Regular Expressions 226String Methods and RegExp Methods 226Testing 227Locating 228Identifying 229Extracting 231Replacing 233Splitting 235Constructing Expressions 235Normal Characters 236Dot Character 236Escaped Characters 236Metacharacters and Metasequences Demystified 237Character Classes 238Quantifiers 239Anchors and Boundaries 240Alternation 242Groups 242Regular Expression Flags 243Global 243Ignore Case 244Multiline 244Dotall 245Extended 246Constructing Advanced Expressions 246Greedy and Lazy Matching 247Backreferences 248Lookahead and Noncapturing Groups 249Noncapturing Groups 249Positive Lookahead Groups 249Negative Lookahead Groups 250Named Groups 250International Concerns 252Using the RegExp Class 252Building Dynamic Expressions with String Operations 252RegExp Public Properties 253Summary 253
xx
Trang 23Chapter 13: Binary Data and ByteArrays 257
Binary Concepts 257Bit Math and Operators 260Basic Arithmetic 260Bit Shifting 260Bitwise Logic 262Binary Types in ActionScript 263Using ByteArray 265Creating a ByteArray 265Writing Data 265Reading Data 265Compressing and Decompressing 266Common Uses of ByteArrays 266Loading Images 266Copying Objects 267Summary 268
Chapter 14: Visual Programming with the Display List 273
Introducing Display Lists and Display Objects 273Structure of the Display List 274Coordinate Spaces 274Manipulating the Display List 276Creating 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 279Display Object Classes 280DisplayObject 280InteractiveObject 283DisplayObjectContainer 283Shape 284Bitmap 284Video 284AVM1Movie 284SimpleButton 284TextField 285Sprite 285MovieClip 285Loader 286Stage 286Resizing 286Changing SWF Properties 286Going Full-Screen 287
Trang 24Device Orientation 288Event Source and Focus Manager 289Color Correction 289Geometry Classes 289Point 289Rectangle 290Putting the Display List to Use 292Drag-and-Drop, Hit Testing 292Nesting and Cumulative Transformations 294Full-Screen and Stage Resizing 295Rendering 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 299Summary 299
Chapter 15: Working in Three Dimensions 301
Introducing 3D in ActionScript 3.0 301The 3D Coordinate System 3033D in Flash Professional 304Limitations of 3D Display Objects 304Display Objects are Flat 305
A Viewport Isn’t a Camera 305Depths Are Managed by the DisplayObjectContainer 305Other Missing Stuff 305DisplayObject Revisited 306Geometry Revisited 309Mouse and Point Translation in 3D 311Translating Points in Code 312Modifying the Projection 314Software 3D Libraries 318Summary 319
Chapter 16: Working with DisplayObjects in Flash Professional 321
The Stage, Symbols, and the Library 321Creating Symbols 322Named Instances 323Nested Instances 324Associating Symbols to Classes 324Writing an Associated Class 326Nongraphic Symbol Types 326Exporting and Using Assets 327Using Assets from a SWC 327Using Assets from a SWF 327Summary 328
xxii
Trang 25Chapter 17: Text, Styles, and Fonts 329
Introducing TextFields 329Creating a New TextField 330Adding and Replacing Text 330Setting a TextField’s Size 330Setting a TextField’s Scaling and Rotation 332Wrapping Text 332Preventing User Selection 333Displaying Multilingual Text and Symbols 334Text with HTML and CSS 334HTML Support in TextField 334
Adding Images or SWF Files to a TextField with <img> 335
Supported CSS Properties 336The StyleSheet Object and CSS Parsing 337Background and Border Treatments 339Styling Text with TextFormats 339align 341blockIndent 341bold 341bullet 341color 341font 342indent 342italic 342leading 342letterSpacing 342leftMargin 342rightMargin 343size 343tabStops 343target 343underline 343url 344Input TextFields 344The Three Kinds of Text Fields 344Making a TextField an Input Field 345Restricting User Input 345Tab-Accessible Input Text Fields 347Password Text Fields 347Interaction with TextField Events 347focusIn and focusOut Events 347Text Input Events 349Link Events 352Scroll Events 354Interactive Typography 354Text by Lines and Paragraphs 354Finding Text by Location 356
Trang 26Locating and Measuring Text 356Scrolling Text 358Fonts 360Device Fonts and Embedded Fonts 360Managing Active Fonts and the Font Object 362Embedding Fonts 362Flash Builder, Flex Builder, Flex SDK, mxmlc 362Flash Professional 363Loading Fonts Dynamically 364Using Embedded Fonts 364Anti-aliasing 365Fitting Edges to a Grid 366Sharpness and Thickness 366Summary 366
Chapter 18: Advanced Text Layout 367
Understanding Advanced Text Controls 367Advanced Text Controls in Development Tools 369Why There Are Two Engines 369Where to Go from Here 369The Flash Text Engine 370The Text Layout Framework 372Storing Content and Formatting with Models 373Laying Out Text with Controllers 375Simple Composition with TextLine Factories 375Linked Container Composition with ContainerControllers and
FlowComposers 378Text Layout Markup 381Setting Up TLF Markup 382TLF Tags 383Importing and Exporting Markup 384Available Formatting Options 386Editing Features 386Undo and Redo History 388Programmatic Editing 389Clipboard 389Events 393Flow and Container Configuration 394
A TextField Adapter Class 394Fonts Revisited 394Embedding CFF Fonts 395Using Flash Professional 395Using the Embed Tag 396Font Lookup 397Summary 397
Chapter 19: Printing 399
Why Print from Flash? 399Controlling Printer Output from Flash 400
xxiv
Trang 27Introducing the PrintJob Class 400Starting a Print Request 400Determining the Print Target and Its Formatting Options 401Printing Targets as Vectors 402Printing Targets as Bitmaps 402Scaling Screen Dimensions to Print Dimensions 403Potential Issues with the Flash-Printed Output 403Adding Print Functionality to Applications 403Summary 406
Chapter 20: Events and the Event Flow 409
Introducing Events 409Saturday Morning Events 410Event Terminology 411Event 411Type 411Target 412Dispatcher 412Listener 412Handler 412Flow 412Phase 412The EventDispatcher Class 413Using EventDispatcher 413Using EventDispatcher by Composition 417Working with Event Objects 418Adding and Removing Event Listeners 419The Event Flow 421The Phases of Event Flow 422Capture Phase 423Target Phase 423Bubble Phase 423Event Flow in Action 424Preventing Default Behaviors 426Summary 427
Chapter 21: Interactivity with the Mouse and Keyboard 429
Mouse and Keyboard Event Handling 429Finding the Target 430Bubbling and Nested Clips 431Listening for All Events 432Mouse Interactions 432Clicking 433Button Mode and the Hand Cursor 434
Trang 28Complex Clicking 435Keyboard Modifiers 436Double-Clicking 436Rollovers 437Dragging 440Position Tracking and Cursors 442Blocking all Mouse Input 445Mouse Wheel 447Keyboard Interactions 447Interpreting Keypresses 447Modifier Keys 450Related Events 450IMEs 450Focus 451Finding or Setting the Current Focus 451Focus Events 453Tabbing 454Focus Rectangle 455Context Menus 455Creating and Setting a Context Menu 455Customizing Default Items 456Adding Custom Items 456Summary 459
Chapter 22: Timers and Time-Driven Programming 461
Timer Basics 461Creating a Timer 462Listening for Timer Events 462Starting, Stopping, and Resetting the Timer 463Handling Timer Events 464Delaying the Execution of a Function 466Creating a World Clock 467Enterframe Events 469Other Time-Related Functions 469getTimer() 469setTimeout() 470setInterval() 470clearInterval() 470Aside: Threads 470Summary 471
Chapter 23: Multitouch and Accelerometer Input 473
Planning for Your Audience 473Using Multitouch 474Touch Mode 476Event Object Properties Shared by MouseEvent 477Event Object Properties Unique to TouchEvent 477Putting It Together 478Gesture Mode 480Special Properties of PressAndTapGestureEvent 480
xxvi
Trang 29Special Properties of TransformGestureEvent 482Putting It Together 482Touch-Related Methods 484Using the Accelerometer 485Other Sensors 486Summary 486
Chapter 24: Errors and Exceptions 491
Comparing Ways to Fail 491Understanding Exceptions 492Throwing Exceptions 492Catching Exceptions with Try and Catch 493The Exception Flow 494Uncaught Exceptions 497The Finally Clause 497Rethrowing Exceptions 498Errors Generated by Flash Player 499Custom Exceptions 501Handling Asynchronous Errors 502Capturing Unhandled Events 503Summary 504
Chapter 25: Using the AVM2 Debugger 505
Introducing Debugging 505Launching the Debugger 506Starting and Stopping the Flash Professional Debugger 506Starting and Stopping the Flash Builder Debugger 508Debuggers Compared 509Taking Control of Execution 510Stopping at an Uncaught Exception 510Stopping at a Breakpoint 511Stopping on Demand 513Pulling Back the Curtain 513Interpreting the Variables Panel 513Flash Builder Variables Panel and Watches 515Navigating through Code 515Continue 515The Call Stack 516Step Into 517Step Over 518Step Out 518Debugging a Simple Example 518Using the Debugger Effectively 520Summary 521
Chapter 26: Making Your Application Fault-Tolerant 523
Developing a Strategy 523Determining What Errors to Handle 524
Trang 30Categorizing Failures 525Logging Errors 526Messaging the User 527Degrading Styles: An Example 528Summary 530
Chapter 27: Networking Basics and Flash Player Security 533
HTTP in Brief 533Introducing URLRequest 536Navigating to a Web Page 536Loader 537Graphics File Formats 538Accessing Information about the Loading Process 538LoaderInfo versus ContentLoaderInfo 539Loading Events 540The LoaderInfo Class 540Getting Loaded Content 543Loading External SWFs 545Instantiating Classes from External SWFs 545Interacting with Loaded SWFs 548Loading AVM1 SWFs 548Using Loader to Interpret Files in Memory 549URLLoader 549Loading a File 550Loading and Canceling 550Tracking Load Progress 550Loading Different Formats 551Loading XML 551Loading CSS 552Loading a Binary File 553Loading URL-Encoded Variables 553Sending Variables with URLRequest 555Request and Response with URLLoader 556Request Only with sendToUrl() 557Understanding Flash Player Security 557Summary 559
Chapter 28: Communicating with Remote Services 561
Web Services Using HTTP 562REST 563SOAP 563XML- RPC 565
xxviii
Trang 31Socket Services 565XML Socket Services 567Flash Remoting 568NetConnection 569Responder 570Summary 570
Chapter 29: Storing and Sending Data with SharedObject 571
Comparing Approaches to Persistent Storage 571Storing Information in a Local Shared Object 571Storing Information in Local Files 572Storing Information on a Server 572Storing Information in the Browser 572Identifying Useful Situations for Shared Objects 573Shared Objects and Remoting 574Using SharedObjects 574Retrieving a SharedObject 574Reading from and Writing to a SharedObject 575Deleting Information from a SharedObject 576Saving Information 576Sharing Information between SWFs 576Requiring a Secure Connection 578Sharing with ActionScript 1.0 and 2.0 SWFs 579Working with Size Constraints 579User Settings 579User Requests 580Asking for Space before It’s Too Late 581Asking for Space Up front 581Using flush() 582Viewing Used Space 583Storing Custom Classes 583Storing Custom Classes without Modification 583Creating Self-Serializing Classes 585Summary 587
Chapter 30: File Access 589
Abilities of the File API 589Introducing FileReference 589Choosing a File 590Determining When a File Is Selected 591Retrieving File Properties 592Uploading a File 593Adding Upload Handling to a Server 593Downloading a File to Disk 596Loading a File into Memory 598Saving Data to Disk 599Summary 602
Trang 32Part VII: Sound and Video 603
Chapter 31: Playing and Generating Sound 605
An Overview of the Sound System 605Prepping and Playing Sound Objects 607Loading a Sound from an External File or URL 607Buffering a Streaming Sound 608Embedding Sounds in a SWF 608Embedding Sound with Flash Professional 609Embedding Sound with Flash Builder 610Accessing Embedded Sounds 611Controlling Sound Playback 611Playing and Stopping 611Seeking and Looping 613Fast-Forwarding, Rewinding, Pausing, and Restarting
a Sound 613Applying Sound Transformations 615Working with a Sound’s Metadata 616Checking Load Progress 616Getting a Song’s ID3 Data 616Sampling Audio 617Extracting Audio 621Synthesizing Audio 621Detecting Audio Capabilities 623Summary 623
Chapter 32: Playing Video 625
Video and the Flash Platform 625Video Sources 625Embedded 626Video Files and Streams 626Webcam 626Codecs and Container Formats 626Metainformation 628Metadata 628Cue Points 628Subtitles and Closed Captioning 628Delivery Methods 628Local, Progressive Download 629Streaming 629Delivery Networks 630Encoding 631Adobe Media Encoder 631Exporting from Applications 632Video Encoding Services 632Playback 632
xxx
Trang 33Video Acceleration 632Video Players 632Open Source Media Framework 633Implementing a Video Player 634Video 634NetConnection 634NetStream 635Putting It All Together 638Summary 641
Chapter 33: Capturing Sound and Video 643
Video Input Using a Camera 643Retrieving a Camera Object 643Viewing Video from a Camera 644Tweaking Camera Settings 646Detecting Camera Activity 647Capturing and Analyzing Camera Data 647Sound Input Using a Microphone 648Retrieving a Microphone Object 648Playing Back Microphone Input 648Tweaking Microphone Settings 648Sound Recording Settings 649Sound Compression Settings 650Detecting Microphone Activity 651Overall Activity 651Voice Activity 652Capturing and Analyzing Microphone Data 652Flash Media Servers 653Summary 654
Chapter 34: Geometric and Color Transformations 657
DisplayObject and the Transform Object 6572D Affine Transformations 658Matrices and Coordinates 659Kinds of Affine Transform and Their Matrices 661The Identity Matrix 661Translation 661Scale 661Rotation 661Skew 662The Matrix Class 663Transform Methods 663Utility Methods 664
Trang 34Order of Application 664Applying Transformation Matrices 665Color Transforms 666Color Fills 666Color Transformation Math 667Resetting and Combining Color Transforms 668Applying Color Transformations 6683D Transformations 670Basic 3D Concepts Review 670Coordinate System 670Points 671Vectors 672Matrices 673Orientation 6743D Affine Transformations 674Projection Transformations 6753D Transformations in ActionScript 677Vector3D 678Matrix3D 681Summary 686
Chapter 35: Programming Vector Graphics 687
Overview 687Drawing Basics 689Moving the Pen 689Straight Line Segments 690Curved Line Segments 694Filling a Path 698Clearing Graphics 700Setting Drawing Styles 700Solid Colors 700Gradients 706Bitmaps 710Shaders 712Drawing Primitives 714Rectangles and Squares 714Circles and Ellipses 715Rounded Rectangles 715Example: A Drawing Application 716Batched Drawing 721Drawing a Path 721Finally, the Method 723Winding 723Example: Drawing a Glyph 724Storing a Path in a Command 726Batching Generic Drawing Commands 728Copying and Pasting Drawings 7303D Drawing 731Summary 731
xxxii
Trang 35Chapter 36: Programming Bitmap Graphics 733
Bitmaps and Their Applications 733Creating and Displaying Bitmaps 735Creating Empty BitmapData Instances 735Creating Instances of Embedded Assets 736Displaying Bitmaps 736Displaying Bitmaps 736Bitmap Quality 737Disposing Bitmap Data 737Capturing and Copying Bitmaps 737Copying from Display Objects 737Copying from BitmapData Objects 740Drawing from Another Bitmap 740Cloning a BitmapData Object 741Copying Pixels 742Copying Channels 743Merging BitmapData Images 745Pixel-Level Access 746Accessing Single Pixels 747Accessing Bitmap Data in Memory 748Using ByteArray 749Using Vector 750Working with Colors 751Replacing a Color with a Flood Fill 751Color Transforms 752Retrieving a Histogram 753Replacing Colors with Threshold 755Remapping Colors with Palette Mapping 757Detecting Areas of a Solid Color 759Bitmap Effects 761Applying Filters 761Scrolling a Bitmap 762Using Pixel Dissolves 762Making Noise 762Random Noise 762Perlin Noise 764Summary 766
Chapter 37: Applying Filters 769
Introducing Filters 769Applying Filters to Display Objects 770Multiple Filters 771Blurs 771Drop Shadows 773Bevels 775Gradient Bevels 777Glows 779Gradient Glows 783Color Effects 784
Trang 36Brightness 785Tint 786Negative 788Contrast 789Convert to Grayscale 790Saturation 792Convolution Filters 793Displacement Maps 797Shaders 801Summary 802
Chapter 38: Writing Shaders with Pixel Bender 803
Introducing Pixel Bender 803The Case for Pixel Shaders 804Thinking Like a Pixel Shader 805Integrating Pixel Bender and Flash
Player 807Pixel Bender Kernel Language 808Syntax 808Structure of a Kernel 809Required Metadata 810Member Declarations 810Basic Control Structures 811Types 811Vector Types 812Matrix Types 813Image Types 814Stuff You Don’t Get 814Functions 814Interfacing with Pixel Bender Kernels 817Loading the Bytecode 817Running a Kernel in ActionScript 818Manipulating a Kernel 819
A Basic Shader in ActionScript 820
An Effect Shader in ActionScript 821Bending Other Data 826Preparing Data for Pixel Bender 826BitmapData 827Vector 827ByteArray 828Accessing Data in the Kernel 828Executing and Monitoring ShaderJobs 828The Double-Shader Experiment 829Summary 834
Chapter 39: Scripting Animation 835
Understanding Flash Player and Animation 835Frame rate 835Flash Player operation 836
xxxiv
Trang 37Animating with Code 837Animating by Time 837Animating by Frames 839Animation and Speed 839Animating Using Flash Professional 841Review: Tweens, Keyframes, and Easing 842Introducing Motion XML 842The Motion Object 844The Source Object 845The Keyframe Object 846The Color Object 847Filter Objects 848The ITween Objects 848Using the Flash Motion Package 850Animating Using Flex 852Choosing a Third-Party Animation Toolkit 852Summary 853
Chapter 40: Advanced 3D 855
Game Plan 856Projecting Batches of Points 856Triangle Strips 861Backface Culling 864Texture Mapping 865Z-Sorting, Shading, and Further Topics 870Polygon Z-Sorting 871Shading and Lighting Introduced 873Normal Maps 874Shading with a Normal Map 874Summary 875
Chapter 41: Globalization, Accessibility, and Color Correction 879
Globalization and Localization 879Identifying Locale 880Using the Default that the Operating System Provides 881Based on Location 881Based on the Browser 881Based on the Browser’s Configuration 882Just Ask 883
An Example 883Getting the Closest Match 885Formatting Numbers 885Formatting Dates 886Formatting Currency 888
Trang 38Localized String Comparison 889Localized Capitalization 891Error Handling 892Accessibility 892Color Correction 893Summary 895
Chapter 42: Deploying Flash on the Web 897
Embedding Flash in a Page 897Embedding Flash Using SWFObject 898Enabling Flash Player Options 900Transparent Flash 900Hardware Acceleration 901Full-Screen Flash 901Passing Variables to a SWF 902Automatically Upgrading Flash Player 903Summary 904
Chapter 43: Interfacing with JavaScript 905
Using ExternalInterface 905Calling JavaScript Functions from Flash 906Calling ActionScript Functions from JavaScript 907JavaScript Interaction and Flash Player Security 908Making a Hybrid Application with ExternalInterface 908Summary 910
Chapter 44: Local Connections between Flash Applications 911
Local Connections and Their Uses 911Implementing a Local Connection 912The Sending Application 912Sending Methods to a Receiving Application 912Listening for the Status of Local Method Invocations 913The Receiving Application 914Assigning a Delegate 914Listening to a Named Channel 915Closing the Connection 915Local Connections and the Security Policy 915Specifying the Domain in the Sender 916Removing the Domain from the Channel Name 916Allowing Cross-Domain Local Connections from the Receiving Application 916Example: Following the Mouse 917Summary 919
Index 921
xxxvi
Trang 40flash.events
6String
12RegExp
11XML
11XMLList
7Number
7int
7uint
7Date
7Math
8Array
2Boolean
3Function
4Class
9Vector
24Error
DisplayObject
InteractiveObject
DisplayObjectContainer
35Shape
35Graphics
36BitmapData
38Shader
38ShaderJob
38ShaderInput
38ShaderParameter
27LoaderInfo
14SimpleButton
14Sprite
14MovieClip
14
27AVM1Movie
36Bitmap
20Event
20ErrorEvent
20EventDispatcher
21MouseEvent
21FocusEvent
21ContextMenuEvent
27IOErrorEvent SecurityErrorEvent27 UncaughtErrorEvent24
22TimerEvent
14FullScreenEvent
23TouchEvent
23GestureEvent
23AccelerometerEvent
33ActivityEvent
27ProgressEvent
32NetStatusEvent21
KeyboardEvent