You are on page 1of 28

Multimedia Application Development

LAB MANUAL
FOR

MULTIMEDIA APPLICATION DEVELOPMENT


Of B.TECH IV-I AND MCA V SEM

DEPARTMENT OF COMPUTER SCIENCE & ENGG

JYOTHISHMATHI INSTITUTE OF TECHNOLOGY AND SCIENCE


(Approved by AICTE, New Delhi, Affiliated to JNTU) Ramakrishna Colony, Nustulapur, Karimangar-505481

INDEX

S. No.
1. 2. 3. 4.

Program Name
Assigning Actions to an object Assigning actions to a button Mouse Events Detecting the player version

Page No.
03 03 04 05

zxcb

Preapered By D Srinivas

Page 1

Multimedia Application Development


5. 6. 7. 8. 9. 10. 11. 12. 13. 14. Detecting the Operating System Checking the System Language Detecting Display Settings Tinting a Movie Clip's Color Controlling a Movie Clip's Color with Sliders Drawing a Rectangle Filling a Shape with a Gradient Scripting Masks Converting Angle Measurements Calculating the Distance Between Two Points 06 06 07 07 07 12 13 15 18 19

15. 16. 17. 18.

Formatting Currency Amounts Converting Between Units of Measurement Sorting or Reversing an Array Creating a Text Field

20 22 24 26

19.

Making a Password Input Field

27

zxcb

Preapered By D Srinivas

Page 2

Multimedia Application Development

General Instructions 1. The procedures presented in this manual uses ActionScript 2.0 for Flash MX 2004 (versoin 7.0). 2. Although some of the exercises could be performed without using ActionScript, students are instructed to perform them using ActionScript to understand its power and use. 3. Students are instructed to become familiar with the Flash environment, perform some basic presentations/animations/effects before coding. 4. Be creative and make use of the strategies presented to create independent swfs.

zxcb

Preapered By D Srinivas

Page 3

Multimedia Application Development

5. Detecting the player version

zxcb

Preapered By D Srinivas

Page 4

Multimedia Application Development

use ActionScript (System.capabilities.version, or $version) For maximum compatibility, use the _level0.$version property, which returns a string of the form: OS MajorVersion,MinorVersion,Build,Patch // Split $version into an array with two elements using a space as the delimiter. // This creates an array with two elements, such as "WIN" and "6,0,40,0". playerParts = _root.$version.split(" "); // Store the OS name in playerOS. playerOS = playerParts[0]; // Split the remaining version string using a comma as the delimiter. This creates an // array with four elements, such as "6", "0", "40", and "0". playerVersion = playerParts[1].split(","); // Convert the major and minor version, the build, and the patch into numbers and // store them for later use. playerMajorMinor = Number(playerVersion[0] + "." + playerVersion[1]); playerBuild = Number(playerVersion[2]); playerPatch = Number(playerVersion[3]); if (playerMajorMinor < 5.0) { getURL ("http://www.person13.com/flashplugin/versionerrorpage.html"); } else { getURL ("http://www.person13.com/ascb/modernmovie.swf"); }

6. Detecting the Operating System Use the $version or System.capabilities.os property. playerParts = _level0.$version.split(" "); switch (playerParts[0]) {
zxcb Preapered By D Srinivas Page 5

Multimedia Application Development

case "MAC": gotoAndStop ("WelcomeMac"); break; case "WIN": gotoAndStop ("WelcomeWindows"); break; case "UNIX": gotoAndStop ("WelcomeUnix"); }

7. Checking the System Language Use the System.capabilities.language property. You can use the System.capabilities.language property to determine the language of the computer that is playing the movie. The property returns a two-letter ISO-639-1 language code (i.e., "fr" for French). Where applicable, a two-letter country code is appended, separated from the language code with a hyphen (i.e., "en-US" for U.S. English and "en-UK" for U.K. English). For a summary of language codes, see the following resources:
http://lcweb.loc.gov/standards/iso639-2/englangn.html http://www.iso.org/iso/en/prods-services/iso3166ma/02iso-3166-code-lists/list-en1.html

8.Detecting Display Settings Use the screenResolutionX and screenResolutionY properties of the System.capabilities object.

9. Tinting a Movie Clip's Color You can create the transform object by creating a generic instance of the base Object class and

zxcb

Preapered By D Srinivas

Page 6

Multimedia Application Development

adding properties to it, as follows: myColorTransform = new Object( ); myColorTransform.ra = 100; myColorTransform.rb = 50; myColorTransform.ga = 100; myColorTransform.gb = 50; myColorTransform.ba = 100; myColorTransform.bb = 50; myColorTransform.aa = 100; myColorTransform.ab = 0; Or you can create an equivalent transform object using object literal notation: myColorTransform = {ra: 100, rb: 50, ga: 100, gb: 50, ba: 100, bb: 50, aa: 100, ab: 0}; Any properties that are omitted from the preceding transform object are given a value of 0. After defining a transform object, apply it to the targeted movie clip via Color.setTranform( ), as follows: my_color = new Color(myMovieClip); my_color.setTranform(myColorTransform); Controlling a Movie Clip's Color with Sliders

