|
This book is in the style of the classic O'Reilly Cookbook series format, in which each recipe presents the problem, the solution, and a discussion of the solution. Each section pretty much stands alone, although you should understand chapter one on the basics before moving on. The Discussion sections of each recipe offer a good analysis of how the solution works and different design choices and their various ramifications. Thus you get the best of both worlds - quick and easy access to the answers you want and deeper insights into the nature of both the problem and the solution. This book is helping me develop my understanding of ActionScript concepts by applying them in real situations and I highly recommend it. All of the code examples in this book are based on ActionScript 3.0 and only compatible with products that support ActionScript 3.0. Flex 2.0 and Flash 9 allow you to author ActionScript 3.0 content. Flash Player 9 supports ActionScript 3.0. If you are using a product that does not support ActionScript 3.0, then the code in this book is not likely to work. The following is the table of contents: Chapter 1. ActionScript Basics Recipe 1.1. Creating an ActionScript Project Recipe 1.2. Customizing the Properties of an Application Recipe 1.3. Where to Place ActionScript Code Recipe 1.4. How to Trace a Message Recipe 1.5. Handling Events Recipe 1.6. Responding to Mouse and Key Events Recipe 1.7. Using Mathematical Operators Recipe 1.8. Checking Equality or Comparing Values Recipe 1.9. Performing Actions Conditionally Recipe 1.10. Performing Complex Conditional Testing Recipe 1.11. Repeating an Operation Many Times Recipe 1.12. Repeating a Task over Time Recipe 1.13. Creating Reusable Code Recipe 1.14. Generalizing a Method to Enhance Reusability Recipe 1.15. Exiting a Method Recipe 1.16. Obtaining the Result of a Method Recipe 1.17. Handling Errors Chapter 2. Custom Classes Classes are absolutely essential to ActionScript 3.0. This is truer in ActionScript 3.0 than in any earlier release of the language. ActionScript 1.0 was essentially a procedural language with modest object-oriented features. ActionScript 2.0 formalized the object-oriented features and took a big step in the direction of a truly object-oriented language. However, ActionScript 3.0 shifts the core focus of ActionScript so that the basic building block is that of the class. If you are using ActionScript 3.0 with Flex, and the introduction of the minor exception of code being placed within mx_Script tags, all ActionScript code must appear within a class. This chapter discusses the fundamentals of writing custom classes in ActionScript 3.0. Recipe 2.1. Creating a Custom Class Recipe 2.2. Determining Where to Save a Class Recipe 2.3. Creating Properties That Behave As Methods Recipe 2.4. Creating Static Methods and Properties Recipe 2.5. Creating Subclasses Recipe 2.6. Implementing Subclass Versions of Superclass Methods Recipe 2.7. Creating Constants Recipe 2.8. Dispatching Events Chapter 3. Runtime Environment Flash Player 9 offers a relatively large amount of information about and control over the runtime environment. The flash.system.Capabilities class has many static methods that return information about the player and the computer on which it is running, such as the operating system, language, audio, and video capabilities. There are other classes such as flash.display.Stage and flash.system.Security that allow you to control other elements of the Player such as the right-click menu under Windows (Control-click on the Macintosh) and the Settings dialog box. The flash.display.Stage class also controls the scaling and alignment of the movie within the Player. Recipe 3.1. Detecting the Player Version Recipe 3.2. Detecting the Operating System Recipe 3.3. Checking the Player Type Recipe 3.4. Checking the System Language Recipe 3.5. Detecting Display Settings Recipe 3.6. Scaling the Movie Recipe 3.7. Changing the Alignment Recipe 3.8. Hiding the Flash Player's Menu Items Recipe 3.9. Detecting the Device's Audio Capabilities Recipe 3.10. Detecting the Device's Video Capabilities Recipe 3.11. Prompting the User to Change Player Settings Recipe 3.12. Dealing with System Security Chapter 4. Numbers and Math ActionScript 3.0 has three basic numeric types: number, int, and uint. number is for any floating-point numbers, whereas int and uint are for integers (whole numbers). The distinction between int and uint is that int is the set of negative and non-negative integers, while uint is the set of non-negative integers (unsigned integers). This chapter gives you examples of working with all types of numbers in ActionScript using a variety of mathematical applications. Recipe 4.1. Representing Numbers in Different Bases Recipe 4.2. Converting Between Different Number Systems Recipe 4.3. Rounding Numbers Recipe 4.4. Inserting Leading or Trailing Zeros or Spaces Recipe 4.5. Formatting Numbers for Display Without a Mask Recipe 4.6. Formatting Currency Amounts Recipe 4.7. Generating a Random Number Recipe 4.8. Simulating a Coin Toss Recipe 4.9. Simulating Dice Recipe 4.10. Simulating Playing Cards Recipe 4.11. Generating a Unique Number Recipe 4.12. Converting Angle Measurements Recipe 4.13. Calculating the Distance Between Two Points Recipe 4.14. Determining Points Along a Circle Recipe 4.15. Converting Between Units of Measurement Chapter 5. Arrays In ActionScript, there are two kinds of arrays: integer-indexed and associative. Both array types group related data, but they use different means of accessing the data. The integer-indexed array uses integers as unique identifiers for each element in the array. Associative arrays use string keys to access each value. There's more about associative arrays in Recipe 5.15. This chapter will remind you of any good chapter in any book on arrays in any programming language. Recipe 5.1. Adding Elements to the Start or End of an Array Recipe 5.2. Looping Through an Array Recipe 5.3. Searching for Matching Elements in an Array Recipe 5.4. Removing Elements Recipe 5.5. Inserting Elements in the Middle of an Array Recipe 5.6. Converting a String to an Array Recipe 5.7. Converting an Array to a String Recipe 5.8. Creating a Separate Copy of an Array Recipe 5.9. Storing Complex or Multidimensional Data Recipe 5.10. Sorting or Reversing an Array Recipe 5.11. Implementing a Custom Sort Recipe 5.12. Randomizing the Elements of an Array Recipe 5.13. Getting the Minimum or Maximum Element Recipe 5.14. Comparing Arrays Recipe 5.15. Creating an Associative Array Recipe 5.16. Reading Elements of an Associative Array Chapter 6. Display List The rendering model for ActionScript 3.0 and Flash Player 9 is radically different than in previous versions. The new renderer is still hierarchical, but not as rigid, and aims to simplify and optimize the rendering process. The new rendering model centers on the display list concept and focuses on the classes available in the flash.display package. The display list is a hierarchy that contains all visible objects in the .swf movie. Any object not on the display list is not drawn by the renderer. Each .swf movie contains exactly one display list, which is comprised of three types of elements: the stage, display object container, and display objects. This chapter gives you practice working with this new model. Recipe 6.1. Adding an Item to the Display List Recipe 6.2. Removing an Item from the Display List Recipe 6.3. Moving Objects Forward and Backward Recipe 6.4. Creating Custom Visual Classes Recipe 6.5. Creating Simple Buttons Recipe 6.6. Loading External Images at Runtime Recipe 6.7. Loading and Interacting with External Movies Recipe 6.8. Creating Mouse Interactions Recipe 6.9. Dragging and Dropping Objects with the Mouse Chapter 7. Drawing and Masking With ActionScript, you can programmatically draw many display objects such as Shape, Sprite, Button, and MovieClip. Each of these classes has a graphics property that is an instance of the flash.display.Graphics class. The Graphics class defines an API for drawing content programmatically. Most recipes in this chapter discuss how to use the Graphics class API. Recipe 7.1. Setting a Line Style Recipe 7.2. Setting Gradient Line Styles Recipe 7.3. Drawing a Line Recipe 7.4. Drawing a Curve Recipe 7.5. Drawing an Arc Recipe 7.6. Drawing a Rectangle Recipe 7.7. Drawing a Circle Recipe 7.8. Drawing an Ellipse Recipe 7.9. Drawing a Triangle Recipe 7.10. Drawing Regular Polygons Recipe 7.11. Drawing a Star Recipe 7.12. Filling a Shape with a Solid or Translucent Color Recipe 7.13. Filling a Shape with a Gradient Recipe 7.14. Filling a Shape with a Bitmap Recipe 7.15. Scripting Masks Chapter 8. Bitmaps Before Flash 8, support for bitmap images was minimal. Although they could be loaded and displayed, there wasn't much you could do with them at runtime. The BitmapData class offers a nice set of tools for creating and manipulating bitmap graphics at runtime in Flash, and is featured in this chapter. Recipe 8.1. Creating a BitmapData Object Recipe 8.2. Adding a Bitmap to the Display List Recipe 8.3. Drawing a Display Object to a Bitmap Recipe 8.4. Loading an External Image into a Bitmap Recipe 8.5. Manipulating Pixels Recipe 8.6. Creating Rectangular Fills Recipe 8.7. Creating a Flood Fill Recipe 8.8. Copying Pixels Recipe 8.9. Copying Channels Recipe 8.10. Creating Noise Recipe 8.11. Creating Perlin Noise Recipe 8.12. Using Threshold Recipe 8.13. Applying a Filter to a Bitmap Recipe 8.14. Dissolving Between Two Bitmaps Recipe 8.15. Scrolling a Bitmap Chapter 9. Text With ActionScript 3.0, the new text field object isn't automatically added to the display list. That means that if you want to make the text field visible, you have to use the addChild( ) method. The addChild( ) method is defined for all container display objects, such as Sprite, and it adds the object specified as a parameter to the display list of the object from which it is called. These recipes are good examples of the new method. Recipe 9.1. Creating an Outline Around a Text Field Recipe 9.2. Creating a Background for a Text Field Recipe 9.3. Making a User Input Field Recipe 9.4. Making a Password Input Field Recipe 9.5. Filtering Text Input Recipe 9.6. Setting a Field's Maximum Length Recipe 9.7. Displaying Text Recipe 9.8. Displaying HTML-Formatted Text Recipe 9.9. Condensing Whitespace Recipe 9.10. Sizing Text Fields to Fit Contents Recipe 9.11. Scrolling Text Programmatically Recipe 9.12. Responding to Scroll Events Recipe 9.13. Formatting Text Recipe 9.14. Formatting User-Input Text Recipe 9.15. Formatting a Portion of Existing Text Recipe 9.16. Setting a Text Field's Font Recipe 9.17. Embedding Fonts Recipe 9.18. Creating Text that Can Be Rotated Recipe 9.19. Displaying Unicode Text Recipe 9.20. Assigning Focus to a Text Field Recipe 9.21. Selecting Text with ActionScript Recipe 9.22. Setting the Insertion Point in a Text Field Recipe 9.23. Responding When Text Is Selected or Deselected Recipe 9.24. Responding to User Text Entry Recipe 9.25. Adding a Hyperlink to Text Recipe 9.26. Calling ActionScript from Hyperlinks Recipe 9.27. Working with Advanced Text Layout Recipe 9.28. Applying Advanced Anti-Aliasing Recipe 9.29. Replacing Text Recipe 9.30. Retrieving a List of System Fonts Chapter 10. Filters and Transforms ActionScript lets you to apply several different transforms and filters to display objects (and bitmaps) to change their color, shape, rotation, size, and to apply special effects. Transforms are changes in color, shape, rotation, and size. The remainder of special effects di scussed in this chapter use filters. Filters are native to Flash Player; they allow you to apply effects ranging from blurs to embossing. Recipe 10.1. Applying Color Changes Recipe 10.2. Applying Color Tints Recipe 10.3. Resetting Color Recipe 10.4. Shearing Recipe 10.5. Applying Basic Filters Recipe 10.6. Applying Advanced Filter Effects (Emboss, etc.) Recipe 10.7. Embossing Recipe 10.8. Detecting Edges Recipe 10.9. Sharpening Recipe 10.10. Making a Digital Negative Recipe 10.11. Applying Grayscale Recipe 10.12. Changing Saturation Recipe 10.13. Changing Brightness Recipe 10.14. Changing Contrast Chapter 11. Programmatic Animation In the earliest versions of Flash, most animation was done by using tweens. An object was placed on a keyframe, another keyframe was made, and the object was changed in some way. Flash filled in the frames in between, hence, the term tween. Using ActionScript, you can create much more dynamic and interactive animation. Recipe 11.1. Moving an Object Recipe 11.2. Moving an Object in a Specific Direction Recipe 11.3. Easing Recipe 11.4. Acceleration Recipe 11.5. Springs Recipe 11.6. Using Trigonometry Recipe 11.7. Applying Animation Techniques to Other Properties Chapter 12. Strings Strings are the fundamental textual element of the ActionScript language. A string is a series of zero or more characters enclosed in single or double quotes. Unlike some other languages, ActionScript does not differentiate between single characters and strings. Both characters and strings are grouped into the String datatype. This chapter gives you a good basic understanding of how to handle this datatype in programs. Recipe 12.1. Joining Strings Recipe 12.2. Using Quotes and Apostrophes in Strings Recipe 12.3. Inserting Special Whitespace Characters Recipe 12.4. Searching for a Substring Recipe 12.5. Extracting a Substring Recipe 12.6. Parsing a String into Words Recipe 12.7. Removing and Replacing Characters and Words Recipe 12.8. Retrieving One Character at a Time Recipe 12.9. Converting Case Recipe 12.10. Trimming Whitespace Recipe 12.11. Reversing a String by Word or by Character Recipe 12.12. Converting Between Strings and Unicode or ASCII Chapter 13. Regular Expressions One of the most powerful features added to ActionScript 3.0 is regular expressions. Regular expressions are, put simply, patterns that can be matched against strings. You may be familiar with other types of patterns, such as wildcards, which can be used to match patterns while searching for files. Patterns are also used in Recipe 9.5. Regular expressions support this type of pattern matching, but they are also much more sophisticated. Recipe 13.1. Understanding Regular Expression Patterns Recipe 13.2. Testing Regular Expressions Recipe 13.3. Looking for Pattern Matches Recipe 13.4. Removing and Replacing Characters and Words Using Patterns Recipe 13.5. Creating a Nongreedy Pattern Recipe 13.6. Validating User Input with Common Patterns Chapter 14. Dates and Times Recipe 14.1. Finding the Current Date and Time Recipe 14.2. Retrieving the Date Values Recipe 14.3. Retrieving the Day or Month Name Recipe 14.4. Formatting the Date and Time Recipe 14.5. Formatting Seconds or Milliseconds as Minutes and Seconds Recipe 14.6. Converting Between DMYHMSM and Epoch Milliseconds Recipe 14.7. Using Timers Recipe 14.8. Calculating Elapsed Time or Intervals Between Dates Recipe 14.9. Parsing a Date from a String Chapter 15. Programming Sound In the Flash IDE, you can import sound into the library, put sound on timeline frames, attach sounds to movie clips, and so on. This chapter covers programming sound with ActionScript 3.0, using the Sound class and its related classes SoundChannel, SoundLoaderContext, SoundMixer, and SoundTransform, all part of the flash.media package, so as your first order of business, make sure that you import flash.media.Sound in each example as well as any of the other classes the example use. Recipe 15.1. Creating a Sound Object and Loading a Sound Recipe 15.2. Starting and Stopping a Sound Recipe 15.3. Setting the Buffer for a Sound Recipe 15.4. Offsetting the Start of a Sound Recipe 15.5. Playing a Sound Multiple Times (Looping) Recipe 15.6. Getting the Size of a Sound File Recipe 15.7. Reading the ID3 Tag of a Sound File Recipe 15.8. Find Out When a Sound Finishes Playing Recipe 15.9. Tracking the Progress of a Playing Sound Recipe 15.10. Pausing and Restarting a Sound Recipe 15.11. Reading the Level of a Sound Recipe 15.12. Stopping All Sounds Recipe 15.13. Reading the Sound Spectrum Recipe 15.14. Changing the Volume or Pan of a Sound Recipe 15.15. Creating a Sound Application Chapter 16. Video The Flash Player is capable of playing back video. Although it's possible to embed video content within an .swf file, most Flash video content is stored in Flash video files (.flv files) and loaded into the Flash Player at runtime using ActionScript. By loading .flv files at runtime, you have smaller .swf files, more flexible content management, and greater control over the loading and playback of the video content. Flash video loaded from .flv files has two faces: progressive download and streaming. Streaming .flv video requires a streaming server, such as Flash Media Server. In contrast, progressive download doesn't require any additional software. However, for the most part, the ActionScript required to work with streaming and progressive download video is identical. The recipes in this chapter discuss how to work with progressive download video and focus exclusively on working with .flv files. Recipe 16.1. Loading and Playing Back Video Recipe 16.2. Controlling Video Sound Recipe 16.3. Reading Playback Time Recipe 16.4. Reading Video Duration Recipe 16.5. Controlling Playback Time Recipe 16.6. Scaling Video Recipe 16.7. Managing and Monitoring Buffering and Loading Recipe 16.8. Listening for Cue Points Recipe 16.9. Applying Filters to Video Recipe 16.10. Pausing and Resuming Video Recipe 16.11. Stopping Video Recipe 16.12. Scrubbing Video Recipe 16.13. Clearing the Video Display Recipe 16.14. Determining User Bandwidth Chapter 17. Storing Persistent Data This chapter focuses solely on local shared objects (LSOs). Local shared objects are similar to browser cookies in that they are stored on the client's machine. LSOs are useful for storing the same kind of information for which cookies have traditionally been used, such as the ability for a web site to remember a user so that the user does not have to manually login during each visit. However, LSOs are more powerful than cookies because, by default, they never expire, they can store more data than cookies, they aren't transmitted between the client and server, and they can store native ActionScript datatypes. In contrast to remote shared objects (RSOs), LSOs are available to use without any additional software involved on either the client or server. Recipe 17.1. Creating and Opening a Local Shared Object Recipe 17.2. Writing Data to a Shared Object Recipe 17.3. Saving a Local Shared Object Recipe 17.4. Reading Data from a Shared Object Recipe 17.5. Removing Data from a Shared Object Recipe 17.6. Serializing Custom Classes Recipe 17.7. Sharing Data Between Flash Applications Recipe 17.8. Controlling the Size of Local Shared Objects Chapter 18. Communicating with Other Movies Flash Player 6 introduced local connections, a means by which any Flash movie can broadcast to and listen for broadcasts from any other movie on the same computer. This chapter focuses on inter-movie communication through the use of LocalConnection, allowing multiple movies on the same client computer to interact with each other. Recipe 18.1. Creating Local Connections Recipe 18.2. Sending Data Recipe 18.3. Validating Receipt of Communication over Local Connections Recipe 18.4. Accepting Local Communications from Other Domains Chapter 19. Sending and Loading Data Sending and loading data has changed dramatically in ActionScript 3.0. The LoadVars class has been removed and replaced with a more robust URLLoader class in the flash.net package. URLLoader is supported by a new cast of characters, namely URLRequest, URLVariables, and URLStream (and a few others). In this chapter you'll see that these classes combine to form a rich API that offers more functionality and flexibility than what was available in previous versions. Recipe 19.1. Loading Variables from a Text File Recipe 19.2. Loading Variables from a Server-Side Script Recipe 19.3. Loading a Block of Text (Including HTML and XML) Recipe 19.4. Checking Load Progress Recipe 19.5. Accessing Data Being Downloaded Recipe 19.6. Sending Data to a Server-Side Script Recipe 19.7. Sending Variables and Handling a Returned Result Chapter 20. XML ActionScript 3.0 boasts a revolutionary new syntax for working with XML. ECMAScript for XML, otherwise known as E4X, is a language extension that gives you a simpler, easier to read approach for working with XML objects than the traditional Document Object Model (DOM), an interface of the past. Using E4X, you'll find that you can work with XML much easier than before. Additionally, if this is your first time working with XML, E4X dramatically lowers the learning curve of using XML, as the recipes in this chapter illustrate. Recipe 20.1. Understanding XML Structure (Reading and Writing XML) Recipe 20.2. Creating an XML Object Recipe 20.3. Adding Elements to an XML Object Recipe 20.4. Adding Text Nodes to an XML Object Recipe 20.5. Adding Attributes to an XML Element Recipe 20.6. Reading Elements in an XML Tree Recipe 20.7. Finding Elements by Name Recipe 20.8. Reading Text Nodes and Their Values Recipe 20.9. Reading an Element's Attributes Recipe 20.10. Removing Elements, Text Nodes, and Attributes Recipe 20.11. Loading XML Recipe 20.12. Loading XML from Different Domains Recipe 20.13. Sending XML Recipe 20.14. Searching XML Recipe 20.15. Using HTML and Special Characters in XML Chapter 21. Web Services and Flash Remoting Flash Remoting and Web services both make asynchronous requests to service methods, and both can be used to create sophisticated client-server applications. The recipes in this chapter look at how to work with these technologies. Recipe 21.1. Calling Web Services Methods Recipe 21.2. Handling Web Services Responses Recipe 21.3. Handling Web Services Errors Recipe 21.4. Calling Flash Remoting Methods Recipe 21.5. Handling Flash Remoting Responses Chapter 22. Building Integrated Applications The ExternalInterface class allows the Flash Player to communicate in a synchronous manner with the application within which it is embedded. In many cases that host application is a web browser. As such, this chapter focuses exclusively on how to build applications that integrate ActionScript and JavaScript when Flash Player is embedded in a browser. Recipe 22.1. Calling JavaScript Functions Recipe 22.2. Calling ActionScript Functions Recipe 22.3. Passing Parameters from HTML Chapter 23. File Management Prior to Version 8, the Flash Player did not support any mechanism for allowing the user to browse their computer for files. Furthermore, Flash Player didn't have a mechanism for uploading or downloading files, either. As such, most web applications used HTML-based solutions for uploading and downloading files. Flash-based applications not deployed on the Web often had to use customized solutions for uploading and downloading files. Flash Player 8 and higher now supports the new APIs, which greatly simplify file I/O by allowing Flash Player to browse a user's system for files to upload and download. Flash Player allows users to browse to files on their local disks and upload and download files using the FileReference and FileReferenceList classes. This chapter discusses the details of working with those APIs Recipe 23.1. Downloading Files Recipe 23.2. Detecting When a User Selects a File to Upload Recipe 23.3. Monitoring Download Progress Recipe 23.4. Browsing for Files Recipe 23.5. Filtering Files That Display in the Browser Window Recipe 23.6. Detecting When the User Has Selected a File to Upload Recipe 23.7. Uploading Files Recipe 23.8. Monitoring File Upload Progress Chapter 24. Socket Programming Socket connections allow the Flash Player to send and load data from a server over a specified network port. Binary socket connections are new in ActionScript 3.0 and enable raw connections that allow for transfer of binary information. Binary sockets are slightly more advanced than XML sockets because they require a low-level knowledge of binary datatypes, but they are also more powerful because you can connect to a wider range of socket servers and generally do more with them. For example, binary sockets allow you to connect to mail servers (via POP3, SMTP, and IMAP), news servers (via NNTP), chat servers, or even implement screen sharing and remote desktop applications by connection to a VNC server (via RFB). You'll learn more about how to deal with the asynchronous nature of the Flash Players socket connections as you go through this chapter. Recipe 24.1. Connecting to a Socket Server Recipe 24.2. Sending Data Recipe 24.3. Receiving Data Recipe 24.4. Handshaking with a Socket Server Recipe 24.5. Disconnecting from a Socket Server Recipe 24.6. Handling Socket Errors
|