1. Trang chủ
  2. » Công Nghệ Thông Tin

Tài liệu Foundation Flash CS5 For Designers- P15 doc

50 329 0
Tài liệu đã được kiểm tra trùng lặp

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Tiêu đề Foundation Flash CS5 For Designers
Tác giả Group of authors
Trường học University of Fine Arts and Multimedia Technology
Chuyên ngành Design and Multimedia
Thể loại Sách hướng dẫn
Năm xuất bản 2011
Thành phố Hanoi
Định dạng
Số trang 50
Dung lượng 0,99 MB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

Block element styling The authors spent a bit of time studying the tea leaves, and this is what we discovered: officially documented or not, the tags that support element selectors are

Trang 1

CSS

Figure 13-4 CSS styles pulled from an external CSS file

Double-click your newly created StylingExternal.swf file to give it one last look This is a bit like making sure the magician has nothing up either sleeve

Now, open the styles.css document and make a few changes If you are not sure where to start, update the p and strong styles as follows:

p {

margin-left: 100; leading: 12;

} strong {

font-family: Impact; font-size: 40; color: #339966;

} After you make your changes, save the CSS document Then close StylingExternal.swf, and double-click it again to launch the SWF Without republishing the SWF, you’ve updated its formatting (see Figure 13-5) That’s no small feat!

Hey, did you catch that something is missing? What happened to that hyperlink? The increased leading in the p selector has pushed it off the stage! In fact, the phrase Broil to taste has also been shoved

aside No problem All you need to do is to readjust the leading property or decrease the strong selector’s font-size property until everything fits This sort of tweaking is what CSS was made for

We just love telling “war stories” to support what we are talking about In this case, David Stiller, who was one of the coauthors in the CS4 version of this book, had recently completed a Flash-based training presentation for a U.S government agency that featured more than 250 slides At one point, David needed to change the color of one of the heading styles to a slightly different orange He was able to make the change in a single CSS file David tells us he is still smiling

Trang 2

Figure 13-5 Look, ma—style changes without re-creating the SWF!

Block element styling

The authors spent a bit of time studying the tea leaves, and this is what we discovered: officially documented or not, the tags that support element selectors are all block elements, with the exception of the anchor tag (<a>) In other words, the rule of thumb is that, if the tag carries with it a built-in line break, then an element selector will do the trick The special case is hyperlinks, which we’ll cover in detail later in the chapter (hyperlinks are a special case in several ways)

For your reference, let’s take a quick look at a “proof is in the pudding” sample file:

1 Open the ElementSelectors.fla file in this chapter’s Exercise folder You’ll find a text field with the instance name styledContent The ActionScript in the scripts layer shouldn’t be any trouble for you by now A string of HTML is created, element selectors are defined and then assigned to a StyleSheet instance, and finally, the HTML is supplied to the text field

2 Test the movie to see the result in Figure 13-6 The output may not look all that interesting, but it

is, because it demonstrates a few additional “gotchas” while verifying the block element principle

Trang 3

CSS

Figure 13-6 Only block elements—and one exception, anchor tags—support element selectors

3 Click into frame 1 of the scripts layer, and take a look at the ActionScript in the Actions

panel

Each line of HTML ends in a break tag (<br />), just to keep things visually neat Every tag is given an element selector that alternates its color between #0000FF (blue) and #00FF00 (green) In normal HTML, most of these lines would display as either blue or green (<img /> contains no actual text, so it wouldn’t)

In Flash, this holds true only for the block elements

The <a> tag is not a block element, so it does not display an additional, built-in line break as some later tags do But as the exception to the rule in question, the <a> tag does pick up the blue color (mid-gray, in Figure 13-6) from its element selector The <body> and <p> (paragraph) tag contents carry their own additional line breaks—these are block elements—and both display the expected element selector color styling The <ul> and <li> tags’ content is combined These are also block elements and therefore display a combined pair of extra line breaks, as well as the expected element selector styling

