Master the Time-saving Power of Flash Components, Part 1

Master the Time-saving Power of Flash Components, Part 1

ow often have you found yourself repeating the same tasks in Flash over and over? Perhaps you’ve recreated a logo or animation, or rewritten some simple script again and again. Wouldn’t it be great if you could drag and drop a widget into your file and just have it work? With Flash components you can often do just that.

Components are self-contained units, usually comprised of graphics and code, that you can simply drop into your file to serve a specific purpose. Components can include preloaded animations, buttons, or even code-only tasks such as a timer.

You may have tried using existing Flash components or even added third-party components to your applications, but wouldn’t it be ideal if you could create your own component that did exactly what you wanted it to do? This article will help you accomplish that goal.

Defining Components
For the uninitiated, MovieClips are one of the three symbol types that promote efficient reusability of Flash assets. A graphical element that begins life as a circle drawn on the stage, for example, is called a shape and might be considered a ‘one-time use’ asset. That is, each time that circle is used, it is essentially recreated, and contributes to file size. Converting that shape into a symbol, in this case a MovieClip, places a copy of that graphical element into the library of a Flash file. Thereafter, repeated uses of that element within the same file are, essentially, references rather than new copies. This promotes reusability, improves performance and reduces file download times.

What You Need
Components are basically self-contained, reusable combinations of MovieClips extended with the power of ActionScript. This article does not require fluency in either MovieClips or ActionScript but you may find a smoother road into the world of components if you have at least a fundamental understanding of both.

ActionScript, as the native scripting language of Flash, allows us to exert programmatic control over MovieClips, and gives developers the tools with which to create richer interactive experiences. Add the ability to reuse ActionScript, as well as graphical assets?all with drag-and-drop simplicity?and you have a Flash component.

To download the souce code for this article:

Author’s Note: The material from which this article was derived will be presented in a session called “Authoring Components” at the FlashForward 2005 conference in San Francisco, April 6-8.

Flash Component Architecture: v1 vs. v2
If you’ve been interested in learning about components, you may have noticed a lot of recent discussion about “v1” vs. “v2” architecture. “Version 1” refers to Flash MX-compatible components, using ActionScript 1.0. “Version 2” refers to the new component architecture, based on ActionScript 2.0 for use with Flash MX 2004.

With the release of MX 2004, ActionScript has evolved into a more robust object-oriented language. The differences between AS 2.0 and AS 1.0 are too significant to go into great detail here; a few simple examples will help you understand how they impact the v1 vs. v2 component architecture choice. AS 2.0 offers strict data typing (meaning that variables must be defined as numbers or strings, for example, and stay with that data type), strict case-sensitivity, and the benefits of a true object-oriented language?including public and private classes and proper inheritance. AS 1.0 employs weak data typing (meaning that a variable with a number value can later be reassigned a string value without error), is case-insensitive in some ways, and does not offer true public and private classes for optimal object-oriented programming. (For a more detailed description of these compatibility issues, see the sidebar “Component Migration.”)

Figure 1. The End Result: This is an example of our finished sample component in action.

The differences between the v2 and v1 components are similar in some ways. To get the most of the v2 architecture, you need to use ActionScript 2.0 and define private and public classes. Another feature v2 offers is an extensible framework that allows components to share code structures and accomplish common tasks by sub-classing. Neither of these features is available to v1 components.

I won’t be focusing on the v2 architecture in this article for a variety of reasons. To begin with, it helps to learn the basics of how to put a v1 component together from nothing, before learning the v2 base framework that you can extend. Second, it can be easier for the uninitiated to embrace the less-restrictive structure of ActionScript 1.0 and move on to the changes, and benefits, of ActionScript 2.0 as experience is gained. But there’s a more important reason that applies to all skill levels: By focusing on the earlier version of the architecture you’ll learn how to create a component that is compatible not only with many Flash MX 2004 projects, but also Flash MX files?and even Flash 5 files, in some cases, where legacy issues may be at stake. .

As hinted above, v2 components won’t work in versions of Flash prior to MX 2004. If a component is authored in MX 2004 using ActionScript 2.0, it will require at least that version of ActionScript to function, preventing its use in Flash versions prior to MX 2004. But there’s also no guarantee that v1 components will work in all MX 2004 projects, so a little project planning is recommended. Again, see the brief sidebar “Component Migration” for more information.

Learn Step by Step
It’s true that components can offer a lot of power and flexibility, and with that comes a necessary support infrastructure. However, there’s no reason that you have to start with an overly complex example. You certainly don’t have to begin by using every component feature right away, and you can embrace some of the more important coding techniques early, and add more complex concepts as you become more comfortable.

