Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

Beginning ActionScript 2.0 2006

.pdf
Скачиваний:
104
Добавлен:
17.08.2013
Размер:
12.47 Mб
Скачать

Chapter 18

1.

2.

Open a new FLA and save it as scrollFieldTest.fla.

Select the first frame and enter the following code in the Actions panel:

var my_format:TextFormat = new TextFormat(); my_format.font = “myFont”;

my_format.size = 12;

var id:Number = this.getNextHighestDepth();

var field1:TextField = this.createTextField(“field” + id, id, 20, 20, 300, 150); field1.border = true;

field1.wordWrap = true; field1.multiline = true; field1.antiAliasType = “advanced”; field1.embedFonts = true;

field1.text = “Ipsum Lorem da dayem Ipsum Lorem da dayem Ipsum Lorem da dayem Ipsum Lorem da dayem Ipsum Lorem da dayem Ipsum Lorem da dayem Ipsum Lorem da dayem Ipsum Lorem da dayem Ipsum Lorem da dayem Ipsum Lorem da dayem Ipsum Lorem da dayem Ipsum Lorem da dayem Ipsum Lorem da dayem Ipsum Lorem da dayem Ipsum Lorem da dayem Ipsum Lorem da dayem Ipsum Lorem da dayem Ipsum Lorem da dayem Ipsum Lorem da dayem Ipsum Lorem da dayem Ipsum Lorem da dayem Ipsum Lorem da dayem Ipsum Lorem da dayem Ipsum Lorem da dayem Ipsum Lorem da dayem”;

field1.setTextFormat(my_format);

3.Test the code by selecting Control Test Movie. You should now see a simple text field on the stage. Close the SWF and add the following code below the code you entered in step 2:

var id:Number = this.getNextHighestDepth();

var scrollbar1:MovieClip = this.createEmptyMovieClip(“clip” + id, id); var square:Number = 10;

scrollbar1.beginFill(0xCCCCCC, 100); scrollbar1.moveTo(-square, -square); scrollbar1.lineTo(-square, square);

scrollbar1.lineTo(square, square); scrollbar1.lineTo(square, -square); scrollbar1.lineTo(-square, -square); scrollbar1.endFill();

scrollbar1._x = field1._x + field1._width + (scrollbar1._width / 2); scrollbar1._y = field1._y;

4.Test the code by selecting Control Test Movie. A gray square appears at the top-right corner of the text field.

5.Close the SWF and enter the following code below the code added in step 3:

scrollbar1.startPosition = scrollbar1._y; scrollbar1.onPress = function()

{

this.startDrag(false,this._x,this.startPosition,this._x, ; this.startPosition+field1._height);

clearInterval(this.scrolling);

this.scrolling = setInterval(this, “scroller”, 10);

};

scrollbar1.onRelease = scrollbar1.onReleaseOutside = function()

{

clearInterval(this.scrolling);

this.stopDrag();

468

Handling Text

};

scrollbar1.maxSize = field1._height; scrollbar1.scroller = function()

{

var percentPosition:Number = (this._y-this.startPosition) / this.maxSize; trace(1+int(percentPosition+field1.maxscroll)+” “+field1);

field1.scroll = 1+int(percentPosition*field1.maxscroll); updateAfterEvent();

};

6.Test the code by selecting Control Test Movie. Drag the gray square up and down to scroll the text within the text field.

How It Works

This example takes a minimal approach. By using the maxscroll and scroll properties of a text field, the field can be easily scrolled. The result appears jagged because the text is bumped line by line into position within the text field; you might prefer the mask method in the previous Try It Out.

However, this method does present the fullest freedom in design and behavior while retaining classic text field scroll behavior.

As mentioned earlier, creating your own scroll mechanism is fraught with usability issues, and care should be taken when defining the behavior of a scroll bar.

Summar y

In this chapter you learned about the TextField class, the different types of text fields, their uses, and how to create them with ActionScript. You can, of course, create text fields using the Text tool in the Tools palette, but that’s a limiting way of introducing text when working with ActionScript.

This chapter also examined the different methods for formatting text to display rich text within text fields. The TextFormat class was presented as a fast and simple way to highlight text as well as quickly define styles for a text field. antiAliasType also was introduced, along with its advantages over the method of anti-aliasing text in older Flash players.

Shared fonts were discussed, as were robust skinning alternatives when dealing with text content. CSS was also explored and you learned how to modify text within a text field for rich text formatting.