4 Comment out the body and li element selectors in the ActionScript by preceding those lines with double slashes (//), as shown in Figure 13-7

5 Test the movie again

Trang 4

Figure 13-7 Commenting out the <body> and <li> selectors leads to a line-spacing quirk and the concept of inheritance

It should come as no surprise that the <body> tag content is no longer styled What may raise your eyebrows is that the extra line break is missing This is a quirk involving only the <body> tag and will raise its head again in the “Custom tags” section of this chapter The other thing to notice is that the <ul>/<li> content has changed color This is because a distinct color style was applied to each tag (green for <ul> and blue for <li>) Blue won the wrestling match earlier because of a CSS concept called inheritance (covered in the “Style inheritance” section later in the chapter)

6 As a final experiment, uncomment the body element selector by removing the double slashes from that line Instead, comment out the p element selector

7 Test the movie a final time, and you’ll see that the <p> content is still blue

Why? Again, this is an example of inheritance, but in a really twisted way Under normal circumstances, HTML documents feature most of their content inside a <body> tag If a style is applied to the body, it will

“trickle down” to tags inside that body if those inner tags happen to support the style properties at hand Here in this Flash file, the <p> content is clearly not inside the <body> content, and yet some phantom inheritance seems to still hold sway Comment out the body element selector one last time, and the <p> content finally turns black

8 Close the file without saving the changes

Every development platform has its quirks, and now you’ve seen a few of the ones that belong to Flash Being aware of these, even if they aren’t burned into your neurons, might just save your hide when something about CSS styling surprises you

Now you’ve had some experience with block elements and the anchor tag, with the understanding that anchor tags still hold a bit of mystery, yet to be unfolded Meanwhile, what remains of the other supported HTML tags? What’s the opposite of a block element, and how can one be styled?

Trang 5

CSS

Inline element styling

In Flash, if a tag is not a block element, it is an inline element There is no “in between,” and all that means

is that it doesn’t carry its own line break with it Examples include the <b> and <i> tags, which apply their own innate formatting—bold and italic, respectively—without otherwise interrupting the flow of text As you’ve seen, inline elements in Flash do not support element selectors Is there another option, then? Yes,

there is But it goes only so far

Not to be confused with the classes discussed in Chapter 4, CSS features something called class

selectors, which differ from element selectors in a significant way Rather than apply their style to all tags

of a specified type, class selectors look only for tags that have a class attribute whose value is set to the name of the class in question We’ll see an example of this in just a moment In HTML documents, just about any tag can be given a class attribute, but this isn’t the case in Flash Actually, nothing stops you from giving an HTML tag such an attribute in Flash, but Flash applies class selector styling to only a few tags, and only one of those is an inline element

Here’s another “proof is in the pudding” exercise, which should make everything clear:

1 Open the ClassSelectors.fla file in this chapter’s Exercise folder At first glance, this file may look identical to ElementSelectors.fla, but click into frame 1 of the scripts layer to lay eyes

on a different chunk of code

You’ll see that every HTML tag now has a class attribute, set either to blue or green, and the number of selectors has been reduced to two: the selfsame blue and green styles Now, how can you tell that these are class selectors and not element selectors? The giveaway, which is easy to miss if you aren’t looking for it, is the dot (.) in front of the style names, which is highlighted in Figure 13-8

Figure 13-8 Class selectors are much more selective than element selectors You can spot them by their

Trang 6

2 Test the movie to see the result

Remember that in the “real world” outside of Flash, every one of these tags would be affected by the relevant style In the SWF, only the following tags do anything: <a>, <li>, <p>, and <span> Unfortunately,

we haven’t found a way to memorize this list as neatly as the other, but if you can remember the block elements that go with element selectors, you need only swap the <body> tag for the <span> tag and drop

<ul> to know the block and inline elements that go with class selectors (Yeah, we agree, it’s not especially intuitive.)

3 For the sake of completeness, comment out the green class selector, and test the movie to verify the outcome The <ul>/<li> content turns black, because class selectors don’t apply to

<ul> tags in Flash

4 Close the movie without saving the changes

Custom tags

Ready to head back to the street food? When we abandoned it to venture out on our educational tangent, our styling had been applied, with the exception of the <b> content, and now we know why The <b> tag is not a block element, which means it simply doesn’t support element selectors

Element selectors affect all tags of a given type, and for the sake of illustration, let’s say we want only this recipe’s title to stand out, rather than all content that happens to be set in bold An obvious solution, based

on your current knowledge, is to swap the <b> tag for something that supports class selectors Let’s try it

1 Open the Styling03.fla file in this chapter’s Exercise folder to see an example of using a class selector The key changes in the ActionScript from Styling01.fla are shown in bold in the following code:

<strong>, and so on) Flash happily accepts these as “custom” tags, because, in its skimpy repertoire, they are