In keeping with this step-by-step methodology, I will begin this article with a simple hard-coded MovieClip, then replace some of the hard-coded values with user-defined parameters, and finally add features that really allow components to function as standalone widgets. (Click here to download the code for this article or use the link in the left-hand column.)

The Sample Component
My goal is to create a very simple sample component that will allow you to focus more on the process of creating the component and less on general ActionScript. As such, I will focus on only one feature for the utility; I will not spend time on error-checking user-entered values, and I won’t cover all the best practices recommended for bulletproof coding. You can add these types of checks and balances to your final product as your comfort level grows.

The example component I’ve developed will automatically “stamp” a copyright symbol in the lower right corner of your movie. This is a stripped example of something you might use to automatically (and programmatically) brand your movies. I’ve used similar techniques to programmatically add phrases such as “BETA,” a watermark, a datestamp, etc., without having to worry about doing it by hand again and again.

I will focus on changing only one parameter?the opacity of the artwork’s white background?which is accomplished by adjusting the _alpha property one of the component’s parts. An _alpha of 0 is transparent, and an _alpha of 100 is opaque. The final component, complete with an optional custom user interface (more on that later), is shown in Figure 1.

In this article, you’ll learn how to:

  • Create a normal hard-coded Movie Clip (MC)
  • Create user-definable parameters
  • Create a live preview so users can change parameter values and see the effects
  • Add a plain text description about the component to the Reference panel
  • Add a custom icon to your component for distribution to others
  • Manually install the component for testing.

In February, DevX will publish part 2 of this article, which will discuss how to:

  • Add a custom user interface to the Properties pane, to set parameters
  • Enhance the component with a custom class when it is initialized
  • Make your code more user-friendly and better insulated by defining “getter” and “setter” wrappers
  • Enhance the Reference panel description, and add custom actions to the Action panel using XML
  • Package the component for distribution with the Extension Manager.

Step 0: Starting with a MovieClip
I’ll start by making a simple 72 x 72 pixel MovieClip that has two MovieClips within it. The first is a solid white square background and the second is a black copyright symbol. Using the color effect symbol properties menu, I’ll give the copyright symbol an alpha value of 50 percent, which will remain fixed. Then, I’ll instantiate the white background square with the name “stampBack.” This allows me to control its alpha value through ActionScript. Finally, I’ll add the following ActionScript to frame the background MovieClip:

this.swapDepths(1000);this.stampBack._alpha = 50this._x = Stage.width - 20;this._y = Stage.height - 20;

This script does three simple things. The first line ensures the copyright “stamp” appears, arbitrarily, above the first 999 levels of content of any file. The second line will give the “stampBack” MC (our white square background) an opacity of 50 percent. This is the hard-coded value that I’ll change later. Finally, the third and fourth lines will position the parent MovieClip (containing both the white background and the copyright symbol) in the lower right corner of your movie, 20 pixels from the right and bottom edges.

In the Library, name the MovieClip “Stamper.” Test your movie. You now have a functioning asset in a familiar format (MovieClip). (I’ve called this “step 0” because what I’ve created is not yet a component but rather a familiar hard-coded example to work with.)

Step 1: Define Parameters

Figure 2. Setting Definitions: This shot demonstrates setting a variable type in the Component Definition dialog. This value will be interpreted as a number.

Next, I’ll turn the MovieClip into the first stages of a component by defining parameters that can be changed by the user. From a scripting standpoint, I need to change a hard-coded value to a variable. Because I’m working only with the background alpha at this point, I only need to change one line of the above code?to replace the value of 50 with the variable “sBackAlpha” (localized to the MovieClip by using the “this” self-reference):

this.stampBack._alpha = this.sBackAlpha

Next, I need to use the Library to turn the MC into a component and define this parameter as user-modifiable. Select the MovieClip in the Library and use the Library’s pull-down menu to choose the “Component Definition…” option. Here, I’ll add a parameter and configure its attributes (see Figure 2).

Figure 3. Changing Parameters: Once your component parameters have been defined, set their value in the Component Parameters tab of the Property Inspector.

You should use the “+” symbol at the top of the window to add a parameter. Give it a short name that will still be clear in the parameters pane. This is more of a descriptive string to tell the user what the parameter is. Then assign a variable that will be populated. I used “sBackAlpha” when I replaced the hard-coding, so I’ll use the same value here. Then assign the type of the variable.

