BUY THIS BOOK
Add to Cart

Print Book $24.95


Add to Cart

Print+PDF $32.44

Add to Cart

PDF $19.99

Safari Books Online

What is this?

Add to UK Cart

Print Book £17.50

What is this?

Looking to Reprint or License this content?


Flash Hacks
Flash Hacks 100 Industrial-Strength Tips & Tools

By Sham Bhangal
Book Price: $24.95 USD
£17.50 GBP
PDF Price: $19.99

Cover | Table of Contents | Colophon


Table of Contents

Chapter 1: Visual Effects
This book assumes you are familiar with the basics of using Flash to create visual effects and animations using the timeline. If you aren't comfortable with Flash, you might still find the techniques employed here interesting. Once you've learned some Flash basics via either Flash's online help or a tutorial book, you can revisit the hacks that piqued your curiosity. I considered beginning the book with tips on optimization, security, and similar topics. But I decided to defer those until later, hoping that the hacks in this chapter would get you excited about the book and expand your horizons while remaining true to the hacker ethic: "Show me the cool stuff first."
So, in this chapter, I've grouped hacks that show you how to achieve some effects you might not have known about or might have seen and not known how to reproduce. As with all the hacks presented in this book, I hope they educate and ultimately inspire you—not in the sense of "inspiration," as when one views a great piece of art, but in the sense of "motivation." Thus, I hope you are motivated to try these hacks and inspired to create some of your own.
The hacks in this chapter are grouped together because they are all loosely associated with visual effects. Later chapters in this book deal with additional visual effects using transitions and colorization, 3D, masking, and the Drawing API. This chapter includes pixel effects and converting from animated GIFs and Photoshop files to Flash .fla and .swf files (the source document and distribution formats used by Flash). I close the chapter with two hacks that show you how to generate a tree and make it sway in the breeze.
Although Chapter 3 makes the heaviest use of masks, masks are so ubiquitous in Flash [Hack #1] that hacks in other chapters use them as well. So for readers unfamiliar with masks, here is a brief introduction.
Flash animations are created by superimposing one or more layers in an animation (similar to layers as you'd find in Photoshop and other graphics programs). The Timeline panel contains the main timeline, which organizes the layers and displays their contents over time. Masks are traditionally used to create visual effects, such as a spotlight effect, in which one layer is viewed through the "hole" created by the masking layer. That is, the masking layer defines the area of the underlying masked layer that is visible (the remainder is "masked off" and therefore invisible). To create a masking layer (or simply "mask layer") in the authoring tool, insert a new layer in the timeline (using Insert
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Hacks #1-7
This book assumes you are familiar with the basics of using Flash to create visual effects and animations using the timeline. If you aren't comfortable with Flash, you might still find the techniques employed here interesting. Once you've learned some Flash basics via either Flash's online help or a tutorial book, you can revisit the hacks that piqued your curiosity. I considered beginning the book with tips on optimization, security, and similar topics. But I decided to defer those until later, hoping that the hacks in this chapter would get you excited about the book and expand your horizons while remaining true to the hacker ethic: "Show me the cool stuff first."
So, in this chapter, I've grouped hacks that show you how to achieve some effects you might not have known about or might have seen and not known how to reproduce. As with all the hacks presented in this book, I hope they educate and ultimately inspire you—not in the sense of "inspiration," as when one views a great piece of art, but in the sense of "motivation." Thus, I hope you are motivated to try these hacks and inspired to create some of your own.
The hacks in this chapter are grouped together because they are all loosely associated with visual effects. Later chapters in this book deal with additional visual effects using transitions and colorization, 3D, masking, and the Drawing API. This chapter includes pixel effects and converting from animated GIFs and Photoshop files to Flash .fla and .swf files (the source document and distribution formats used by Flash). I close the chapter with two hacks that show you how to generate a tree and make it sway in the breeze.
Although Chapter 3 makes the heaviest use of masks, masks are so ubiquitous in Flash [Hack #1] that hacks in other chapters use them as well. So for readers unfamiliar with masks, here is a brief introduction.
Flash animations are created by superimposing one or more layers in an animation (similar to layers as you'd find in Photoshop and other graphics programs). The Timeline panel contains the main timeline, which organizes the layers and displays their contents over time. Masks are traditionally used to create visual effects, such as a spotlight effect, in which one layer is viewed through the "hole" created by the masking layer. That is, the masking layer defines the area of the underlying masked layer that is visible (the remainder is "masked off" and therefore invisible). To create a masking layer (or simply "mask layer") in the authoring tool, insert a new layer in the timeline (using Insert
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Fake Per-Pixel Transitions
Simulate pixel-based fades and wipes, as supported in Macromedia Director.
Flash doesn't have built-in support for pixel-based transitions. This hack can be used with other video-friendly hacks [Hack #8] to make your static bitmaps more interesting [Hack #3].
Flash uses a vector-based rendering engine, which doesn't allow direct access to the individual screen pixels. This hack depends on the fact that pixels are small, and when you make something small, it looks like anything else that is small.
The per-pixel transition effect is shown in Figure 1-1.
Figure 1-1: Simulated per-pixel transition, steps 1 through 4
The transition hides (masks) pixels in the first image over time so that the image disappears a few pixels at a time. Masking off the first image reveals a second image that is positioned below it, thus creating the transition effect from the first image to the second image. The masks used to create the preceding effect are shown in Figure 1-2. Note that for black pixels, the mask effect shows the first (topmost) image; for white pixels (no mask), it shows the second (bottom) image.
Figure 1-2: Masks for simulated per-pixel transition, steps 1 through 4
As we shall see, we can make much more complex transitions with little change.
This hack requires three steps:
  1. Make the fake pixel. In this hack we will create a little 4x4 rectangle.
  2. Find a way to make lots of fake pixels. This is done very easily in Flash using MovieClip.attachMovie( ).
  3. Create a transition by creating a script that makes each dot disappear after a certain time. By using all the dots as a large mask, we create the transition between two images (or video clips), as seen in Figure 1-1.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Per-Pixel Text Effects
Create advanced text effects and transitions that operate on the per-pixel level.
The problem in simulating per-pixel effects in Flash is that potential performance degradation limits how many fake pixels you use. You have two ways to keep this number small: keep to small images (as we did in the per-pixel transition effect hack [Hack #1]), or use the effect on an image with lots of background pixels (which you can ignore to reduce the number of fake pixels needed).
Although it's probably obvious in hindsight, it took me ages to realize that text fits the "lots of background pixels" criterion. A quick trawl on the Web suggests that it really isn't obvious because nobody else seems to be using this hack.
In this hack, we'll make the text appear to coalesce from pixels spread out over the screen. Of course, you can implement various effects using different calculations for the mask pixels' positions.
The hack comes in two parts:
  • Converting the text block's shape into 1x1 squares (i.e., our "fake pixels")
  • Animating the fake pixels
Here are the steps:
  1. Create a text field and enter some text.
  2. Press Ctrl-B (Windows) or ⌘-B (Mac) or choose ModifyBreak Apart twice to turn the text field into a primitive shape.
  3. With the text still selected, press F8, and convert it into a movie clip symbol named text. Make sure the Export for ActionScript checkbox is checked and specify the linkage identifier as text. (Delete the clip instance from the Stage, as we'll be adding it at runtime from the Library with MovieClip.attachMovie( ).)
  4. For the effect to work, the movie clip's registration point must be at the top left of the text. Enter Edit in Place mode by double-clicking the movie clip; then to select all the text choose Edit
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Simulate Old Film Grain
Create the effect of old film grain using Photoshop and Flash.
Flash's vector graphic engine has a lot going for it, but sometimes you want something a little less clean-edged. Adding an old film grain effect is one of the easiest ways to add instant atmosphere or a grungy hard edge to an otherwise crisp and clean clip. It can be combined with video colorization [Hack #8] or sepia tone colorization [Hack #13] for more dramatic and specialized effects.
The most obvious way to add a film grain effect is to add random vector lines and dots to an image. That reproduces the effect, but it doesn't really reproduce the atmosphere of old film; we still end up with a crisp rendering. In this hack we use a bitmap, which allows us to avoid the clean effect of vectors.
The hack has two parts: creating the film grain bitmap in Photoshop and then importing and using it in Flash. (We could of course use Fireworks in place of Photoshop; the principles are the same.)
Dirt, scratches, and dropouts add a real-world edge to a photograph. Dust, dirt, and hair or lint that has made its way onto the film or negative appear as dark patches and lines. Scratches appear as white lines.
To begin adjusting the image in Photoshop:
  1. Open Photoshop.
  2. Press D to reset to the default background and foreground colors.
  3. Press X to switch background and foreground colors. This will give you a background color of black and a foreground color of white.
  4. Create a new Photoshop file called grain.psd using FileNew. Select a bitmap size that is longer than it is wide. I created a file 800 400 pixels for demonstration purposes, but you can go much smaller (typically 400 200).
  5. Check the Background Color option in the Contents section of the New Document dialog box, as shown in Figure 1-9. This creates a rectangular black canvas.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Create SWFs from Animated GIFs
Quickly repurpose animated GIFs for use in Flash effects.
I thought it would be fun to show how you can enhance a GIF by reproducing it in Flash. So I went to the O'Reilly home page (http://www.oreilly.com) where I was greeted by the little critter—I'm told it's a tarsier—shown in Figure 1-17. The filename is oreilly_header1.gif, which is typical of slices created for an HTML-based table, so I knew I had a GIF I could work with. Anyway, I kept looking at him, given that he looks so cute, and then I blinked. He blinked back. After the surprise and obligatory double take, I realized he's an animated GIF.
Figure 1-17: The O'Reilly tarsier mascot on oreilly.com
So I started thinking...doing a Flash version of this critter would be a good example of the difference between Flash and traditional HTML design. This hack shows how you can reduce filesizes by using Flash instead of your animated GIFs. Once the 2D blinking tarsier animation is in Flash, you can modify it to simulate a 3D blinking tarsier [Hack #35] .
We can obtain a copy of our animated friend using a web browser's Save option. In Internet Explorer on Windows, for example, we right-click on the GIF and select Save Picture As from the pop-up menu to download the image to our local drive.
Another advantage of Flash animations over animated GIFs is that you can make them harder to steal than this critter was from O'Reilly's site by obfuscating the SWF [Hack #98] in the browser cache, which is where users ordinarily look for downloaded SWFs.
If you open the O'Reilly GIF file in an image editor (such as Fireworks or Photoshop/ImageReady), you will see that the blink animation runs every 12 seconds (the first frame has a delay of 12 seconds), and the animation is 12 seconds in total. One thing worth noticing is that an awful lot of pixels in the image don't change between frames—only the eyes do. So converting it to Flash and animating only the eyes should give us a big filesize advantage straight away.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Animate Photoshop PSD Files with Flash
Import full Photoshop PSD files into Flash, then animate them.
This hack tells you how to re-create a Photoshop file with layers in Flash. We'll go through the details because they are instructive (and free!), but a third-party Photoshop plugin, called PSD2FLA (http://www.medialab.com/psd2fla) from Media Lab, simplifies the process considerably. Director developers will recognize Media Lab as the maker of PhotoCaster, the well-respected and popular Xtra that imports PSD files into Director.
Assuming you have QuickTime 4.0 or higher installed, you can import a PSD file directly into Flash. Flash will most likely tell you that it cannot import the file, but it gives you the option of trying to import via QuickTime. Clicking Yes to this prompt imports your image.
Flash's file import description for .psd files is Photoshop 2.5, 3 Image; however, when importing via QuickTime, Flash can handle .psd files from much more recent versions of Photoshop.
The trouble with importing files using the QuickTime option is that the imported file becomes flattened, preventing you from accessing the separate PSD layers, seen in Figure 1-22. Given that the only real reason to import a PSD (as opposed to web formats such as JPEG) is to access the embedded layer information; this limitation makes QuickTime import less than ideal.
Figure 1-22: A Photoshop image with layers
This hack shows how to import a PSD in such a way that you can efficiently rebuild it in Flash for animation, complete with a significant amount of the original PSD layer information.
Starting in Photoshop, crop/resize the PSD so that you have an image with dimensions that make it suitable for the Web (i.e., no larger than 500x500 pixels).
You will get much better results if you scale a Photoshop image down in steps. For example, reducing a 1000x1000 image to 900x900, then 800x800, and so on, all the way down to 500x500 will give you a better final image and offer more options when you compress it later.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
A Tree Grows in Brooklyn
Create a random tree generator.
This hack creates a natural-looking tree using the usual suspects (fractals/recursion/repeat-and-scale algorithms). In the next hack, we'll create movement using an embedded hierarchy of movie clips.
For those of us who prefer speaking English, we're going to grow a tree and make it sway in a breeze [Hack #7]. We will do this by re-creating natural phenomena in code.
The first time I went to Flash Forward (http://www.flashforward2004.com), Josh Davis talked about what made him tick. To paraphrase his 45-minute presentation into a single sentence, he said, "Look at nature, and see what it throws up at you, and then think what you can do with the result."
The Web is full of such experiments, and no hacks book would be complete without one or two such excursions.
To get the following information on nature, I had a short conversation with my girlfriend Karen. We have a neat division of labor: she deals with the garden, and I deal with the computer.
Here's what I learned without having to set foot outside. Trees follow a very basic pattern, and this is usually regular. A branch will be straight for a certain length and will then split. The thickness of the parent branch is usually related to the branches that grow from it—normally the cross-section is conserved (the total thickness of the trunk is roughly the same as, or proportional to, the thickness of the branches that sprout from it). This means that a twig grows and splits in exactly the same way as a main branch: the relative dimensions are the same. You know that this self-same process between tree and twig is going on because, if you plant a twig (well, if Karen plants it; mine always dies), you end up with a tree.
With this in mind, I created a random tree generator. Two example results are shown in Figure 1-28.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Blowin' in the Wind: Simulate Tree Movement
Create forward kinematics with embedded movie clips.
We saw in the preceding hack how to generate a random tree. In this hack, we'll animate it. When trees move, they seem to follow the same tree-branch-twig hierarchy we used when generating the tree. It took me a while to work it out, although it's completely obvious once you grasp it:
  • When the tree trunk moves, the whole tree moves.
  • When a branch moves, all its daughter branches move.
The part that takes a bit of insight, though, is to figure out how much each part of the tree moves. I assumed that the trunk moves much less than the twigs at the fringes of the tree, but this isn't so. To see for yourself, plant a twig (cut up to its branch point) in the ground during a wind. You'll see it moves as much or as little as the trunk. The twig is weaker, but its surface area (assuming it has no leaves) is also less than the trunk, so the wind force is to the same scale.
A twig at the top of a tree moves more than the trunk simply because the motion of each branch in the hierarchy that supports it also moves, and all these movements are added cumulatively as you move up the tree. Wow! You learn something every day.
That tip for the day makes it easy to add a wind effect—you simply treat each branch the same as the trunk and all other branches!
Rather than delete each onEnterFrame( ) handler as we did in our original tree-creation code [Hack #6], change this line that removed the grow( ) function as the onEnterFrame( ) handler:
delete (this.onEnterFrame);
and replace it with the sway( ) function, once the branch is grown:
this.onEnterFrame = sway;
To create the wind effect, simply create a sway( ) function that specifies a wind value that is added to each branch every frame using our new sway( ) function:
function sway( ) {
  this._rotation += wind;
}
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 2: Color Effects
Although most Flash animators concentrate on animated movement and scaling when creating motion graphics, you can also animate color to create fades and transitions.
The compelling thing about animating color for the designer is that it can change both appearance and mood with little effort (and virtually no filesize increase). Changing the color scheme of a Flash animation allows you to create wide-ranging effects, such as shifting the animation from day to night. Changing the color of an image to sepia tones will give an old-time mood, whereas changing the colors to electric blues can be used to give a more techno feel.
You can apply color changes to anything that can be placed within a movie clip, including bitmaps, video, and vector graphics. In fact, anything that can be displayed on the Flash Stage can be color animated, and this animation can be controlled by tweens (performed at authoring time in the timeline) or ActionScript (performed at runtime).
This makes it easy to add runtime color effects, allowing you to make content appear more interesting with little or no bandwidth penalties. We will see how color effects can be applied to bitmaps to make them look more interesting, more in tune with a site design, or even to make your stationary bitmaps take on some of the features of video via video-like color transitions.
We will also look at applying color transitions to video, allowing you to make a short, repetitive video look like a much longer or more visually interesting one. Given that video is the most bandwidth-heavy asset, you can also optimize video content delivery by adding complex video transitions at runtime rather than applying them to the video source.
SWF files are one of the few web-based graphic assets in which color is "free"—there is no bandwidth penalty for adding lots of different colors to a Flash site. The downside is that you need to be more careful in managing this high level of choice. Therefore, we will look at several novel ways to manage color or to create sensible palettes quickly.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Hacks #8-13
Although most Flash animators concentrate on animated movement and scaling when creating motion graphics, you can also animate color to create fades and transitions.
The compelling thing about animating color for the designer is that it can change both appearance and mood with little effort (and virtually no filesize increase). Changing the color scheme of a Flash animation allows you to create wide-ranging effects, such as shifting the animation from day to night. Changing the color of an image to sepia tones will give an old-time mood, whereas changing the colors to electric blues can be used to give a more techno feel.
You can apply color changes to anything that can be placed within a movie clip, including bitmaps, video, and vector graphics. In fact, anything that can be displayed on the Flash Stage can be color animated, and this animation can be controlled by tweens (performed at authoring time in the timeline) or ActionScript (performed at runtime).
This makes it easy to add runtime color effects, allowing you to make content appear more interesting with little or no bandwidth penalties. We will see how color effects can be applied to bitmaps to make them look more interesting, more in tune with a site design, or even to make your stationary bitmaps take on some of the features of video via video-like color transitions.
We will also look at applying color transitions to video, allowing you to make a short, repetitive video look like a much longer or more visually interesting one. Given that video is the most bandwidth-heavy asset, you can also optimize video content delivery by adding complex video transitions at runtime rather than applying them to the video source.
SWF files are one of the few web-based graphic assets in which color is "free"—there is no bandwidth penalty for adding lots of different colors to a Flash site. The downside is that you need to be more careful in managing this high level of choice. Therefore, we will look at several novel ways to manage color or to create sensible palettes quickly.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Video Color Effects
Simulate a video transition using Flash color effects.
This hack alters video using the Color class to create a unique type of color transition. This is not an obvious technique and not one ordinarily applied to video transitions, but that's the whole point of a hack—to explore the nonobvious.
You can always tell when videographers have to create a pop music video with a singer who can't move to the beat in a hip sort of way. In such a case, the videographer moves the camera or adds lots of video transitions and effects that are in sync with the music. That way, you get onscreen movement in time with the beat even if the band is standing hopelessly still and nodding their heads in a 70s prog-rock kinda way.
Flash video poses a similar challenge: video is bandwidth-heavy, and to keep compression ratios as high as possible, we have to create sequences in which not much changes between frames. Most codecs, including the Sorenson codec that Flash uses, perform both spatial and temporal compression. Spatial compression is performed by looking for similarities within the frame (for example, a solid colored background compresses very easily). Temporal compression is achieved by looking at consecutive frames and including only deltas (differences) between the frames. It therefore makes sense to reduce large-scale movement in our videos, allowing the difference frames , which contain only the deltas between frames, to be as bandwidth-light as possible. (For want of a better analogy, difference frames are akin to the tween frames used in animation within Flash's timeline. Video, like animation, has keyframes as well.) Video keyframes are used to maintain image quality and to handle situations in which the differences between frames are so large as to make difference frames inefficient. Therefore, more changes per frame requires either larger difference frames or more keyframes.
This leaves us stuck in the same situation as the pop music video; we can't have too much big movement in our visuals without a massive increase in the download size of the video.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Video Fade to Black and Fade to White
Create fade to black and fade to white video transitions.
Transitions can be applied to both still images and videos. For example, you can apply a color transformation to a video [Hack #8] to create instantaneous color effects. This hack applies a color transformation over time to create fade effects.
For a time-based transition, we need a code structure that allows us to apply incremental changes to the color values over a number of frames. Two common transitions are "fade to black" and "fade to white." The color transform objects you need to end up with an all-black or all-white image are as follows:
transToBlack ={ra:100, rb:-255, ga:100, gb:-255, 
               ba:100, bb:-255, aa:100, ab:0};
transToWhite ={ra:100, rb:255, ga:100, gb:255,
               ba:100, bb:255, aa:100, ab:0};
You will notice that these transforms change only the offset values (to either +255 or -255). The result is that the RGB value R:255, G:255, B:255 is added to each pixel to create a fade to white, or subtracted from each pixel to create a fade to black. Given that the three color channels have a range of 0 to 255 (0x00 to 0xFF in hex), this fades each pixel to either 255 (white) or 0 (black), regardless of the pixel's original color.
The following code gives us a way of spreading this color change over a number of frames to produce a fade over time:
function trans(targetClip, frames, targetTrans) {
  var transCol = new Color(targetClip);
  // Get the current color transform applied to the clip, if any
  var getTrans = transCol.getTransform( );
  var diffTrans = new Object( );
  // Calculate the differences for each of the 8 properties
  // and store them in the diffTrans color object.
  for (var i in targetTrans) {
    diffTrans[i] = (targetTrans[i]-getTrans[i])/frames;
  }
  targetClip.onEnterFrame = function( ) {
    var getTrans = transCol.getTransform( );
    for (var i in diffTrans) {
      getTrans[i] += diffTrans[i];
    }
    transCol.setTransform(getTrans);
    frames--;
    if (frames == 0) {
      // Explicitly set the target transform just in case the 
      // target numbers were not exactly divisible by the 
      // number of frames, then clean up.
      transCol.setTransform(targetTrans);
      delete this.onEnterFrame;
      delete transCol;
    }
  };
}
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
A Custom Color Transform Class
Create a custom class to perform color transformations.
We saw in the preceding two hacks that there are several common color transformations [Hack #8] you may want to perform on a target clip. Furthermore, we saw that this requires a bit of housekeeping, including setting up timers and callbacks [Hack #9]. The nature of the task suggests that it is a great candidate to be implemented as a custom class. The class can take care of all the grunt work, allowing us to perform a color transformation or fade using a few simple calls to the custom class's methods. In this hack, we implement a custom color transform class in ActionScript 2.0 using object-oriented programming (OOP) instead of the procedural timeline-based code seen in the preceding hacks.
Using ActionScript 2.0 requires Flash MX 2004 or Flash MX Professional 2004. You must set the ActionScript Version to ActionScript 2.0 under the Flash tab in the FilePublish Settings dialog box. Furthermore, the custom Transform class we'll develop must be placed in an external plain-text file named Transform.as (both the capitalization of the name and the .as extension are mandatory). You can create and edit such a file in Flash MX Professional 2004 if you select FileNewActionScript File. If using Flash MX 2004, you'll need an external text editor [Hack #74] . The .as file should be placed in the same folder as the .fla file that makes use of the Transform class. For many more details on ActionScript 2.0 classes and object-oriented development, see Essential ActionScript 2.0 by Colin Moock (O'Reilly).
Although we can't give a full course on OOP and ActionScript 2.0 here, this custom color transform class can be used even if you don't understand OOP. And we'll examine several aspects of the code after the code listing.
Here is our object-oriented version, implemented as a custom Transform class, which must be stored in an external
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Create and Organize Custom Swatches
Save and organize your color swatches without having to use the Color Swatches panel.
One of the most important factors in setting the mood and graphic impact of your Flash site is the color scheme. You can save the current palette from the Color Swatches panel as a Flash color set (CLR file). However, incorporating the colors in the Color Swatches panel into your workflow, such as arranging your colors into meaningful groups, isn't easy.
Of course, there's nothing stopping you from creating your own swatches. Simply create a layer called swatches, turn it into a guide layer (using ModifyTimelineLayer PropertiesTypeGuide), and add a few rectangles in which to store your colors. Just as oil painters keep a separate painting area on which to test colors before committing them to the final work, you can create as many ordered swatches as you want. To change or read the color of a particular swatch, use the paint bucket and eyedropper, respectively.
Figure 2-5 depicts storing skin tone and lip colors as a series of swatches outside the Stage area in the FLA document. Because the swatches are on a guide layer, they will not be exported as part of the final SWF.
Figure 2-5: Storing custom swatches off stage in a guide layer
Of course, there is still the problem of getting your colors into Flash in the first place.
The Color Swatches panel contains that aging dinosaur of a bygone era, the web-safe palette. For the most part, the web-safe palette is no longer relevant. If a computer cannot display more than 256 colors, chances are it doesn't support the Flash Player (the exception might be handheld devices).
Furthermore, the web-safe palette is designed to work on hardware that can display a palette based on standard memory sizes (8, 16, or 32 bits). Web-safe colors do not display accurately on computers set to display 24-bit color.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Borrow Color Schemes from Nature
Sample real-world color to capture natural color combinations and schemes.
Using the Color Mixer panel is a rather artificial way of creating new color palettes [Hack #11] . The human eye is relatively poor at discerning color. A dark red set against other dark reds will appear darker if it is viewed around whites and may even appear black. This is to be expected because the human eye has evolved to discern relative differences between currently visible colors and not absolute color.
With this in mind, it is sometimes far easier to choose your color palettes by taking colors from images of real life. For example, Figure 2-9 shows the colors available in a knife blade and flower petals.
Figure 2-9: The scan of a knife blade contains a number of grays in a real-life context, and the flower scans provide real-life vivid colors
Both these images were sampled using an inexpensive flatbed scanner, which is far faster than looking up web-safe color swatches on the Web and less expensive than buying a color process swatch book!
You immediately see the trouble in trying to pick colors from either of these images, though. Adjacent pixel colors are highly variable, so if you try to pick a color from a yellow flower petal, you shouldn't be surprised if you actually sample a light green. To make selecting colors easier, we are better off making the images more friendly to the color picker. We can do this by using some Photoshop filters.
To reduce noise in the sampled image using Photoshop, select FilterNoiseDespeckle. This reduces the problem somewhat, but still leaves us with the problem of accurately selecting colors while maintaining the image as a natural palette. Luckily, we can get to this via a single filter. Select FilterPixelatePointillize. Your image will break up into a series of swatchlike daubs, looking much like an oil painter's paint swatch, as shown in Figure 2-10.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Simulate Sepia Effects
Simulate hue/saturation effects in Flash to create sepia tone images.
Most graphics editing packages, including Photoshop and Fireworks, can change the hue and saturation of an image to create change-of-color effects, such as sepia tone effects. Flash also has this ability, although it is not immediately apparent. This hack shows how to create a sepia effect manually in Photoshop and then convert the workflow to Flash.
Sepia tones imitate the look of so-called sepia prints (a.k.a. albumen prints) produced in the latter half of the nineteenth century using a process invented by Louis-Desiré Blanquart-Evrard in 1850. The dark brown tones commonly associated with an antique look are not due to aging but rather caused by the original photographic development process. See the Royal Photographic Society (http://www.rps.org/book/terms/albumen.html) for more details on albumen prints.
If you are using a graphics editor with built-in support for sepia tone effects, the process is straightforward. For example, you can open the image in Fireworks and choose CommandsCreativeConvert to Sepia Tone.
Here we cover the more general process in Photoshop, so you can create variations beyond sepia tones. With an image open in Photoshop, select ImageAdjustmentsHue/Saturation. The Hue/Saturation window, as shown in Figure 2-12, appears. Check both the Colorize and Preview options.
Figure 2-12: The Hue/Saturation window in Photoshop
Creating a sepia tone image consists of two steps:
  1. Desaturating the image so you are left with a black-and-white image
  2. Colorizing the image with a particular hue (sepia is a deep brown)
You can desaturate the image by setting the Saturation slider all the way to the left, but that's further than we want—we need some color information to remain so we can colorize. Set it to 25.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 3: Drawing and Masking
When we say "drawing" in Flash, we can be talking about two different things. The more traditional form of drawing is freehand vector drawing as used by animators who create Flash cartoons. The other type uses scripts to do the drawing for you, something I like to call "kinetic drawing." In kinetic drawing, not only do the graphics themselves move, but you can also create the graphics in real time, and you might display the interim steps to the user for effect. To draw at runtime, we use the so-called Drawing API, which is just a collection of methods of the MovieClip class including lineStyle( ), moveTo( ), lineTo( ), and beginFill( ), which can be used to create strokes and fills.
For the traditional animator, this chapter includes a number of hacks to address common problems, such as reducing the pixelation around the edges of bitmaps [Hack #23] (which allows you to effectively mix bitmaps with vector content, as well as reducing the appearance of jaggies).
The scripter will find a number of fixes to common Flash problems, such as alpha property inaccuracy [Hack #19] and the bitmap "shifting pixel" problem [Hack #24]. We have also included hacky shortcuts to creating common building blocks when you are creating graphic content dynamically with scripts, such as drawing a circle with just a single straight line [Hack #14].
Drawing in Flash is a crucial ability whether you are a scripter or an artist, so the hacks presented should be some of the most accessible for all Flash users. It should come as no surprise to experienced Flashers that several hacks presented here rely on masks. If you are unfamiliar with masks, refer to the introduction to Chapter 1 for a quick primer.
Creating filled circles at runtime can be processor-intensive. Draw circles using a single straight line for performance and greater flexibility than author-time drawing allows.
Drawing filled rectangles with the Drawing API is relatively easy—you define four corner points and fill the area enclosed by them. Circles are more problematic. You either have to approximate the circle's curvature with multiple straight lines or use the
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Hacks #14-25
When we say "drawing" in Flash, we can be talking about two different things. The more traditional form of drawing is freehand vector drawing as used by animators who create Flash cartoons. The other type uses scripts to do the drawing for you, something I like to call "kinetic drawing." In kinetic drawing, not only do the graphics themselves move, but you can also create the graphics in real time, and you might display the interim steps to the user for effect. To draw at runtime, we use the so-called Drawing API, which is just a collection of methods of the MovieClip class including lineStyle( ), moveTo( ), lineTo( ), and beginFill( ), which can be used to create strokes and fills.
For the traditional animator, this chapter includes a number of hacks to address common problems, such as reducing the pixelation around the edges of bitmaps [Hack #23] (which allows you to effectively mix bitmaps with vector content, as well as reducing the appearance of jaggies).
The scripter will find a number of fixes to common Flash problems, such as alpha property inaccuracy [Hack #19] and the bitmap "shifting pixel" problem [Hack #24]. We have also included hacky shortcuts to creating common building blocks when you are creating graphic content dynamically with scripts, such as drawing a circle with just a single straight line [Hack #14].
Drawing in Flash is a crucial ability whether you are a scripter or an artist, so the hacks presented should be some of the most accessible for all Flash users. It should come as no surprise to experienced Flashers that several hacks presented here rely on masks. If you are unfamiliar with masks, refer to the introduction to Chapter 1 for a quick primer.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Create Filled Circles Quickly at Runtime
Creating filled circles at runtime can be processor-intensive. Draw circles using a single straight line for performance and greater flexibility than author-time drawing allows.
Drawing filled rectangles with the Drawing API is relatively easy—you define four corner points and fill the area enclosed by them. Circles are more problematic. You either have to approximate the circle's curvature with multiple straight lines or use the MovieClip.curveTo( ) method to create a series of arcs. In either case, the trigonometry slows down your code and makes it impenetrable to those of us put off by sines and cosines. Not to worry, there's a far easier way to draw filled circles in Flash—draw a single straight line.
Whenever you draw a straight line, you will notice that the ends of the line are rounded, as shown in Figure 3-1.
Figure 3-1: A short line with rounded ends
So you may be thinking, "Hey, I see what he's getting at. If I draw a line short enough that the two rounded ends touch, I end up with a circle, right?" Sort of. The Pencil and Line tools don't allow you to draw a line short enough, and they limit the line thickness to 10, which doesn't allow you to create large circles. And the whole idea is to draw circles at runtime, so the hack relies on ActionScript to draw very short, very thick lines. Try this:
var clip:MovieClip = this.createEmptyMovieClip("circle_mc", 
                     this.getNextHighestDepth( ));
circle_mc._x = circle_mc._y = 150;
circle_mc.lineStyle(200, 0x0, 100);
circle_mc.moveTo(0, 0);
circle_mc.lineTo(0.2, 0);
The preceding code draws a circle as shown in Figure 3-2.
Figure 3-2: A line so short that the rounded ends form a circle
The circle consists of a single line 0.2 units long but of thickness 200 units. Because the line is so short, Flash draws the two curved endpoints very close together, resulting in a nearly perfect filled circle of diameter 200.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Create Synthetic Art
Instead of downloading large bitmaps or creating predetermined layouts, make Flash generate artwork on the fly.
Just as computers can be made to create songs based on a small set of musical rules, you can make them generate simple images based on a few graphical layout or positioning rules.
As with all creative output coming from a computer though, most of the artistic skill resides within the programmer rather than the machine. In generative art, the trick is to create substantially complete (but interchangeable) sections of a piece and then allow the computer to perform the final placing of the sections to create the complete work.
This hack presents a typical example of this trick by Anthony "Ant" Eden (a.k.a. arseiam): a pop art pattern. It works by creating a grid of randomly nested clips, each of which contains a number of simple shape sections.
Our image is created out of several different shape sections, each of which exists on a keyframe of the movie clip node. Some of our shapes are shown in Figure 3-5. The source file is available as antart.fla on this book's web site.
Figure 3-5: Shapes for our generated art
The following code generates a 12 8 grid of our node clips whenever the user clicks on the Stage and makes each copy go to and stop at a random frame number:
this.onMouseDown = function( ) {
  var depth = 0;
  for (var i = 0; i < 12; i++) {
    for (var j = 0; j < 8; j++) {
      var me = "n" + i + j;
      this.attachMovie("node", me, depth++);
      this[me]._x = 50 * i;
      this[me]._y = 50 * j;
      this[me].gotoAndStop(random(100) + 1);
    }
  }
};
The code creates a random grid of our shapes, which results in patterns such as the one shown in Figure 3-6.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Create Seamless Tiles
Create tiles that mesh seamlessly more easily than you might think. Even nonartists can create repeating tiles using very basic techniques.
Throughout this book, I try to emphasize that you don't need to be an art expert or a music major to create compelling content. Here is a hack that artists and mathematicians alike can appreciate. It shows you how to create graphics that can be used in creating synthetic art [Hack #15] .
The principle for creating tiles that mesh seamlessly is surprisingly simple. Start with a uniform grid of rectangles, squares, triangles, or hexagons, as shown in Figure 3-8, and modify each tile into something more interesting.
Figure 3-8: Dividing a plane into uniform shapes
Let's start with a grid of squares because it is easiest to work with.
To create a more interesting pattern, we can create some negative space by simply cutting out or darkening a given area. To start with a grid of squares, akin to graph paper, you can use Flash's gridlines feature (ViewGridShow Grid and ViewSnappingSnap to Grid ). Now draw a dark circle on the Stage so that it fills one cell of the grid, and duplicate it a few times to fill in all the squares in, say, a 2x2 box area, as shown in Figure 3-9.
Figure 3-9: Using negative and positive space to define seamlessly repeating tiles
You're left with negative and positive space within the 2 2 grid, and you can make either of them into a pattern using the various drawing tools to select and alter fills and strokes, as shown in Figure 3-10.
Figure 3-10: Editing strokes and fills to create varied shapes
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Fill Areas with Patterns
Flash can't fill a nonrectangular area with a custom tile pattern at runtime. But you can fill any shape with a pattern of custom tiles by using masking.
Like most graphics applications, Flash has a Paint Bucket tool that can fill an arbitrary area with a solid color or a gradient. Flash treats the fill as a separate entity from the shape's border (stroke). The Paint Bucket tool uses the fill color specified using the Fill Color swatch in the Colors section of the Tools palette (WindowTools). For example, you can select a gradient fill by clicking on the Fill Color swatch and selecting one of the gradient chips from the pop-up palette.
Furthermore, you can use the Color Mixer panel to customize the gradient for a fill. Simply select a fill using the Selection tool and then choose WindowDesign PanelsColor Mixer. In the Color Mixer panel, you can set the fill type to a Linear gradient or Radial gradient using the pop-up menu in the center of the panel. You can even choose a Bitmap fill, in which case Flash prompts you to select an image to use as a tile to fill the specified area.
Therefore, filling an area during authoring is relatively trivial. Furthermore, you can customize (scale, skew, rotate, and translate) a gradient or bitmap fill using the Tools palette's Fill Transform tool. However, the built-in ActionScript options for specifying fills are more limited. The MovieClip class's fill( ) and beginGradientFill( ) methods, part of the Drawing API, allow you to create solid, linear gradient, and radial gradient fills, but not patterned tile fills at runtime.
Earlier we learned how to create a tile that could be repeated to form a fill pattern [Hack #16] . Let's use our tile to fill different shapes with our custom pattern.
Assuming you have given your tileable movie clip symbol a linkage ID of tilePattern in the Symbol Linkage properties dialog box, the following code generates a rectangular pattern from it:
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Imitate Escher
Create repeating tiles reminiscent of M.C. Escher's artwork.
Repeating tiles need not be limited to simple geometric grids. This hack explores the principles of the divided plane to create complex interlocking tiles.
Even if you're not familiar with M.C. Escher by name, you'll undoubtedly recognize many of the Dutch artist's famous works. We didn't license them for reproduction, but you can find them all over the Web, such as at http://www.mcescher.com. Some of his most popular works make use of divided planes , in which one or more repeated shapes interlock seamlessly. Some of Escher's most famous examples include interlocking birds, fish, and reptiles.
You can Google for "tessellation" or "divided plane" to find many such examples on the Web. ("Tessellation" is just a fancy word for seamless tiling, such as in a checkerboard or mosaic pattern.)
With the negative-space trick [Hack #16] behind us, you may be feeling pretty confident. That technique used a single tile with negative and positive space to simulate a geometric pattern, but the tiles were all square, and the design consisted of simple geometric shapes. What if you want to create an Escher-like repeating pattern that uses complex interlocking shapes? How do we make tiles more interesting than squares and hexagons yet ensure they interlock seamlessly?
The trick to making seamless tiles is to start with a regular shape and modify it into something more interesting. Let's again start with a square because it is easiest to work with.
Draw a square. Convert it a movie clip symbol using F8. Next, tile other square movie clips around it (i.e., arrange multiple instances of the movie clip symbol on stage) so that you end up with a 3x3 grid as shown in Figure 3-18. Double-click the middle clip in the grid to edit it in place.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Fix Alpha Property Inaccuracies
Content preview·Buy PDF of this chapter|