Trang 7

css.setStyle("strong", {fontFamily: "Impact", fontSize: "16", color: "#339966"});

styledContent.styleSheet = css;

Note the absence of a dot preceding the strong element selector, which means that this is not a class

selector! If you put 50 <strong> tags full of content into your SWF, all 50 occurrences will pick up the style from this setStyle() method That said—and we can’t stress this enough—please understand that this is not a magical, undocumented way to squeeze additional tags out of Flash’s limited HTML support Flash has no idea what a <strong> tag is, much less that most browsers treat it like a tag This is nothing more than a convenient hook for CSS—an excuse to dodge class selectors if you happen not to like them In fact, to prove it and to reveal a limitation of the custom tag approach, proceed to step 3

3 Replace the <strong> tag in the bolded ActionScript with the completely made-up <citrus> tag There is no such tag in any of the W3C specifications (we looked) Your code will change in only three places:

Trang 8

Figure 13-9 Whoops, something isn’t right with the fruit juices

Danger, Will Robinson! What do we learn from the broken Fruit juice line? A valuable lesson, that’s what The recipe’s title is fine, but that’s because it stands on its own The fruit juice line breaks because custom tags become block elements when styled In this case, the word juice has even been

pushed past the extra line height given earlier to the <ul> tag

We’ve spent the last several miles mulling over some pretty arcane rules and even hazier exceptions to them CSS was supposed to be easier in Flash, right? If your head is spinning, take a break While you wait, one of the authors will use a chant from the “L’Eglise CSS.” It goes something like this: “To get the biggest bang for your buck, use element selectors first, then custom tags for headings and other short or specific blocks, and finally class selectors for special cases.” (Take our word for, this sounds really great

as a Gregorian chant.)

Style inheritance

In moving from Object instances to the object shortcut characters ({}) earlier in the chapter, we saw one way to trim CSS into a more compact form There’s another way to shrink things even further, but it’s more

conceptual than syntactical The concept is called inheritance, and it basically means that styles applied

“up the creek” tend to eventually flow down to lower waters

Let’s look at a concrete example Open the Inheritance.fla file in this chapter’s Exercise folder You’ll see a text field with the instance name styledContent Click into frame 1 of the scripts layer to view

Trang 9

CSS

the ActionScript As with the other samples in this chapter, the code begins by building an HTML string In this case, the structure of the HTML tags is important Stripping out the text content, the structure of the tag hierarchy looks like this:

in Arial, as its parent does (see Figure 13-10)

Figure 13-10 CSS inheritance in action

This sort of procedure can get fairly sophisticated For example, the custom <outer> tag adds italics to the mix

css.setStyle("outer", {fontStyle: "italic"});

In light of that, and because the flow goes downhill, <mid>, <inner>, and <span> inherit not only the font

of <outer>’s parent but also its italics Meanwhile, sibling tags (<p>) and parent tags (<body>) do not And honestly, that makes good sense

In the same vein, the custom <mid> tag introduces bold:

css.setStyle("mid", {fontWeight: "bold"});

If unopposed, <inner> and <span> would inherit that bold styling as well, but <inner> purposely overrides that by setting fontWeight to normal in its own element selector:

Trang 10

css.setStyle("inner", {fontFamily: "Arial", fontWeight: "normal"});

In turn, this causes <span> to inherit the override, because it too ignores the bold Note, however, that

<span> does inherit the italics, which were not overridden by a parent tag The interesting thing is that the

<span> content inherits styling applied to its parents, even though that styling is provided by element selectors Why is this interesting? Remember that <span> is an inline element, and inline elements, as a rule, can’t be styled with element selectors Oh, the tangled web Flash weaves!