You tried out different methods for scrolling text, some easy and some more advanced, and saw the advantages and drawbacks to each.

All of this adds up to very robust text support in Flash, with far more control and design possibilities than its HTML counterpart in the browser.

469

Chapter 18

Exercises

1.Using the ASFunction method, control an SWF file presented within an HTML field with an

<img> tag.

2.Using the code in exercise 1, apply a style sheet to the <a> tag, which contains the ASFunction URL.

3.Using XHTML content, define what Flash should do when it finds a div tag using CSS.

4.Using text span methods, allow the user to select a span of text and change one or more TextFormat properties for that span only.

470

19

Using ActionScript for Media

In the preceding chapter you learned how Flash displays and manipulates text. Now you examine something that’s a bit more visually stimulating for your viewers. Flash is, after all, a multimedia platform. With ActionScript, you have unprecedented control of media and media integration.

Media can include images, video, sound, and input such as cameras and microphones. You can, of course, integrate these pieces on the stage, on a timeline, and with the Flash drawing tools. However, ActionScript provides you with a robust set of objects, methods, and events for displaying and handling media for a rich media user experience.

In this chapter, you explore loading images, sound, and the microphone, and learn to use them efficiently.

Managing Images

Images are everywhere on the web. They come in all sizes and formats you can think of. You have long been able to load many image types into HTML pages. Since the introduction of JPG loading in Flash 6, you have been able to load a popular image format directly into Flash, giving you incredible freedom in terms of displaying content and working with existing media as well as skinning your applications. With Flash 8, this has advanced even further. You can now load JPG, GIF, and PNG files directly into a movie clip. JPG images are no longer limited to non-progressive .jpg format allowed in Flash 6. GIF images can be transparent and animated, or can be static. PNG images can be transparent, 8 bit, or 24 bit.

Loading an image is as simple as loading an SWF file and, in fact, uses the same methods to accomplish the task. You use loadMovie() to load images into existing movie clips, as well as to load images into movie clips created with ActionScript.

This is very good news for almost all Flash developers because it allows Flash applications to more easily integrate with existing image databases without server-side conversion of the image to an acceptable format.

Chapter 19

Unlike data files and SWF files, there are not many security issues with loading images. You can load them from any domain, without setting any security methods.

Remember that images are often copyrighted. Be sure that you have the right or permission to show an image before displaying it in your application.

Preloading images is the same as preloading an SWF file loading into a movie clip. In this chapter’s examples, you use the setInterval() method to watch the bytes loading and display the image. Because you are loading directly into a movie clip, calling getBytesLoaded and getBytesTotal on the clip into which the image is loading returns byte values just as you would expect.

Sometimes an image may seem to load 100 percent, but fails to appear for various reasons. Because of this, an interval or loop event should check a valid property of the movie clip that has changed since the image loaded. Often, most developers watch the height or width property of the movie clip, because it is a definite indicator that the movie clip has not only loaded the image data, but has successfully displayed it.

Try It Out

Placing an External Image into a Movie Clip

In this example you load a PNG. However, you can change the target image to whatever image you want. Try images from various domains.

1.Open a new Flash document and save it as imageLoadTest.fla in your work folder.

2.Click the first frame in the timeline, open the Actions panel, and type the following ActionScript code:

this.createEmptyMovieClip(“test”,0);

this.test.loadMovie(“test.png”);

3.Be sure your image is available and at the path specified. Test the movie by pressing Ctrl+Enter. You will see the image load into your movie in the top-right corner.

How It Works

In this example you created a movie clip and then used loadMovie() to specify an image that should occupy it. However, you didn’t watch it load, and you had no indication of whether the image was available to manipulate, position, or work with.

If you simply needed to display it as is, you wouldn’t need to do much more, but you usually want to place an image in a specific area, or with specific attributes.

You need to add an interval to watch the test movie clip load and to act upon the image.

A load listener is a function that is repeated over a course of time. It can be an interval, or an enterFrame event, running on a different movie clip than the clip the image is being loaded into. The function that is repeated checks the getBytesLoaded and getBytesTotal properties of the target object. You can use those two properties not only to determine the success of the image load, but also to indicate to the user that Flash is working and loading an image.

472

Using ActionScript for Media

Smart Preloading

If you are familiar with JavaScript you know that it is often helpful to preload images at the start of an application. This makes image presentation smoother and often enables you to do things with multiple images that otherwise might not be possible unless you know each are preloaded.