To specify an opacity value, you need a number. This prevents errors due to data type translation. If you type in a string of “50” into the parameters pane, you want it to be thought of as the number 50, not the letters “50.” This type attribute feature of the Components Definition dialog will cast the type of the variable to ‘number.’ Finally, use a default value of 50. (The “Parameters are locked in instances” option should be left on to prevent users from adding or deleting parameters from component instances.)

You now have a functioning component! Drag the component to the stage and make sure it is selected. The Properties panel has changed to show the Component Parameters tab. You can change the default value of 50 to 20, or 100; then test your movie and you will see the effect of the updated value (see Figure 3).

Author’s Note: Once you’ve changed a MovieClip into a component, you can’t double-click the component on the stage to edit it any longer. This is to prevent you from making accidental changes to the component. However, editing remains a simple task. All you need to do is select the component in the library and choose “Edit” from the library menu.

Step 2: Create a Live Preview
It can be time consuming to test your movie every time you want to see the results of changing a parameter. Fortunately, Flash provides a mechanism for seeing the update right on the stage. It is called Live Preview and, essentially, it is a duplicate of your component, stored inside the component itself (ultimately) and, once configured, it automatically receives the updated information from the parameters pane, displaying changes as you make them.

To create a Live Preview, you will be creating an entirely new Flash file with the same dimensions of your component (72 x 72). Next, copy or drag the component you created in Step 1 from its library into the new movie stage. Break it apart (Modify > Break Apart) so you have access to the component’s individual parts. (It should not remain a duplicate of the component.)

At this point, the copyright symbol is still a MovieClip with an assigned color effect alpha value of 50, and the background white square is still a MovieClip with an instance name of “stampBack.” All you need to do is add some ActionScript to update the alpha of the background square when the Live Preview is told to do so. This communication between the component parameter dialog and the Live Preview is automatic, but you’ll need to understand two things.

First, that the information used to update the preview is transferred through a built-in mechanism called “xch,” short for “exchange.” This allows Live Previews to receive parameter changes and act on that information, and it also allows custom parameter interfaces (which I’ll discuss later) to send the same information. You don’t have to do anything to use this mechanism other than reference it in your ActionScript.

Second, there is a built-in function, appropriately named “onUpdate(),” that will react to xch info when it comes in. So, all you have to do is add the following script to the first frame of your new Live Preview movie:

function onUpdate() {     stampBack._alpha = xch.sBackAlpha;}

Now save your movie into the same directory as your component movie (this is not necessary, just convenient) and test your movie to quickly publish an SWF version of the file (you’ll need it for the next operation).

Finally, you have to add the Live Preview to the component itself. Go back to your main component movie, select the component you’re working on in your library, and open the same “Component Definition…” window you used earlier. Next to the Live Preview option, hit the Set button and choose the “Live Preview in external .swf file” option. Then browse to the Live Preview SWF that you just created. Linking to this external file will allow you to test often by simply replacing the SWF if you make changes to the Live Preview. (In part 2 of this article, I’ll show you how to “embed” this operation so that you don’t have to distribute additional SWF files, which can get lost or damaged, with your component.) When you are done, dismiss the dialog.

Figure 4. Matching Icon: The ‘FCustomIcons’ folder and the component must be in the same relative directory of your Library for your component to display a custom icon.

Now, for certainty, delete the copy of the component that you have on stage and drag another copy in. This time, when you make changes in the parameters pane, they will be reflected on stage immediately. (Make sure the Enable Live Preview option is active in Flash’s Control menu. This is a performance option that allows you to enable or disable Live Previews to speed up authoring, if you desire.)

Step 3: Add a Description
Now that you have a component with a Live Preview, it’s time to add some text describing your component in the Reference pane. In the same “Component Definition…” window you used before (see Figure 2), click on the “Description” Set button and choose “Description is plain text.” The text you provide here will be seen when the Properties Help button is clicked (while the Component is selected) and you choose “Help On This component.”

Step 4: Add a Custom Icon
Adding a custom icon to your component is an extra step you can take to help you easily identify it, or even brand it, within the components dialog. If you decide not to create a custom icon, you can use the default components icon (or choose from any preset icons that may be appropriate). But creating your own is easy and a nice “extra” touch.

To do it, create a 24 x 20 graphic, in a file format supported by Flash. (I used PNG because that format does not require a square background; I have the freedom to make whatever shape I want.) Go to the Library and create a new folder called “FCustomIcons.” Import the graphic into the Library, and place it in this folder. Double-click the graphic file to change its name and match the name of your component exactly. If these names match, and the file is in the properly named folder, the component will have a custom icon. If it doesn’t update immediately, close and reopen the library to see the change.