Use this inheritance phenomenon to your advantage It saves you keystrokes You don’t need to specify font families for whole groups of related tags In addition, inheritance gives you the opportunity to make sweeping changes from relatively few locations As you’ve seen from the quirky exceptions, though, you’ll want to experiment carefully before committing yourself to a particular styling scheme But do make sure you experiment, because there’s more to Flash CSS than first meets the eye

Styling hyperlinks Anchor tags are fun to style because of something called pseudo-classes In CSS-speak, a pseudo-class

corresponds to various possible states of an HTML element and is indicated by a colon (:) prefix In Flash, the only supported pseudo-classes are associated with the anchor tag (<a>) and correspond to the following states:

 :link (an anchor tag that specifically contains an href attribute)

 :hover (triggered by a mouse rollover)

 :active (triggered by a mouse click) The long and short of this is that you have the tools you need to create different anchor tag styles that update as the mouse moves and clicks your hyperlinks Note that Flash does not support the :visited pseudo-class, which in normal CSS indicates that a hyperlink has already been clicked

Think of pseudo-classes as a second tier of styles, not separated by hierarchy, as shown in the “Style inheritance” section, but instead separated by time or events

Open the Hyperlinks.fla file in this chapter’s Exercise folder to see an example in action The ActionScript begins, as always, by establishing an HTML string:

var str:String = "";

str += "<ul>";

str += "<li><a href='http://www.apress.com/'>Hyperlink 1</a></li>";

str += "<li><a href='event:someFunction'>Hyperlink 2</a></li>";

Trang 11

css.setStyle("a", {fontFamily: "Courier"});

css.setStyle("a:hover", {fontStyle: "italic"});

css.setStyle("a:active", -{text-decoration: "underline",color: "#FF0000"});

styledContent.styleSheet = css;

Test this movie to verify that hovering over hyperlinks puts them temporarily in italics, and that clicking omits the italics but additionally displays an underline and new color The italic style isn’t inherited by :active, because :active is not a child of :hover; they have a sibling relationship The Courier typeface, however, appears for all states, because even the pseudo-classes are anchor tags

What if you would like more than one style for your hyperlinks? The solution is to use a class selector Open the HyperlinksVaried.fla file in this chapter’s Exercise folder for an example First, here’s the new HTML (shown in bold):

var str:String = "";

str += "<ul>";

str += "<li><a href='http://www.apress.com/'>Hyperlink 1</a></li>";

str += "<li><a href='event:someFunction'>Hyperlink 2</a></li>";

var css:StyleSheet = new StyleSheet();

css.setStyle("li", {leading: "12"});

css.setStyle("a", {fontFamily: "Courier"});

css.setStyle("a:hover", {fontStyle: "italic"});

css.setStyle("a:active", {textDecoration: "underline",

color: "#FF0000"});

css.setStyle(".oddball", {color: "#00FF00"});

styledContent.styleSheet = css;

Trang 12

Figure 13-11 The last three hyperlinks are in a different color (gray here; green in real life)

Close the open files, and let’s now look at embedding fonts

Embedded fonts

Before we take what we’ve learned and nudge it all toward an external CSS file, let’s make a quick stop as

we buy a sausage on a stick to talk about embedded fonts CSS in Flash requires HTML, which in turn requires a dynamic text field if you are using Classic Text As you learned in Chapter 6, only static text fields embed font outlines by default, which explains why Flash has been chattering about embedding

fonts in the Output panel This means that unless you purposely embed your fonts—and the choice is

yours—text in CSS-enhanced SWFs tends to have a jagged look

Font symbols were introduced in Chapter 6, but there’s a new twist in how they’re used with CSS To recap, the font-embedding process is as follows:

 Add a font symbol to the library and associate it with the desired font on your system

 Enable the font symbol’s linkage by exporting the symbol for ActionScript

 Use the Font Embedding dialog, which is accessed through the Properties panel

The new part—because Flash CSS usage requires ActionScript—is that you must refer to the font’s actual name in your setStyle() method The tricky part is how to reference the font’s actual name, because neither its symbol name (in the library) nor its linkage class name necessarily provides any clues

Naturally, you can find out the font’s actual name by consulting the Font Symbol Properties dialog