1.Create a new Flash document and save it. 2.On the main timeline, rename the default layer as movieClips and create a new layer named actions. 3.Create a movie clip symbol and draw a circle in it. The circle should be approximately 120 x 120 pixels. 4.Return to the main timeline and create an instance of the circle movie clip on the Stage on the movieClips layer. Place the instance on the left side of the Stage. Name the instance circle_mc using the Property inspector. 5.Open the Components panel and drag four instances of the ScrollBar component onto the Stage on the movieClips layer. Name these instances red_sb, green_sb, blue_sb, and alpha_sb. Line them up horizontally on the right side of the Stage. 6 Select the keyframe of the actions layer and open the Actions panel. 7. Add the following code to the Actions panel and test the movie (Control Test Movie). The scrollbars are automatically colorized to indicate the color components they control.
zxcb Preapered By D Srinivas Page 7

Multimedia Application Development

Moving the thumb sliders on the scrollbars adjusts the circle's color. // Define a function that will initialize the scrollbar instances as sliders to // control the color values. function initSliders ( ) { // First, set the scroll properties of each of the scrollbars. For the red, // green, and blue scrollbars, the values should range from 0 to 255. Use a // pageSize of 120 for the color sliders to create a proportional thumb bar. // The alpha range is from 0 to 100, and so the pageSize should be 47 to create // a thumb bar that is proportional with the other sliders. red_sb.setScrollProperties (120, 0, 255); green_sb.setScrollProperties(120, 0, 255); blue_sb.setScrollProperties (120, 0, 255); alpha_sb.setScrollProperties(47, 0, 100); // Colorize the sliders themselves. Make the red_sb slider red and, similarly, // make green_sb green and blue_sb blue. Make the alpha_sb slider white. red_sb.setStyleProperty ("face", 0xFF0000); green_sb.setStyleProperty("face", 0x00FF00); blue_sb.setStyleProperty ("face", 0x0000FF); alpha_sb.setStyleProperty("face", 0xFFFFFF); // Set the initial position for the color sliders. alpha_sb remains at 100%. red_sb.setScrollPosition (127); green_sb.setScrollPosition(127); blue_sb.setScrollPosition (127); } function initColor ( ) { // Store a new Color object in a property of circle_mc. my_color = new Color(circle_mc); circle_mc.col = my_color; // Store references to the four scrollbars as properties of circle_mc. circle_mc.red = red_sb; circle_mc.green = green_sb; circle_mc.blue = blue_sb; circle_mc.alpha = alpha_sb; } // Initialize the sliders and the Color object. initSliders( ); initColor( );
zxcb Preapered By D Srinivas Page 8

Multimedia Application Development

// Update the color of the circle_mc movie clip based on the slider positions. circle_mc.onEnterFrame = function ( ) { // Retrieve the current position of the color and alpha sliders. var r = 255 - this.red.getScrollPosition( ); var g = 255 - this.green.getScrollPosition( ); var b = 255 - this.blue.getScrollPosition( ); var a = 100 - this.alpha.getScrollPosition( ); // Set up the transformation object properties to set circle_mc's color. transformObj = new Object( ); transformObj.ra = 0; transformObj.rb = r; transformObj.ga = 0; transformObj.gb = g; transformObj.ba = 0; transformObj.bb = b; transformObj.aa = a; transformObj.ab = 0; this.col.setTransform(transformObj); }

Drawing a Circle Create a custom MovieClip.drawCircle( ) method using the Drawing API and invoke it on a movie clip. You can create a circle in ActionScript with eight curves. Fewer curves results in a distorted circle and too many curves hinders performance. Let's create a custom method of the MovieClip class for drawing circles. This method, drawCircle( ), allows for three parameters: radius The radius of the circle x The x coordinate of the circle's center point. If undefined, the circle is centered at x = 0. y The y coordinate of the circle's center point. If undefined, the circle is centered at y = 0. Define the custom drawCircle( ) method on MovieClip.prototype to make it available to all
zxcb Preapered By D Srinivas Page 9

Multimedia Application Development