Figure 4 shows the “FCustomIcons” folder, relative to your component.

Step 5: Manually Install and Test the Component
You’re now done with the absolute basics and can test your work. To do this you need to install the component in the Components panel and try it out.

Figure 5. Roll over: After manual installation you should be able to see your component in the Components palette. If you added a tool tip string, you should also be able to see a tool tip when you roll over your component with your mouse.

First, select the component in the Library and go back to the “Component Definition…” window. Enable “Display in Components Panel” checkbox. Here, you can add a brief tool tip that will display when you roll over the component’s icon in the Components panel. Next, click on the “Live Preview” Set button and switch to the embedded option. I left this file external throughout the testing phase for convenience. However, changing it to embedded will help reduce any possible problem of lost or incorrect pathnames when moving or copying the file on your drive.

Finally, quit Flash, copy the FLA file (not the SWF) to the Flash Configuration folder for your operating system, and place it in the “Components” directory:

For Windows operating systems:
Windows 2000 or XP: C:Documents and SettingsuserApplication DataMacromediaFlash MXConfigurationComponents
Windows 98 or ME: C:WindowsApplication DataMacromediaFlash MXConfigurationComponents
Windows NT: Windows directoryprofilesuserApplication DataMacromediaFlash MXConfigurationComponents

For Macintosh operating systems:
Macintosh OS X: Hard Drive/Users/Library/Application Support/Macromedia/FlashMX/Configuration/Components
Macintosh System 9.x, single user: Hard Drive/System folder/Application Support/Macromedia/FlashMX/Configuration/Components
Macintosh System 9.x, multiple users: Hard Drive/Users/user/ Documents/Macromedia/FlashMX/Configuration/Components

Now you can restart Flash and your component should be in the Components panel (see Figure 5). When you roll over it you should see the tool tip you provided. Drag it to the stage and configure its lone property. Because of the Live Preview, the stage version should update immediately, without having to test your movie.

Coming up Next …
In part two of this article, coming in February, I’ll show you how to make a custom interface for the Component Properties panel, how to add some new ActionScript to make your component more robust and easy to use, and how to add help and usage notes to Flash’s Reference and Action panels. You’ll even learn how to package your component for error-free distribution via the Macromedia Extension Manager.



Share the Post:
USA Companies

Top Software Development Companies in USA

Navigating the tech landscape to find the right partner is crucial yet challenging. This article offers a comparative glimpse into the top software development companies

Software Development

Top Software Development Companies

Looking for the best in software development? Our list of Top Software Development Companies is your gateway to finding the right tech partner. Dive in

India Web Development

Top Web Development Companies in India

In the digital race, the right web development partner is your winning edge. Dive into our curated list of top web development companies in India,

USA Web Development

Top Web Development Companies in USA

Looking for the best web development companies in the USA? We’ve got you covered! Check out our top 10 picks to find the right partner

Clean Energy Adoption

Inside Michigan’s Clean Energy Revolution

Democratic state legislators in Michigan continue to discuss and debate clean energy legislation in the hopes of establishing a comprehensive clean energy strategy for the

Chips Act Revolution

European Chips Act: What is it?

In response to the intensifying worldwide technology competition, Europe has unveiled the long-awaited European Chips Act. This daring legislative proposal aims to fortify Europe’s semiconductor

USA Companies

Top Software Development Companies in USA

Navigating the tech landscape to find the right partner is crucial yet challenging. This article offers a comparative glimpse into the top software development companies in the USA. Through a

Software Development

Top Software Development Companies

Looking for the best in software development? Our list of Top Software Development Companies is your gateway to finding the right tech partner. Dive in and explore the leaders in

India Web Development

Top Web Development Companies in India

In the digital race, the right web development partner is your winning edge. Dive into our curated list of top web development companies in India, and kickstart your journey to

USA Web Development

Top Web Development Companies in USA

Looking for the best web development companies in the USA? We’ve got you covered! Check out our top 10 picks to find the right partner for your online project. Your

Clean Energy Adoption

Inside Michigan’s Clean Energy Revolution

Democratic state legislators in Michigan continue to discuss and debate clean energy legislation in the hopes of establishing a comprehensive clean energy strategy for the state. A Senate committee meeting

Chips Act Revolution

European Chips Act: What is it?