box, but why rope yourself into something hard-coded? If you choose to associate your font symbol with another font, you’ll need to change the font’s name in your code, unless you use the Font.fontName property instead Here’s how:

1 Open the StylingEmbeddedFonts01.fla file in this chapter’s Exercise folder Test the movie, and you’ll see jagged fonts Let’s change that

Trang 13

CSS

2 Click into frame 1 of the scripts layer, and note the following pertinent lines of code:

var css:StyleSheet = new StyleSheet();

css.setStyle("li", {fontStyle: "italic", color: "#FF0000", leading: "-2"});

css.setStyle("p", {textAlign : "justify", leading:"6"});

css.setStyle("ul", {leading:"4"});

css.setStyle("strong", {fontFamily: "Impact", fontSize: "16", color: "#339966"});

styledContent.styleSheet = css;

styledContent.htmlText = str;

3 Look at the strong element selector, and you’ll see that the fontFamily property is set to

Impact, which is represented in the Library by a font symbol named Impact Right-click (Windows) or Control+click (Mac) the Impact font symbol, and select Properties to open the

Font Embedding dialog box

4 In the Font Embedding dialog box, verify that the actual font selected is Impact (If you don’t

have Impact on your system, choose some other suitable headline typeface.) Also verify that the

font symbol is exported for ActionScript by clicking the ActionScript tab and that its linkage class name is Impact, as shown in Figure 13-12 Then click OK to close the dialog box

Figure 13-12 The font symbol’s linkage class name is Impact

Trang 14

Referring to the actual font name—Impact (or your replacement)—will do, but you don’t want to be tied to that changeable value Instead, you’re going to create an instance of this particular font—an instance of the custom Impact class—and reference that the Font.fontName property of that instance You’ll also set the TextField.embedFonts property of the styledContent instance to true

5 Update the ActionScript as follows (new code in bold):

var embeddedFont:Impact = new Impact ();

var css:StyleSheet = new StyleSheet();