movie clip instances: MovieClip.prototype.drawCircle = function (radius, x, y) { // The angle of each of the eight segments is 45 degrees (360 divided by 8), which // equals p/4 radians. var angleDelta = Math.PI / 4; // Find the distance from the circle's center to the control points for the curves. var ctrlDist = radius/Math.cos(angleDelta/2); // Initialize the angle to 0 and define local variables that are used for the // control and ending points. var angle = 0; var rx, ry, ax, ay; // Move to the starting point, one radius to the right of the circle's center. this.moveTo(x + radius, y); // Repeat eight times to create eight segments. for (var i = 0; i < 8; i++) { // Increment the angle by angleDelta (p/4) to create the whole circle (2p). angle += angleDelta; // The control points are derived using sine and cosine. rx = x + Math.cos(angle-(angleDelta/2))*(ctrlDist); ry = y + Math.sin(angle-(angleDelta/2))*(ctrlDist); // The anchor points (end points of the curve) can be found similarly to the // control points. ax = x + Math.cos(angle)*radius; ay = y + Math.sin(angle)*radius; // Draw the segment. this.curveTo(rx, ry, ax, ay); } } How the drawCircle( ) method functions is better understood with a little explanation. The distance of the control point for each segment from the circle's center is found using a trigonometric formula that states that the cosine of an angle is equal to the adjacent side over the hypotenuse. In the case of the circle, the angle that bisects a segment (thus also intersecting its control point) is p/8 (angleDelta/2). The distance to the control point from the center of the circle forms the hypotenuse of the right triangle,
zxcb Preapered By D Srinivas Page 10

Multimedia Application Development

var ctrlDist = radius/Math.cos(angleDelta/2);

Basic trigonometric formulas can be used to find the x and y coordinates along the circle's circumference given the angle and the hypotenuse. For the control point, the hypotenuse value is ctrlDist, and the angle is angle - angleDelta/2, since this angle bisects the segment. The anchor point is found using the value of angle, which is calculated to be the angle that intersects the anchor point, and the circle's radius (since the anchor point should always be on the circle's circumference). Thus, it follows: rx = x + Math.cos(angle-(angleDelta/2))*(ctrlDist); ry = y + Math.sin(angle-(angleDelta/2))*(ctrlDist); ax = x + Math.cos(angle)*radius; ay = y + Math.sin(angle)*radius; Once you have defined the drawCircle( ) method and included it in your Flash document, you can quickly draw a circle with just a few lines of code. Remember that you still need to define a line style before Flash will draw anything. // Create a movie clip instance in which you will draw the circle. this.createEmptyMovieClip("circle_mc", 1); // Define a 1-pixel, black, solid line style. circle_mc.lineStyle(1, 0x000000, 100); // Draw a circle of radius 100, centered at (50,75). circle_mc.drawCircle(100, 50, 75); // Draw a circle of radius 65, centered at (0,0). circle_mc.drawCircle(65); You can fill a circle by invoking beginFill( ) or beginGradientFill( ) before drawCircle( ) and invoking endFill( ) after drawCircle( ): this.createEmptyMovieClip("circle_mc", 1); circle_mc.lineStyle(1, 0x000000, 100); // Use a 1-pixel, black, solid border. circle_mc.beginFill(0x0000FF); // Use a solid blue fill. circle_mc.drawCircle(100); circle_mc.endFill( );

zxcb

Preapered By D Srinivas

Page 11

Multimedia Application Development

Drawing a Rectangle Create a custom MovieClip.drawSimpleRectangle( ) method using the Drawing API and invoke it on a movie clip. To draw a simple rectangle, specify the stroke's attributes using the lineStyle( ) method and then draw four lines using the lineTo( ) method: // Create rectangle_mc with a depth of 1 on the main timeline. _root.createEmptyMovieClip("rectangle_mc", 1); // Specify a one-pixel, solid, black line. rectangle_mc.lineStyle(1, 0x000000, 100); // Draw four lines to form the perimeter of the rectangle. rectangle_mc.lineTo(100, 0); rectangle_mc.lineTo(100, 50); rectangle_mc.lineTo( 0, 50); rectangle_mc.lineTo( 0, 0); Thus, drawing a simple rectangle is no huge feat. To draw multiple rectangles with various dimensions, you should create a custom drawSimpleRectangle( ) method for the MovieClip class, as follows: // Define the custom method on MovieClip.prototype so that it's available to all // movie clip instances. MovieClip.prototype.drawSimpleRectangle = function (width, height) { this.lineTo(width, 0); this.lineTo(width, height); this.lineTo(0, height); this.lineTo(0, 0); } // Invoke the custom method like this. _root.createEmptyMovieClip("rectangle_mc", 1); rectangle_mc.lineStyle(1, 0x000000, 100); rectangle_mc.drawSimpleRectangle(100, 50); The dimensions of the rectangle are 102 x 52 pixels due to the line thickness. Reduce the dimensions by two pixels in each direction to create a rectangle whose outside dimensions match the intended size. Filling a Shape with a Gradient Use the beginGradientFill( ) and endFill( ) methods to initiate and close a shape drawn at
zxcb Preapered By D Srinivas Page 12

Multimedia Application Development

runtime. In a gradient fill, there is a graded change in colors. Flash supports linear gradients, in which one color fades into the next from left to right. Flash also supports radial gradients, in which the colors radiate out from a center point. You can initiate a gradient-filled shape using beginGradientFill( ) in the same way you initiate a solid-filled shape with beginFill( ). The difference is that the call to beginGradientFill( ) requires a more complex set of parameters: gradientType Either "linear" for a linear gradient, or "radial" for a radial gradient. colors An array of RGB values for the colors to use in the gradient. They are displayed in the gradient from left to right in a linear gradient, or from the center outward in a radial gradient. alphas An array of alpha values that correspond to the colors in the colors parameter array. ratios An array whose elements are numbers corresponding to the colors and alphas elements. The values in the ratios array indicate the point within the gradient at which each color is pure. The range of values for the ratios should be from 0 (leftmost point in a linear fill, or innermost point in a radial fill) to 255 (rightmost or outermost). matrix An object with the following properties: matrixType This value should always be "box". x The x coordinate of the bottom-left corner of the gradient. y The y coordinate of the bottom-left corner of the gradient. width The width of the gradient in pixels.

zxcb

Preapered By D Srinivas

Page 13

Multimedia Application Development

height The height of the gradient in pixels. r The rotation of the gradient in radians (not degrees). Here is an example that uses a linear gradient to fill a rectangle: // Include the drawing methods, which are needed for the drawRectangle( ) method. #include "DrawingMethods.as" // Define the width and height of the rectangle to be drawn and filled. rectWidth = 100; rectHeight = 200; // Create an empty clip into which we will draw the shape. _root.createEmptyMovieClip("shape_mc", 1); shape_mc.lineStyle(3, 0, 100); // Create a colors array with RGB values for blue, green, and red. colors = [0x0000FF, 0x00FF00, 0xFF0000]; // Create an alphas array in which the colors are 100% opaque. alphas = [100, 100, 100]; // Create a ratios array where pure blue is at the left edge of the gradient, pure // green is in the center, and pure red at the right edge. ratios = [0, 127.5, 255]; // Create the matrix object. Set the x and y coordinates so that the bottom-left // corner of the gradient lines up with the bottom-left corner of the rectangle. Set // the width and height of the gradient to match the rectangle. matrix = {matrixType: "box", x: -rectWidth/2, y: -rectHeight/2, w: rectWidth, h: rectHeight, r:0}; // Call beginGradientFill( ) so that the rectangle will be // filled with a linear gradient. shape_mc.beginGradientFill("linear", colors, alphas, ratios, matrix); // Draw the rectangle with rounded corners (requires DrawingMethods.as). shape_mc.drawRectangle(rectHeight, rectWidth, 10); // End the fill.
zxcb

Preapered By D Srinivas

Page 14

Multimedia Application Development

shape_mc.endFill( ); Note that the endFill( ) method is used to end a drawing operation begun with either beginFill( ) or beginGradientFill( ). Here is an example of a radial, gradient fill used to fill an ellipse: // Include the drawing methods, which are needed for the drawEllipse( ) method. #include "DrawingMethods.as" // Define the width and height of the ellipse to be drawn and filled. ellipseWidth = 100; ellipseHeight = 200; _root.createEmptyMovieClip("shape_mc", 1); shape_mc.lineStyle(3, 0x000000, 100); // Create colors, alphas, and ratios arrays for white and black, both 100% opaque. // Pure white starts in the center and grades into pure black at the outside edge. colors = [0xFFFFFF, 0x000000]; alphas = [100, 100]; ratios = [0, 255]; // Define the matrix object. matrix = {matrixType: "box", x: -ellipseWidth/2, y: -ellipseHeight/2, w: ellipseWidth, h: ellipseHeight, r:0}; // Begin the radial fill. shape_mc.beginGradientFill("radial", colors, alphas, ratios, matrix); // Draw the ellipse (requires DrawingMethods.as). shape_mc.drawEllipse(ellipseWidth/2, ellipseHeight/2); // End the fill. shape_mc.endFill( ); Scripting Masks Use the Drawing API to create a shape and then use MovicClip.setMask( ) to apply the mask. Masks can be used to create unique shapes or visual effects. For example, you can use masks to create wipes and transitions or interesting animations in which only the masked portion of the artwork is visible at a given time. You can even create masks that change shape over time, and use them to mask bitmapped graphics (in movie clips).

zxcb

Preapered By D Srinivas

Page 15

Multimedia Application Development

You can use any movie clip as a mask of another movie clip using the setMask( ) method. The setMask( ) method is called from the movie clip to be masked, and you should pass it a reference to the movie clip that acts as the mask: maskedMovieClip.setMask(maskMovieClip); In most cases, masks are simple shapes, such as rectangles or circles. You do not need to use the Drawing API to draw the mask movie clip, but it is recommended that you do so unless the mask is of an unusual shape. First, here is an example in which a mask follows the mouse. The mask is assigned to a movie clip containing a loaded image, so the effect is that the user can see only the portion of the image over which he has positioned the mouse. // Include the drawing methods, which are needed for the drawCircle( ) method. #include "DrawingMethods.as" // Create a movie clip and a nested movie clip for loading an image. See Recipe 15.3 // for more information on the need for creating nested movie clips when loading // external JPEGs. _root.createEmptyMovieClip("image_mc", 1); _root.image_mc.createEmptyMovieClip("imageHolder_mc", 1); // Load the image into the movie clip. You can use this URL if you want, but it will // work only while you are using the test or standalone players. See Recipe 15.3 for // more information on loading JPEGs. image_mc.imageHolder_mc.loadMovie("http://www.person13.com/ascb/images/image1.jpg"); // Draw the masking movie clip. _root.createEmptyMovieClip("mask_mc", 2); mask_mc.lineStyle(3, 0x000000, 0); mask_mc.beginFill(0, 100); mask_mc.drawCircle(60); mask_mc.endFill( ); // Call the setMask( ) method on the masked movie clip and pass it the masking movie // clip as a parameter. image_mc.setMask(mask_mc); // Call the startDrag( ) method of the masking movie clip so that the mask can be // moved with the cursor. mask_mc.startDrag(true); Next, here is an example in which a mask is used to create a wipe transition between two loaded images.
zxcb

Preapered By D Srinivas

Page 16

Multimedia Application Development

#include "DrawingMethods.as" // Create a movie clip and a nested movie clip and load the first image into it. _root.createEmptyMovieClip("image0_mc", 1); _root.image0_mc.createEmptyMovieClip("imageHolder_mc", 1); image0_mc.imageHolder_mc.loadMovie("http://www.person13.com/ascb/images/image1.jpg") ; // Create another movie clip and nested movie clip and load the second image into it. // Both image0_mc and image1_mc are created at (0,0). This means that they will // overlap. This is what we want. _root.createEmptyMovieClip("image1_mc", 2); _root.image1_mc.createEmptyMovieClip("imageHolder_mc", 1); image1_mc.imageHolder_mc.loadMovie("http://www.person13.com/ascb/images/image2.jpg") ;

// Draw the masking movie clip. The dimensions of the images are 640 x 480 (if you // load the images using the URLs provided) and so the mask should be a rectangle // with the same dimensions. _root.createEmptyMovieClip("mask_mc", 3); mask_mc.lineStyle(3, 0x000000, 0); mask_mc.beginFill(0, 100); mask_mc.drawRectangle(640, 480); mask_mc.endFill( ); // Position the mask so that it is off to the left side of the Stage. mask_mc._x = -320; mask_mc._y = 240; // Call the setMask( ) method to set mask_mc as the mask for image1_mc. This causes // image0_mc to display initially, even though it is below image1_mc. image1_mc.setMask(mask_mc); // Define an event handler method for image0_mc so that the mask movie clip moves // when the user clicks on image0_mc. image0_mc.onRelease = function ( ) { // Use an onEnterFrame( ) event handler method to move the mask. This assumes you // have the default frames per second setting of 12. _root.mask_mc.onEnterFrame = function ( ) { // Move the mask to the right by 12 pixels. this._x += 12;
zxcb Preapered By D Srinivas Page 17

Multimedia Application Development

// If the mask is fully masking the image, then delete the onEnterFrame( ) method. if (this._x >= 320) { this._x = 320; delete this.onEnterFrame; } } } Converting Angle Measurements Create custom degToRad( ) and radToDeg( ) methods. The _rotation property of a movie clip object is measured in degrees. Every other angle measurement in ActionScript, however, uses radians, not degrees. This can be a problem in two ways. First of all, if you want to set the _rotation property based on the output of one of ActionScript's trigonometric methods, you must convert the value from radians to degrees. Second, humans generally prefer to work in degrees, which we must convert to radians before feeding to any of the trigonometric methods. Fortunately, the conversion between radians and degrees is simple. You should add the following degToRad( ) and radToDeg( ) methods to your Math.as file for converting from degrees to radians and vice versa. Note that they are attached directly to the top-level Math object, making them available throughout your movie. // Convert degrees to radians by multiplying by p and dividing by 180. Math.degToRad = function(deg){ return (Math.PI * deg) / 180; }; // Convert radians to degrees by multiplying by 180 and dividing by p. Math.radToDeg = function(rad){ return (rad * 180) / Math.PI; }; This following code demonstrates how the methods work: trace(Math.degToRad(90)); // Displays: 1.5707963267949 (which is p/2) trace(Math.radToDeg(Math.PI)); // Displays: 180 These two methods are invaluable when you want to use the trigonometric methods: // Use degToRad( ) to convert degrees to radians before passing the value to // Math.cos( ) (which expects radians). trace(Math.cos(Math.degToRad(36))); // Get the angle (in radians) for a cosine of .75 using the inverse cosine.
zxcb Preapered By D Srinivas Page 18

Multimedia Application Development

angle = Math.acos(.75); // Set MovieClip._rotation to the degree equivalent of the angle in radians. myMovieClip._rotation = Math.radToDeg(angle); Calculating the Distance Between Two Points You can calculate the distance (in a straight line) from any two points by using the Pythagorean theorem. The Pythagorean theorem states that in any right triangle (a triangle in which one of the angles is 90 degrees), the length of the hypotenuse (the long side) is equal to the square root of the sum of the squares of the two other sides (referred to as the legs of the triangle). The Pythagorean theorem is usually written as: a2 + b2 = c2 You can use this formula to calculate the distance between any two points, where a is the difference between the points' x coordinates, b is the difference between their y coordinates, and c (the distance to be determined) equals the square root of (a2 + b2). In ActionScript, this is written as: var c = Math.sqrt(Math.pow(a, 2) + Math.pow(b, 2)); How do you calculate the distance between two points using a right triangle? While it might not seem immediately obvious, you can form an imaginary right triangle using any two points in the Flash coordinate system The hypotenuse of the imaginary triangle is formed by the line connecting the two points. The legs of the triangle are formed by lines extending horizontally and vertically from the two points. You can find the lengths of the legs by finding the differences between the x and y coordinates. The length of leg a is determined by the difference in the points' x coordinates, and the length of leg b is determined by the difference in the points' y coordinates. Once you know the lengths of legs a and b, you can use the Pythagorean theorem to calculate the length of the hypotenuse, c, which represents the distance between the points (our original quarry). It is convenient to encapsulate this calculation in a method that you can reuse. The custom Math.getDistance( ) method we define here accepts the x and y coordinates of the two points as its four parameters: Math.getDistance = function (x0, y0, x1, y1) { // Calculate the lengths of the legs of the right triangle. var dx = x1 - x0; var dy = y1 - y0; // Find the sum of the squares of the legs of the triangle. var sqr = Math.pow(dx, 2) + Math.pow(dy, 2);
zxcb

Preapered By D Srinivas

Page 19

Multimedia Application Development

// Return the square root of the sqr value. return (Math.sqrt(sqr)); }; Here is an example of the Math.getDistance( ) method being used to calculate the distance between two points at (300,400) and (0,0): trace(Math.getDistance(300, 400, 0, 0)); // Displays: 500

Formatting Currency Amounts Create a custom Math.currencyFormat( ) method. Unlike some other languages, such as ColdFusion, ActionScript does not have a built-in function for formatting numbers as currency amounts. That's the bad news. The good news is that it is not too difficult to create a custom method to format numbers as currency amounts. Our custom Math.currencyFormat( ) method accepts up to seven parameters: num The number to format. decimalPl The number of decimal places in the formatted number. currencySymbol The symbol, such as a dollar sign ($), to use. thousandsDelim The characters used to delimit thousands, millions, etc. decimalDelim The characters used to delimit the fractional portion from the whole number. truncate If true, truncate the number to the specified number of decimal places; otherwise, round the number. spaceFill The number of spaces the entire formatted string should occupy.
zxcb Preapered By D Srinivas Page 20

Multimedia Application Development

Here is our custom Math.currencyFormat( ) method. The method converts a numeric parameter into a currency-formatted string. Include this method within Math.as along with the custom roundDecPl( ), numberFormat( ), and zeroFill( ) methods in this chapter, on which this example relies. Math.currencyFormat = function (num, decimalPl, currencySymbol, thousandsDelim, decimalDelim, truncate, spaceFill) { // Default to two decimal places, a dollar sign ($), a comma for thousands, and a // period for the decimal point. We implemented the defaults using the conditional // operator. Compare with Recipe 5.5. decimalPl = (decimalPl == undefined) ? 2 : decimalPl; currencySymbol = (currencySymbol == undefined) ? "$" : currencySymbol; thousandsDelim = (thousandsDelim == undefined) ? "," : thousandsDelim; decimalDelim = (decimalDelim == undefined) ? "." : decimalDelim; // Split the number into the whole and decimal (fractional) portions. var parts = String(num).split("."); // Truncate or round the decimal portion, as directed. if (truncate) { parts[1] = Number(parts[1]) * Math.pow(10, -(decimalPl - 1)); parts[1] = String(Math.floor(parts[1])); } else { // Requires the roundDecPl( ) method defined in Recipe 5.3 parts[1] = Math.roundDecPl(Number("." + parts[1]), decimalPl); parts[1] = String(parts[1]).split(".")[1]; } // Ensure that the decimal portion has the number of digits indicated. // Requires the zeroFill( ) method defined in Recipe 5.4. parts[1] = Math.zeroFill(parts[1], decimalPl, true); // If necessary, use the numberFormat( ) method from Recipe 5.5 to format the number // with the proper thousands delimiter and leading spaces. if (thousandsDelim != "" || spaceFill != undefined) { parts[0] = Math.numberFormat(parts[0], thousandsDelim, "", spaceFill - decimalPl - currencySymbol.length); } // Add a currency symbol and use String.join( ) to merge the whole (dollar) and // decimal (cents) portions using the designated decimal delimiter. return currencySymbol + parts.join(decimalDelim); };
zxcb Preapered By D Srinivas Page 21

Multimedia Application Development

Here are a few examples of Math. currencyFormat ( ) in action: trace(Math.currencyFormat(1.2)); // Displays: $1.20 trace(Math.currencyFormat(.3)); // Displays: $0.30 trace(Math.currencyFormat(1234567)); // Displays: $1,234,567.00 trace(Math.currencyFormat(12.34, 2, "\u20AC")); // Displays: 12.34 (euros) trace(Math.currencyFormat(12.34, 2, "\u00a3")); // Displays: 12.34 (pounds) trace(Math.currencyFormat(12.34, 2, "\u00a5")); // Displays: 12.34 (yen) trace(Math.currencyFormat(1.2, 2, "", ".", ",")); // Displays: 1,20 trace(Math.currencyFormat(1234, 2, "", ".", ",")); // Displays: 1.234,00 Converting Between Units of Measurement Write a custom method to perform the conversion and add it to the Math class. Here is a temperature converter. The method takes three parameters: the name of the units from which you are converting, the name of the units to which you are converting, and the value to convert. In this example code, we define conversions between Fahrenheit and Centigrade ("F" is interpreted to mean "Fahrenheit"; "C" and "Celsius" are recognized alternatives to "Centigrade"): Math.convertTemperature = function (fMeasure, tMeasure, val) { // Convert all names to lowercase to match any capitalization. fMeasure = fMeasure.toLowerCase( ); tMeasure = tMeasure.toLowerCase( ); if ( (fMeasure == "centigrade" || fMeasure == "celsius" || fMeasure == "c") && (tMeasure == "fahrenheit" || tMeasure == "f") ) { // Convert Centigrade to Fahrenheit. return (val * 9/5) + 32; } else if ( (fMeasure == "fahrenheit" || fMeasure == "f") && (tMeasure == "centigrade" || tMeasure == "celsius" || tMeasure == "c") ) { // Convert Fahrenheit to Centigrade. return (val - 32) * 5/9; } else { trace ("Invalid conversion type from " + fMeasure + " to " + tMeasure); return NaN; } }; Here are examples of how to use this function: trace(Math.convertTemperature ("Centigrade", "Fahrenheit", 0)); // Displays: 32 trace(Math.convertTemperature ("c", "f", 0)); // Displays: 32 trace(Math.convertTemperature ("fahrenheit", "centigrade", 212)); // Displays: 100

zxcb

Preapered By D Srinivas

Page 22

Multimedia Application Development

trace(Math.convertTemperature ("fahrenheit", "celsius", 212));

// Displays: 100

You could modify the preceding function to also support degrees Kelvin. However, if you support more than two units of measure, the number of possible permutations (and the number of required else if clauses) multiplies rapidly. In such a case, you can convert all values to an interim unit of measurement to reduce the number of transformations required. For example, you can convert all temperatures to and from Centigrade, as follows: Math.convertToCentigrade = function (fMeasure, val) { fMeasure = fMeasure.toLowerCase( ); if (fMeasure == "kelvin" || fMeasure == "k") { return (val - 273.15); } else if ( fMeasure == "fahrenheit" || fMeasure == "f" ) { return (val - 32) * 5/9; } else if (fMeasure == "centigrade" || fMeasure == "celsius" || fMeasure == "c") { return val; } else { return NaN; } }; Math.convertFromCentigrade = function (tMeasure, val) { tMeasure = tMeasure.toLowerCase( ); if (tMeasure == "kelvin" || tMeasure == "k") { return (val + 273.15); } else if ( tMeasure == "fahrenheit" || tMeasure == "f" ) { return (val * 9/5) + 32; } else if (tMeasure == "centigrade" || tMeasure == "celsius" || tMeasure == "c") { return val; } else { return NaN; } }; This allows our Math.convertTemperature( ) method to be simplified, as follows: Math.convertTemperature = function (fMeasure, tMeasure, val) { var centigradeVal = Math.convertToCentigrade (fMeasure, val); return Math.convertFromCentigrade (tMeasure, centigradeVal ); }; Here are examples of how to use this function: trace(Math.convertTemperature ("centigrade", "Kelvin", 0)); // Displays: 273.15 trace(Math.convertTemperature ("k", "f", 0)); // Displays: -459.67 trace(Math.convertTemperature ("fahrenheit", "kelvin", 212)); // Displays: 373.15
zxcb Preapered By D Srinivas Page 23

Multimedia Application Development

trace(Math.convertTemperature ("K", "celsius", 0));

// Displays: -273.15

Or, if you prefer, you could write single-purpose functions, such as Math.fahrToCent( ), Math.centToFahr( ), and Math.fahrToKelvin( ), that simply accept the value to convert. Here is another function that converts between pounds and kilograms using the same structure shown earlier: Math.convertWeights = function (fMeasure, tMeasure, val) { if (fMeasure == "pounds" && tMeasure == "kilograms") { return val / 2.2; } else if (fMeasure == "kilograms" && tMeasure == "pounds") { return val * 2.2; } else { return "invalid conversion type"; } }; Here are some examples of its use: trace(Math.convertWeights ("pounds", "kilograms", 0)); // Displays: 0 trace(Math.convertWeights ("kilograms", "pounds", 100)); // Displays: 220 You can add support for conversion to other units of weight by inserting additional else if statements following the same pattern. Or you can use the technique demonstrated for temperature, in which all values are first converted to a common unit.

Sorting or Reversing an Array Use the sort( ) method. For arrays of objects, you can also use the sortOn( ) method. You can perform a simple sort on an array using the sort( ) method. The sort( ) method, without any parameters, sorts the elements of an array in ascending order. Elements are sorted according to the Unicode code points of the characters in the string (roughly alphabetical for Western European languages). However, the sort is also case-sensitive, and it sorts numbers "alphabetically" instead of numerically. See Recipe 6.11 for details on creating custom sorting algorithms that are case-insensitive. words = ["tricycle", "relative", "aardvark", "jargon"]; words.sort( ); trace(words); // Displays: aardvark,jargon,relative,tricycle The reverse( ) method reverses the order of the elements in an array: words = ["tricycle", "relative", "aardvark", "jargon"]; words.reverse( );
zxcb

Preapered By D Srinivas

Page 24

Multimedia Application Development

trace(words); // Displays: jargon,aardvark,relative,tricycle If you want to sort the elements of an array in descending order, use the sort( ) method followed by the reverse( ) method: words = ["tricycle", "relative", "aardvark", "jargon"]; words.sort( ); words.reverse( ); trace(words); // Displays: tricycle,relative,jargon,aardvark You can sort arrays of objects using the sortOn( ) method. The sortOn( ) method requires a string parameter specifying the name of the property on which to sort the elements: cars = new Array( ); cars.push({make: "Honda", year: 1997, color: "maroon"}); cars.push({make: "Chrysler", year: 2000, color: "beige"}); cars.push({make: "Mercedes", year: 1985, color: "blue"}); cars.push({make: "Fiat", year: 1983, color: "gray"}); // Sort the cars array according to the year property of each element. cars.sortOn("year"); for (var i = 0; i < cars.length; i++) { // Outputs: // A gray 1983 Fiat // A blue 1985 Mercedes // A maroon 1997 Honda // A beige 2000 Chrysler trace("A " + cars[i].color + " " + cars[i].year + " " + cars[i].make); } To sort the elements of an array of objects in descending order, call the reverse( ) method after calling sortOn( ). Sorted arrays can be useful in many scenarios. For example, if you want to display the elements of an array in a UI component or a text field, you often want to list the elements in alphabetical order.

Creating a Text Field You can create a text field using the MovieClip.createTextField( ) method. You can create a text field at authoring time using Flash's Text tool. Manual creation lets you
zxcb Preapered By D Srinivas Page 25

Multimedia Application Development

see the layout of the objects on the Stage. However, many projects benefit from creating text fields dynamically. For example:

An animation with randomized text elements A user interface in which items (and their labels) are created dynamically based on data loaded into the movie from a text file, XML document, or other source A form that automatically adapts to a user's input Word games

The MovieClip.createTextField( ) method creates a text field at runtime. Note that the createTextField( ) method is invoked on a MovieClip object, not a text field. (If we had a text field already, we wouldn't need the recipe, now would we?) The createTextField( ) method takes six required parameters: parentMovieClip.createTextField(name, depth, x, y, width, height); where the parameters are as follows: name The instance name of the new text field depth The depth (within the MovieClip object) of the new text field x The x position relative to parentMovieClip's registration point y The y position relative to parentMovieClip's registration point width The width of the field in pixels height The height of the field in pixels The new text field is created within the movie clip from which the method is invoked, which is called the parent clip or container clip. This example creates a new text field named myTextwith a depth of 1, positioned at (0, 0), and with a width of 100 and a height of 20within _root: _root.createTextField("myText", 1, 0, 0, 100, 20);
zxcb

Preapered By D Srinivas

Page 26

Multimedia Application Development

Once the text field is created, it can be targeted using parentMovieClip.newTextFieldName, as follows: _root.myText._x = 100; The parent clip can be _root (the main timeline) or a movie clip created either at runtime or authoring time. You can use the duplicateMovieClip( ), attachMovie( ), and createEmptyMovieClip( ) methods of the MovieClip class to dynamically create a parent movie clip to hold the text field: _root.createEmptyMovieClip("myTextHolder", 1); _root.myTextHolder.createTextField("myText", 1, 0, 0, 100, 20); _root.myTextHolder.myText.text = "This is a new text object"; You can remove a TextField created with createTextField( ) simply by invoking the removeTextField( ) method on that object, as follows: myText.removeTextField( );

Making a Password Input Field Set the text field's password property to true. When a user enters a password into a field, you generally do not want observers to be able to read the password. This is a basic security precaution. The common convention is to display only asterisks in the field as the user types. This way, the user can see that he is successfully entering a value without observers being able to easily read the password. To create an input field that is automatically masked with asterisks, you only need to set the TextField.password property to true: myTextField.password = true; When you set the password property to true, all text entered into the text field, either programmatically or by user input, displays as asterisks: myTextField.password = true; myTextField.text = "some text"; // Text field displays: *********

zxcb

Preapered By D Srinivas

Page 27

Multimedia Application Development

zxcb

Preapered By D Srinivas

Page 28

You might also like