In response to the intensifying worldwide technology competition, Europe has unveiled the long-awaited European Chips Act. This daring legislative proposal aims to fortify Europe’s semiconductor supply chain and enhance its

Revolutionized Low-Code

You Should Use Low-Code Platforms for Apps

As the demand for rapid software development increases, low-code platforms have emerged as a popular choice among developers for their ability to build applications with minimal coding. These platforms not

Cybersecurity Strategy

Five Powerful Strategies to Bolster Your Cybersecurity

In today’s increasingly digital landscape, businesses of all sizes must prioritize cyber security measures to defend against potential dangers. Cyber security professionals suggest five simple technological strategies to help companies

Global Layoffs

Tech Layoffs Are Getting Worse Globally

Since the start of 2023, the global technology sector has experienced a significant rise in layoffs, with over 236,000 workers being let go by 1,019 tech firms, as per data

Huawei Electric Dazzle

Huawei Dazzles with Electric Vehicles and Wireless Earbuds

During a prominent unveiling event, Huawei, the Chinese telecommunications powerhouse, kept quiet about its enigmatic new 5G phone and alleged cutting-edge chip development. Instead, Huawei astounded the audience by presenting

Cybersecurity Banking Revolution

Digital Banking Needs Cybersecurity

The banking, financial, and insurance (BFSI) sectors are pioneers in digital transformation, using web applications and application programming interfaces (APIs) to provide seamless services to customers around the world. Rising

FinTech Leadership

Terry Clune’s Fintech Empire

Over the past 30 years, Terry Clune has built a remarkable business empire, with CluneTech at the helm. The CEO and Founder has successfully created eight fintech firms, attracting renowned

The Role Of AI Within A Web Design Agency?

In the digital age, the role of Artificial Intelligence (AI) in web design is rapidly evolving, transitioning from a futuristic concept to practical tools used in design, coding, content writing

Generative AI Revolution

Is Generative AI the Next Internet?

The increasing demand for Generative AI models has led to a surge in its adoption across diverse sectors, with healthcare, automotive, and financial services being among the top beneficiaries. These

Microsoft Laptop

The New Surface Laptop Studio 2 Is Nuts

The Surface Laptop Studio 2 is a dynamic and robust all-in-one laptop designed for creators and professionals alike. It features a 14.4″ touchscreen and a cutting-edge design that is over

5G Innovations

GPU-Accelerated 5G in Japan

NTT DOCOMO, a global telecommunications giant, is set to break new ground in the industry as it prepares to launch a GPU-accelerated 5G network in Japan. This innovative approach will

AI Ethics

AI Journalism: Balancing Integrity and Innovation

An op-ed, produced using Microsoft’s Bing Chat AI software, recently appeared in the St. Louis Post-Dispatch, discussing the potential concerns surrounding the employment of artificial intelligence (AI) in journalism. These

Savings Extravaganza

Big Deal Days Extravaganza

The highly awaited Big Deal Days event for October 2023 is nearly here, scheduled for the 10th and 11th. Similar to the previous year, this autumn sale has already created

Cisco Splunk Deal

Cisco Splunk Deal Sparks Tech Acquisition Frenzy

Cisco’s recent massive purchase of Splunk, an AI-powered cybersecurity firm, for $28 billion signals a potential boost in tech deals after a year of subdued mergers and acquisitions in the

Iran Drone Expansion

Iran’s Jet-Propelled Drone Reshapes Power Balance

Iran has recently unveiled a jet-propelled variant of its Shahed series drone, marking a significant advancement in the nation’s drone technology. The new drone is poised to reshape the regional

Solar Geoengineering

Did the Overshoot Commission Shoot Down Geoengineering?

The Overshoot Commission has recently released a comprehensive report that discusses the controversial topic of Solar Geoengineering, also known as Solar Radiation Modification (SRM). The Commission’s primary objective is to

Remote Learning

Revolutionizing Remote Learning for Success

School districts are preparing to reveal a substantial technological upgrade designed to significantly improve remote learning experiences for both educators and students amid the ongoing pandemic. This major investment, which

Revolutionary SABERS Transforming

SABERS Batteries Transforming Industries

Scientists John Connell and Yi Lin from NASA’s Solid-state Architecture Batteries for Enhanced Rechargeability and Safety (SABERS) project are working on experimental solid-state battery packs that could dramatically change the

Build a Website

How Much Does It Cost to Build a Website?

Are you wondering how much it costs to build a website? The approximated cost is based on several factors, including which add-ons and platforms you choose. For example, a self-hosted