With Flash, the operation of preloading an image is very similar to JavaScript. You call the image into a hidden field and simply remove it. At this point the image is cached locally, and Flash can quickly receive it without much load time at all. As well, if the user has his cache turned off, you simply keep the images offstage until you need them.

Another consideration of smart preloading is that when images are cached, your pre-loader should be smart enough to simply display the image without displaying a pre-loader progress bar or textual percentage indicator, because the pre-loader at that point is redundant.

Using the MovieClipLoader to Preload an Image

Chapter 8 describes the MovieClipLoader class. Luckily, you can use that same class and events to preload a static image. If you are targeting Flash 7 or newer, you can use MovieClipLoader to load images as well as SWF files.

In the following Try It Out, you use the loading of an image to trigger an event.

Try It Out

Firing an Event on Load of the Image

1.Open a new Flash document and save it as imageClipLoaderTest.fla in your work folder.

2.Click the first frame in the timeline, open the Actions panel, and type the following ActionScript:

var id = this.getNextHighestDepth();

var clip = this.createEmptyMovieClip(“mc”+id, id); var mcOnLoadHandler:Object = new Object();

mcOnLoadHandler.onLoadInit = function(clip_mc:MovieClip) { trace(“ok”);

};

var mcLoader:MovieClipLoader = new MovieClipLoader(); mcLoader.addListener(mcOnLoadHandler); mcLoader.loadClip(“logo.gif”, clip);

3.Test your movie by pressing Ctrl+Enter. You will see the image load and the word ok will appear in the output panel.

4.Close the SWF file and return to the first frame actions.

5.Add some ActionScript to the onLoadInit function to manipulate the size of the image:

var id = this.getNextHighestDepth();

var clip = this.createEmptyMovieClip(“mc”+id, id); var mcOnLoadHandler:Object = new Object();

mcOnLoadHandler.onLoadInit = function(clip_mc:MovieClip) { clip_mc._xscale = clip_mc._yscale = 150;

};

473

Chapter 19

var mcLoader:MovieClipLoader = new MovieClipLoader(); mcLoader.addListener(mcOnLoadHandler); mcLoader.loadClip(“logo.gif”, clip);

6.Test your movie by pressing Ctrl+Enter. You will see the image resized when the load is complete.

How It Works

The MovieClipLoader class simplifies and automates the loading of an image. Had you not waited for the image to load completely, the image scaling would have failed because a loadMovie method resets a movie clip.

An object called mcOnLoadHandler was created. It contains the function definitions that are called by the MovieClipLoader class. Any events encountered by the mcLoader object are dispatched to the mcOnLoadHandler object. This connection is made by using the addListener method (discussed in Chapter 4). The MovieClipLoader class works well with images, and the example code here can be extended easily using the methods and events described in Chapter 8.

At any time you can redefine the listener, target movie clip, and listener object for optimum reuse. You just have to remember that the class works only with Flash 7 or newer.

Managing Sound

Sound, especially music, is probably one of the most coveted formats on the Web. It has spawned an entire industry of digital music sales, devices, and software.

ActionScript contains an easy-to-use sound object, which you can use to coincide with user interface functionality or to play files outright.

You can import sound directly onto a timeline in Flash, but that is limited and difficult to control once published. With the sound object, you have full control.

The sound object can obtain sound for playback in two ways: the sound can exist in the library, or the sound can be imported at runtime as an MP3. You can load an MP3 file from any domain without restriction.

Sound Class Methods

The following table describes the sound class’s methods:

Method

Return

Description

 

 

 

loadSound()

Nothing

Loads an MP3 file into the sound object.

getBytesLoaded()

Number

Returns the bytes loaded.

getBytesTotal()

Number

Returns the size, in bytes, of the specified sound object.

 

 

 

474

 

 

 

Using ActionScript for Media

 

 

 

 

 

 

 

 

 

Method

Return

Description

 

 

 

 

 

setVolume()

Nothing

Sets the volume of the sound object. It has one parame-

 

 

 

ter, which is an integer.

 

setTransform()

Nothing

Sets the transformation information for the sound

 

 

 

object. Contains four properties to set values: ll,lr,

 

 

 

rr,rl. Used to mix the two stereo channels to varying

 

 

 

degrees.

 

setPan()

Nothing

An integer of –100 through 100 sets the sound object

 

 

 

to the left and right channels.

 

attachSound()

Nothing

Loads a library sound instance.

 

start()

Nothing

Begins the sound playing at a specified index in sec-

 

 

 