css.setStyle("li", {fontStyle: "italic", color: "#A2A2A2",

6 Test your movie, and the text magically appears

Oddly, only the <strong> element is showing! But hey at least the lettering is smooth, as you can see from the inset Only the <strong> element is showing because this text field is being asked to display

more than one font: Impact and Arial (the text field’s Property inspector settings specify Arial) Both

fonts need to be embedded

7 Using the technique described in Chapter 6, add an Arial font symbol to your library, and name

the symbol whatever you like Make sure to export it for ActionScript To prove that neither the symbol name nor the linkage class name makes any difference, name your linkage class something absurd, like HornyToads You don’t need to create a HornyToads instance in this case, because nothing in the ActionScript refers to that font by name (again, it’s the text field itself

that’s set to Arial in the Properties inspector)

8 Compare your work with StylingEmbeddedFonts02.fla in the Complete folder, whose font

symbol is named HornyToads in both the Library and the linkage class

9 Test your movie to confirm that all of the text content shows, and without jaggies But there’s still one problem Can you spot it? Those <li> elements are supposed to be in italics!

10 To get the italics to show, you need to add a second Arial font symbol, this time with Italic selected in the Style drop-down list Repeat step 7, making sure to specify the italic variant of Arial, and name your symbol (and class) something like HornyToadsItalic The

StylingEmbeddedFonts02.fla file in this chapter’s Complete folder demonstrates this for you

11 Test your movie, and you’ll finally see everything, as shown in Figure 13-13, as it should be: all typefaces accounted for and smooth, including the italic variant

Trang 15

CSS

Figure 13-13 All the text is accounted for, and none of it suffers from the jaggies

Selectors vs the Properties panel It’s imperative that you understand how important the Properties panel settings are in the previous

examples The only reason you need to instantiate the custom Impact class—as opposed to both that and

HornyToads (Arial)—is that Arial was already selected as the text field’s font in the Properties panel

Take a look at StylingEmbeddedFonts03.fla in this chapter’s Complete folder for a working example of

how to reference more than one font in the ActionScript You’ll see that the text field’s Properties panel settings have been changed to Times New Roman That means the Arial typeface (HornyToads), along

with its italic variant (HornyToadsItalic) are present in the SWF but are not actually referenced anywhere Here’s the operative ActionScript to ensure that they do get referenced (new code in bold):

var embeddedImpact:ImpactNormal = new ImpactNormal();

var embeddedArial:HornyToads = new HornyToads();

var css:StyleSheet = new StyleSheet();

css.setStyle("li", {fontFamily: embeddedArial.fontName,

fontStyle: "italic", color: "#A2A2A2", leading: -"-2"});

css.setStyle("p", {fontFamily: embeddedArial.fontName,

textAlign: "justify", leading: "6"});

Trang 16

In this version, the variable that holds the Impact instance has been renamed to embeddedImpact, just to differentiate it from the second scripted font reference, HornyToads (the embeddedArial variable) This solution makes use of CSS inheritance, because it specifies the embeddedArial instance only where it’s necessary Because the anchor tags (<a>) are nested inside the <p> tags, the p element selector takes care of both The li element selector is needed because the <li> tags don’t appear inside a tag styled for the embedded font Note that, although some selectors call for a fontStyle of italic, Flash is smart enough to understand, without a third font variable, that HornyToadsItalic is the italic variant of the HornyToads font

What you have learned

In this chapter, you discovered that the CSS techniques widely employed in the HTML universe are just as applicable to your Flash efforts As you moved through the chapter, you learned the following:

 How to apply CSS styling through ActionScript

 The difference between an element selector and a class selector

 That you can create your own custom tags

 How to use the concept of inheritance to your advantage

 How to reference embedded fonts in your code and the fact that the Properties panel may

help you avoid it

 How to use an external CSS style sheet in Flash

If there is one major theme running through this chapter, it is this: your CSS skills put a powerful tool in your arsenal Speaking of powerful tools, let’s build some stuff and give your new Flash skills a bit of a workout

Trang 17

Chapter 14

Building Stuff

Up to this point in the book, you have created quite a few projects using images, text, audio, video, and other media We bet you’re feeling pretty good about what you’ve accomplished (you should!), and, like many who have reached your skill level, you are wondering, “How does all of this hang together?”

In this chapter, we will bring together the various skills and knowledge you have developed and use them

to create some rather interesting projects We are going to start slowly and show you how to build a preloader, and then we’ll move through a slide show, MP3 player, and full-bore “Whack-A-Bunny” game designed for use on an Android device and as an AIR app Some of these are quite complicated projects, but if you have reached this point in the book, you are ready to develop some Flash “chops” and explore what you can do with your newfound skills

Here’s what we’ll cover in this chapter:

 Understanding how Flash movies are streamed to a web page

 Using the Bandwidth Profiler to turbo-charge movies

 Optimizing Flash movies

 Converting a Flash movie to a QuickTime video

Trang 18

 Choosing web formats

 Publishing a SWF for web playback

 Dealing with remote content

 Using the new AIR for Android features The following files are used in this chapter (located in Chapter14/ExerciseFiles_Ch14/Exercise/):

That last item—a folder named Build More Stuff—contains a bunch of projects that didn’t make the cut for this chapter They either were used in previous editions of this book or were things we thought you would find interesting but space requirements precluded us from fully documenting them in this chapter What we have done is to provide you with heavily commented source code files Feel free to study them, take them apart, dissect them, and adapt them for your personal use

Trang 19

BUILDING STUFF

Loading content

Flash has a potentially bad habit that drives people crazy In cases where everything in a movie is packed into the first few frames—and especially in single-frame movies—the SWF can take an awfully long time to display Why? Because Flash Player loads content one frame at a time, and when a SWF’s first frame is

heavy, the rest of the movie suffers It’s even more interesting in cases where Export for

ActionScript is selected for Library assets, because those items are included in the movie’s first

frame, in a behind-the-scenes way, even if you don’t place them there yourself (Flash does it for you automatically) This should explain to you why, when you hit certain websites, you’re slugged with an interminable wait, involving fingers drumming on the mouse or your desk and audible sighs as you wait for the movie to start

One useful solution is to remove your heaviest assets—large images, audio, and video files—and use ActionScript to load them at runtime This way, the rest of your content—the lighter stuff, including text and vector artwork—displays almost immediately, while the heavy stuff streams into the SWF from your server Just keep in mind that even the light stuff may need a few seconds to load But at least your audience will

be looking at something, such as a preloader, and even the mere perception of at least something happening works wonders

Are we there yet?

This first example is probably one of the most common preloaders in existence: the user is told how much

of the SWF has loaded In this example, a ribbon twirls while the numbers increase to show us loading progress Let’s get started:

1 To see how all of this works, open the preloader1.fla file in the Exercise/Preloader folder for this chapter You’ll see there’s a single movie clip and a text box on the stage; this movie

clip—loaderAnim—is the only one in the Library The graphic symbol—gradientHalf—s

the ribbon in the movie clip, and we have included a Font symbol for those of you who don’t

have the Impact font installed on your computers The last symbol—IMG_0098.jpg—is a photograph of a dog This is the content that will put the preloader to work

2 Select frame 2 on the main timeline, and you will see the image of a rather large dog The word

large is important because, if you double-click the image in the Library to open the Bitmap Properties dialog box shown in Figure 14-1, you will see the image has a rather large file size, not to mention that its physical dimensions—1600 by 1200 pixels—are far larger than the stage Used as a starting point, this is a great example because it gets you to shift your thinking of the image in frame two from “Wow, that is a huge dog” to “Uh-oh, this content is going to be a problem.” This image is going to take a lot of time to load But don’t think it’s just images; that image could be anything from a video to an audio file to even another SWF, so it is not the dog that is the problem; it is the content

Trang 20

Figure 14-1 If it’s big, it needs time to load

3 Open the gradientHalf graphic symbol in the Symbol Editor This symbol was constructed

by simply using the Pen tool to draw half of the shape and to fill it with a gradient It was copied

and “flipped” to make the ribbon This object was then converted to the loaderAnim movie clip

4 Open the loaderAnim movie clip in the Symbol Editor The “twirl” was constructed by adding the keyframes and, using the Transform panel, rotated by 90 degrees, as shown in Figure 14-2,

between the first two keyframes The rotation amount was increase by 45 degrees between the keyframes at frames 11 and 15, which means the symbol rotates thorough 180 degrees over a span of 15 frames Classic tweens were used because we were tweening a graphic symbol

Trang 21

var bytestotal:int = stage.loaderInfo.bytesTotal;

var bytesloaded:int = stage.loaderInfo.bytesLoaded;

Trang 22

var percent:int = Math.round(bytesloaded*100/bytestotal);

percentText.text = percent + "%";

if (bytesloaded >= bytestotal) {

gotoAndStop(2);

removeEventListener(Event.ENTER_FRAME, preloading);

} } The code starts off by loading in the Event class and stopping the playhead on frame 1 By stopping the playhead, you are going to give Flash time to keep an eye on how that image in frame 2 is loading and to let the user know what is going on That process starts with the EventListener in line 3

The function named preloading is where the “magic” happens

When content loads it is not the image, sound or video that loads, it is the data in that content that loads Though we traditionally use the kilobyte as the measurement, Flash gets even more granular and uses the bytes in the content as its base This explains the three variables: bytestotal, bytesloaded, and percent (note that we have used a lowercase l for bytesloaded because the camel case version

(bytesLoaded) is a Flash keyword) Flash knows the value of the first one—you saw it in the Bitmap

Properties dialog box—and, as the movies play, it keeps track of the bytes loading into Flash Player The percent variable takes those two numbers, divides them, strips off the decimals, and, in the fourth line, makes that number the value of the text in the text box

The if () statement is there to tell Flash how to stop calculating and what to do when it has finished with the calculation The parameter—bytesloaded>=bytestotal—is a little programming trick that tells Flash

to do something when the bytesloaded value equals or exceeds the bytestotal value We know the bytesloaded value can’t exceed the bytestotal value, but adding the > (greater than) symbol makes sure this is the case

The rest of the code tells Flash to hop over to frame 2, stay put, and forget about the EventListener

7 Test the movie

You will most likely get a brief glimpse of the preloader, and then the image appears Surely, that image didn’t load that fast? In fact, it did, but what you may not know is the reason for it loading so fast is because you are testing the movie on your computer Here’s how to get a more accurate look at this project

8 With the SWF playing, select View Simulate Download, as shown in Figure 14-3 This

choice allows you to simulate performance when content is delivered through a modem You should now see the numbers start to change

We are going to do a deep dive into Simulate Download in the next chapter For

now, just work along with us

Trang 23

BUILDING STUFF

Figure 14-3 Use Simulate Download to check out performance through a modem

Somebody stole my preloader

In Chapter 11 we showed you how to use the ProgressBar component It is a useful component but contains very little “eye candy.” This project shows you how to “roll your own” progress bar but add a bit more jazz to the preloading process by replacing the bar with the animation of a thief fleeing from the scene of the crime Here’s how:

1 Open the preloader2.fla file

How this preloader works is rather simple As the overly large cow image in frame 2 loads into the SWF, the thief runs from one side of the screen to the other This preloader uses the width of the Flash stage as the width of the bar, and, as the content loads, the thief’s horizontal position on the stage matched the percentage of the content that has loaded

The drawing of the thief was created in Adobe Illustrator, and Illustrator’s layers were used for the various running positions These positions were imported into Flash as movie clips, and if you

open the runnerAnimation movie clip in the Library, as shown in Figure 14-4, you can see how

the animation was created The animation is in its own layer on the main timeline and has the

instance name of thief

The streetscape was created using the Pen tool in Flash What you can gather from this is that

combining the tools and applications available to you is always an option

Though this is a rather interesting way of creating a preloader, always keep in mind that it, too, must be small for it to load fast This means keeping everything as simple as possible

Trang 24

The authors would like to thank Pascal Baumann for creating this exercise for use in the book Pascal is a self-employed creative director from Zurich, Switzerland, currently living in Bangkok, Thailand His work can be seen at www.pascalbaumann.com

Figure 14-4 A simple animation can be used as an engaging preloader

2 Click once in frame 1 of the Actions layer, and enter the following code:

import flash.events.Event;

stop();

addEventListener(Event.ENTER_FRAME, myloading);

function myloading(evt:Event) {

var bytestotal:int = stage.loaderInfo.bytesTotal;

var bytesloaded:int = stage.loaderInfo.bytesLoaded;

var percent:int = Math.round(bytesloaded*100/bytestotal);

thief.x = stage.stageWidth / 100 * percent;

if (bytesloaded >= bytestotal) {

gotoAndStop(2);

removeEventListener(Event.ENTER_FRAME, myloading);

} }

Trang 25

BUILDING STUFF

The myloading function is remarkably similar to the previous example The major difference here

is the movement of the thief across the stage The thief instance’s x property is determined by the width of the stage Its position at any one time is simply set by multiplying the result of the percent variable by 100 and dividing the width

of the stage by that number Once that is determined, the thief instance is sent to that position on the x-axis

3 Test the movie, and select Simulate Download while the SWF is playing The thief, as shown

in Figure 14-5, runs across the stage, and when he moves off the right side of the stage, the cow image appears

Figure 14-5 Preloading is almost complete

Building a slide show with components and XML

The popularity of websites like Flickr and Photobucket prove that people like to share photos Of course, this was true even before the Internet But modern technology makes it easier than ever to whip out that tumbling, unfolding wallet and proudly show off all the kids, aunts, uncles, cousin Ed, and Finnegan, not only to friends but to every human on the planet At the rate most people take pictures, photo collections just keep growing So, if you were to make a photo slide show in Flash, you would want to be sure it was easy to update With components and XML, that goal is closer than you may think

To explore the concept, we’ll start in an interesting location: the Quanjude Roast Duck Restaurant in Beijing, China During the course of writing this book, one of the authors was in Beijing One night, he was enjoying dinner in the company of a couple of Adobe engineers, John Zhang and Zhong Zhou Naturally, one of the dishes was duck and, because of the restaurant’s history, there was a particular way in which the duck was served and to be consumed The author was struggling, and Zhong Zhou called the waitress over to demonstrate the proper (and complex!) procedure It involved a wafer-thin wrap, duck meat, sauces, scallions, and a couple of other treats, which were to be added in a particular order It took a

Ngày đăng: 15/12/2013, 01:16