onds and can control the number of times the sound is

 

 

 

repeated.

 

stop()

Nothing

Stops all sounds if no parameter is specified in the con-

 

 

 

structor, otherwise it stops the sound loaded into the

 

 

 

sound object.

 

getVolume()

Number

Returns a number representing the current volume of

 

 

 

the sound object.

 

getTransform()

Object

Returns the transform state of the current object as an

 

 

 

object.

 

getPan()

Nothing

Returns the current left-to-right balance as an integer

 

 

 

from –100 to 100.

 

 

 

 

Following is some additional information about some of the methods.

The loadSound() method has two parameters: a String URL representing an MP3 file and a Boolean that determines whether the file should start playing as soon as there is enough information to begin playing the file, or whether the object should wait until the entire sound file is completely loaded. Here’s the syntax:

Sound.loadSound(URL:String,isStreaming:Boolean);

The setVolume() method has a single parameter, a Number from 0 to 100, that sets the volume level of the sound object. Its syntax is as follows:

Sound.setVolume(n:Number);

The setTransform() method has one parameter, which must be an object. Here’s the syntax:

Sound.setTransform(SoundTransform:Object);

And here is an example transform object that contains the required values:

475

Chapter 19

var SoundTransform:Object = new Object(); SoundTransform.ll = 50; SoundTransform.lr = 50; SoundTransform.rr = 50; SoundTransform.rl = 50;

The setPan() method has one parameter, which must be a Number from –100 to 100. For example, passing a value of –100 sends all sound to the left channel. Following is the method’s syntax:

Sound.setPan(n:Number);

The attachSound() method can load only sounds that exist within the library. It has one parameter, a String representing the ID of the sound you want to play:

Sound.attachSound(“song1”:String);

The start() method has two parameters. The first parameter must be a Number. The default of the first parameter is zero. This parameter represents the index at which you want to begin playing the file. The second parameter is also a Number and determines the amount of times you want the file to loop. The default value of the second parameter is also zero, which means the file will play only once if this parameter is not set.

Sound.Start(SecondsIn:Number,Loops:Number);

Sound Class Events and Properties

Here are descriptions of the sound class’s events:

Event

Type

Description

 

 

 

onID3

Function

Fires when the sound object has detected id3 tags for an MP3.

onLoad

Function

Fires when a sound file has fully loaded into the sound object.

onSoundComplete

Function

Fires when a sound has finished playing.

The sound class has three properties, which are explained in the following table:

Event

Type

Description

 

 

 

Duration

Number

Total sound time in milliseconds.

Position

Number

Current playhead position in milliseconds.

Id3

Object

An object that contains name/value pairs of the available id3

 

 

information.

476

Using ActionScript for Media

Creating a Sound Object

The sound object can do more than just play back sound. The constructor has a few tricks up its sleeve. These tricks are mostly used to control sound objects that exist within movie clips and your SWF file as a whole. For example, you can control the volume of all sounds in the SWF by creating a sound object with no parameters:

var All_sounds:Sound = new Sound(); All_sounds.setVolume(50);

Alternatively, you can control the sound objects within a specific movie clip by passing the clip as a parameter. Here’s an example in which only the sounds in the specified movie clip are affected:

var some_sounds:Sound = new Sound(myMovieClip_mc); some_sounds.setVolume(50);

If you use the loadSound or attachSound method on the object, all manipulation of the sound occurs only on that specific instance of sound rather than on sounds existing in a movieClip object.

Loading Library Sounds

Loading library sounds is simple. First you import a sound object to the library by selecting File Import Import to Library. In the file browser dialog, select a valid sound file.

After you can see the sound file in the library, Alt+click the file and select Linkage. Select the Export for ActionScript option in the dialog that opens and give the sound a linkage ID.

ActionScript can now access the sound.

Try It Out

Playing a Simple Sound Object

Before you do this exercise, import a sound into the library. In this exercise, you create a simple object to present your sound from the library.

Obviously, your computer needs speakers. When testing sound in Flash, remember to check your system volume settings to ensure that your computer can play the sound. You don’t want to be debugging a sound object problem with the mute button on.

1.Open a new Flash document and save it as SoundTest.fla in your work folder.

2.Click the first frame in the timeline, open the Actions panel, and type the following ActionScript code:

var testSound = new Sound(); testSound.attachSound(“song1”); testSound.start(30);

Be sure the Linkage ID you set in the library for the sound object is what appears as the String parameter of the attachSound method.

477