RENDERING TECHNIQUES
Colors in Flash In Flash, colors are specified as numbers. A color number can be anything from 0 to 16,777,215 for 24- bit color which is 256 * 256 * 256. Flash uses RGB color, meaning that every color is made up of a red, a green, and a blue component. Additionally, there is a 32-bit color system, which I will cover shortly. This has an extra 8-bit number set aside for alpha, or transparency.
Using Hexadecimal Color Values Hexadecimal, or hex for short, is a base 16 system. each digit in a hex number can be from 0 to F. In ActionScript, we use the prefix 0x to signal that we are using a hex number. In decimal, each digit is worth ten times the digit to its right. In other words, the number 243 means two times 100, four times 10, and three times 1. In hex, each digit is worth 16 times its right-hand neighbor. For example, 0x2B3 means two times 256, B (or eleven) times 16, and three times 1.
Using Hexadecimal Color Values For 24-bit colors, this goes all the way up to 0xFFFFFF, which, if you do the math, is magically equal to 16,777,215. those six hex digits can be broken down into three pairs. The first pair represents the red component. The second pair represents the green The last two digits represent blue.
Using Hexadecimal Color Values You might be wondering how to convert between the two formats. Converting from hex to decimal is pretty easy. Just trace the value. The trace function will convert to decimal for you. One way to get hex is to use the tostring(16) method, like so: This will trace ac05a2. If you are going to use that value somewhere, don t forget to add the 0x.
Transparency and 32-Bit Color 32-bit color contains an extra 8 bits for transparency. 32-bit colors are expressed as hexadecimal numbers in the format 0xAARRGGBB, where AA stands for alpha or transparency. 0xFFFFFFFF creates an opaque white color, 0x00FFFFFF creates a completely transparent white color. 0x80FFFFFF creates an approximately 50% transparent white color.
New Number Types: int and uint In prior versions of ActionScript, there was only one type of number. It was represented by the type Number, which could be a positive or negative integer or floating-point value (or zero). There are now a couple of additional types that you can use to make your code clearer. The first new type is int. This type can hold a positive or negative integer or zero. If you try to assign a floating-point number to a variable declared as an int, the decimal part will be truncated.
New Number Types: int and uint One area ints are often used is as counting variables in for loops. The next new type is uint. This stands for unsigned integer. Unit is is always positive.
New Number Types: int and uint Colors are almost always stored as uints in AS 3. This is because an unsigned integer can hold a much larger positive value than a regular (signed) integer. Both ints and uints are stored internally as 32-bit numbers, But an int uses one of those bits to specify the sign (plus or minus) of the number. So a positive 32-bit color value is just too big to fit in an int! What happens if you try? Test the following code and see:
New Number Types: int and uint The value 0xFFFFFFFF is equal to 4,294,967,295 in decimal. Since this is too big for an int, it rolls over and becomes 1! If you use a uint, though, it comes out just fine. Therefore, because color values will always be positive, and may need to go beyond what an int can hold, we use uints to store them.
Combining Colors Say you have three variables, red, green, and blue. Each of them holds a value from 0 to 255. You want to create a valid color value. Here s the formula to do just that: If you also have an alpha value, you can create a 32-bit number with this formula: This makes use of two bitwise operators. Bitwise operators work on numbers on a binary level.
Combining Colors Sticking with 24-bit colors for a moment, if you were to list the bits of a color value, you would have a string of 24 ones and zeros. Breaking up the hex 0xRRGGBB into binary, you have this: You see eight bits for red, eight for green, and eight for blue. The first bitwise operator is <<, which is the bitwise left shift operator. This shifts the binary representation of the value a number of places to the left.
Combining Colors you have a red value of 0xFF or 255. Shifting it 16 places to the left gives you this: As a 24-bit color number, this is red. Seen in hex, this is 0xFF0000 - again, full red.
Combining Colors Now, say you have a green value of 0x55 (85 decimal). In binary, it looks like this: Shift this eight places, and you get this: Finally, you have a blue value of 0xF3 (243 decimal), which is this in binary: Since this already all falls into the blue range, you don t need to touch it.
Combining Colors Now, you have three values for red, green, and blue: Use bitwise OR, the symbol. This compares the digits of two numbers on a binary level and says if either digit is equal to one, the result will be one. If both digits are zero, the result is zero. You get this result:
Combining Colors If you convert that to hex, you get 0xFF55F3. Of course, you never see the bits or deal with the ones or zeros at all. You d just type this: If you are working with decimal values, you could use this form:
Combining Colors Back to 32-bit numbers, it s exactly the same concept. You just take your 8-bit alpha channel and shift it left, 24 bits. For example, if we were to take the 32-bit color number, 0xFFFF55F3, and shift the alpha value to the left 24 places, we d have this:
Extracting Component Colors You might also need to take a color value and extract the various component values from it. Take the value 0xFFFF55F3 and try to get the red, green, and blue values from it. Here s the next formula for 24-bit colors: First, you ve probably guessed that >> is the bitwise right shift operator, which shifts the bits so many places to the right.
Extracting Component Colors Begin with red: When you shift the color value 16 places to the right, it becomes this: For green, shift it eight places, and you get this: you use another bitwise operator, &, also called AND. If this digit AND this digit are both one, then the result is one. If either one is zero, the result is zero.
Extracting Component Colors You compare it to 0xFF so you get this: With blue, you don t need to shift anything, just AND it with 0xFF, which will preserve the blue and knock out the red and green.
Extracting Component Colors For 32-bit colors, you can use the same technique, but you need a slight change:
The Drawing API API stands for application programming interface. The drawing API refers to the properties and methods that allow you to draw lines, curves, fills, gradient fills, and so on with ActionScript. Beginning with Flash MX, you got the following methods:
The Drawing API In Flash 8, several enhancements were added to the linestyle and begingradientfill methods. This version also introduced the beginbitmapfill and linegradientstyle methods. AS 3 added several very useful methods:
The Graphics Object In earlier versions of Flash, the drawing API methods were methods of the MovieClip class, and could be called directly from a movie clip instance, like this: Now, sprites and movie clips have a property called graphics, which is used to access all the drawing API methods.
Removing Drawing with Clear clear simply removes any previously drawn lines, curves, or fills from the sprite or movie clip. Note that it will affect only graphics that were created using other drawing API methods. In other words, if you drew a shape on stage in the authoring environment, calling clear() at runtime would not affect that shape. In the drawing API, it happens that the more you draw in a particular movie clip, the slower it goes. This can be important in animation, using clear handles this by completely removing all prior vector information from the clip.
Setting linestyle With the linestyle(width, color, alpha) method, you set up the appearance of all subsequently drawn lines. This command has no effect on previously drawn lines. The parameters you will use most often. width: The width of the line in pixels. The only valid values are zero or positive integers. color: The color you want the line to be. This is in a 24-bit number in decimal or hex format. alpha: The transparency of the lines. This can be from 0.0 to 1.0, representing a percent of opacity. A setting of 1.0 is obviously fully opaque, and 0.0 is fully transparent or invisible.
Drawing with lineto and moveto There are a couple of different ways to implement line drawing in a graphics language. One is to have a line command that takes a starting point and an ending point, and draws a line between them. The other way is to have a lineto command that takes a single point: the ending point of the line. If you haven t drawn anything yet, you ll be drawing from the point 0, 0.
Drawing with lineto and moveto Say you just type this line in a movie: You ll see a line going from the top-left corner (0, 0), to 100, 100 (assuming you ve set a line style). After you ve drawn at least one line, the ending point for that line will be the starting point for the next line. Finally, you can use the moveto method to specify a new starting point for the next line.
Drawing with lineto and moveto Let s create a simple drawing application.
Drawing with lineto and moveto
Drawing with lineto and moveto You could probably set up some simple controls to make it a full-featured drawing application without too much effort. Just create some variables for color and width, and create some buttons or other controls to change them, and call the linestyle method again with the new values and throw in a button that calls the clear method.
Drawing Curves with curveto The next drawing function, curveto(x1, y1, x2, y2). curveto takes two points. The first is a control point that affects the shape of the curve. The second is the ending point of the curve. The formula used is a standard formula for what is called a quadratic Bezier curve. This formula calculates a curve from one point to another, which curves toward the control point. Note that the curve will not touch the control point. It s more like the curve is attracted to it.
Drawing Curves with curveto
Drawing Curves with curveto
Curving Through the Control Point Now, say you wanted to have the curve hit the control point. You can use the following formula to calculate the actual control point so that the curve will go through the point you specify. you ll be starting out with x0, y0 and x2, y2 as the end points, and x1, y1 as the control point. I ll call the point you want the curve to go through xt, yt (t for target).
Curving Through the Control Point To see it in action, using the mouse coordinates as xt, yt, you just need to change two lines from the last document class. Change the lines To the following
Creating Multiple Curves First, I ll show you the wrong way of creating multiple curves. Basically, you start out with a number of points, draw a curve from the first through the second to the third, and so on.
Creating Multiple Curves
Creating Multiple Curves It all seems fine until you test it. In fact, it often looks a bit spiky. The problem is that there is no coordination between one curve and the next, except that they share a point.
Creating Multiple Curves We have to plug in a few more points to make it work right. Here s the strategy: Between each set of two points, you need a new point that sits exactly in the middle. You then use these as the starting and ending points for each curve, and use the original points as the control points.
Creating Multiple Curves Notice in the figure that the first and last midpoints are not used, and the first and last original points remain terminal points for the curves. You really need to make in-between points only for the second point up to the second-to-last point.
Creating Multiple Curves
Creating Multiple Curves
Creating Multiple Curves The following code, document class MultiCurve3.as, creates a closed curve using the same technique. Basically, it computes an initial midpoint, which is the average of the first and last points, and moves to that. Then it loops through all the rest, figuring midpoints for each one, finally drawing its last curve back to the initial midpoint.
Creating Multiple Curves
Creating Multiple Curves
beginfill and endfill The beginfill(color, alpha) method is so simple. The alpha value is now specified in values from 0.0 to 1.0 You can issue a beginfill command almost any time during the process of drawing. Flash will compute a shape beginning with wherever the drawing location happens to be and ending wherever the drawing location is when the endfill command is issued. If it never is, wherever the location is when the code completes for that frame and the frame is rendered.
beginfill and endfill Generally, though, the sequence is as follows moveto linestyle (if any) beginfill A series of lineto and curveto methods, ending at the original point moved to endfill You don t need to specify a line style. Remember that if you do not specify a line style, you get an invisible line, which is perfectly valid for drawing fills. If you do not draw a line back to the original point, Flash will close the shape as soon as you call endfill.
Gradient Fills begingradientfill(filltype, colors, alphas, ratios, matrix). This works in the same way as beginfill. The difference is in how the fill looks. A gradient fill is basically a fill of at least two colors. One part of the shape starts out with one color, and it slowly blends into another color.
Specifying the Fill Type You can create two kinds of gradient fills: linear and radial. For the begingradientfill(filltype, colors, alphas, ratios, matrix) method, the first parameter is filltype. It s a string that can contain: linear or radial. Rather than typing the strings, you can (and should) import the GradientType class and type GradientType.LINEAR or GradientType.RADIAL.
Setting the colors, alphas, and ratios To specify the colors, you must also specify the position of each color in the fill by assigning it a number from 0 to 255, where 0 is the start of the fill and 255 is the end. One for each color, are known as the ratios of the fill. If you wanted to make a three-color fill, you could say 0, 128, 255 as the ratios. You must also specify the transparency of each color in the blend. This is known as alpha and can be from 0.0 to 1.0.
Setting the colors, alphas, and ratios Each one of these arguments is an array. Because you are probably going to be passing in at least two colors, alphas, and ratios, and possibly many more. You could create a new array and populate it with your values for each parameter, like so: You can create and populate an array on the fly by listing the elements you want in it between square brackets, separated by commas:
Setting the colors, alphas, and ratios You can plug the array right into the begingradientfill statement as an argument. This defines two colors, two alpha values (both 100%), and start and end ratio values. Three arrays must all contain the same number of elements. If you define three colors, you must have three alphas and three ratios.
Creating the Matrix A matrix is a two-dimensional grid containing rows and columns of values used for calculating various values. Matrices are used extensively in graphics for rotating, scaling, and moving things. To use the matrix, you need to create a matrix object. This is an instance of the flash.geom.matrix class. There is a special method for use in creating the type of matrix you need for a gradient fill. It s called creategradientbox.
Creating the Matrix It takes minimally the width and height, and optionally the rotation and starting x, y position of the gradient you want. If you only specify a width and height, the last three values will default to 0.
Creating the Matrix
Creating the Matrix Now let s draw the square in a different location, by changing the drawing code. Now your square is all red. What happened? The gradient starts at 0 in x axis, and it s 100 pixels wide. So at the point your square begins, the gradient has already reached full red. So again, you are going to want the x, y of the matrix to be at the top-left point of your shape, like so:
Creating the Matrix Now let s try 3 colors. The next example is a straight alpha blend. The colors are the same; only the alpha changes: Try changing the angle now. Here s a 45-degree angle:
Creating the Matrix Using Math.PI/2 will make a vertical gradient by rotating it 90 degrees. Math.PI/2 will make it go up, and Math.PI will make it go from right to left. Finally, switch over to a radial gradient type:
Changing Colors with the ColorTransform Class First, you should know that a sprite, movie clip, or any other display object has a property called transform. This is an instance of the flash.geom.transform class, and contains various properties that you can use to scale, rotate, position, and colorize the movie clip. The property of interest here is colortransform. This is a property of a property of a display object, so it s accessed like this: Or, within a class that extends Sprite
Changing Colors with the ColorTransform Class The formula for transforming a particular color channel is like so, using the red channel as an example: When using ColorTransform, remember that it is part of the flash.geom package, so you ll need to import the class from there.
Changing Colors with the ColorTransform Class
Changing Colors with the ColorTransform Class just change the line to match the path of whatever picture you are using. If you are using the Flash IDE, just import your picture into the library, export it for ActionScript, and enter the class name Picture.
Filters Filters are bitmapped effects that can be applied to any display object. They can be applied in the Flash IDE via the Filters panel or at runtime via ActionScript. The following filters are included in AS3: Drop shadow Blur Glow Gradient bevel Color matrix Displacement map Bevel Gradient glow Convolution
Creating a Filter Filters are created by using the new operator and the name of the filter, passing in the required parameters. In this case, the parameters are blurx, blury, and quality. This example will blur an object 5 pixels on both axes, with a medium-quality blur. filters are in their own package, so you can put this at the beginning of the file: If you want to import all the filters in the package, use this:
Creating a Filter So now you have a blur filter, but how do you make it blur a particular object? Any display object has a property called filters. This is an array containing all the filters that have been applied to that object, since any object can have multiple filters applied. But alas, it s not that easy. Flash does not listen for changes to the filters array and won t take note of the change until a whole new array is assigned to filters.
Creating a Filter
Creating a Filter
Creating a Filter But what if you already have a filter applied and want to keep it, or worse yet, you aren t sure if there are any filters? All you have to do is get a reference to the array, push your filter onto it, and assign it back to the object s filters property. With this method, it doesn t matter whether there are already filters applied or not, your filter will just be added to the list. Or uses the concat method:
Animating Filters
Animating Filters
Animating Filters
Bitmaps As in AS 2, you first create a new BitmapData object by calling new BitmapData () with the following parameters: You need to import flash.display.bitmapdata package. Bitmaps will be created using 32-bit color if transparency is true, so you would specify the color using 0xAARRGGBB. If transparency is false, you are safe using 24-bit colors.
Bitmaps When you create a BitmapData object, you probably want some way to make it visible. In AS 2, use attachbitmap to add the bitmap to a movie clip. You might be thinking that you can now substitute addchild to add the bitmap to a display object. Well, yes and no. The problem is that addchild only works for objects that extend the DisplayObject class. BitmapData does not extend DisplayObject.
Bitmaps That s where the Bitmap class comes in to serve as a container for a BitmapData instance. The Bitmap does inherit from DisplayObject, so now you can add this object to the display list: the value of each and every pixel can be read or changed with getpixel, getpixel32, setpixel, and setpixel32. The difference between the two versions is that getpixel and setpixel use 24-bit numbers and ignore the alpha channel
Bitmaps
Bitmaps
Bitmaps
Bitmaps At first glance, you might think, Big deal. I could do the same thing with the drawing API or by attaching small movie clips and coloring them. True, you could do just that, but if you ve tried drawing hundreds and hundreds of individual shapes with the drawing API, you ll notice that the more you draw, the slower it goes. A bitmap is quite different, though. You could spray new layers of paint on with this program all day, with no change in its speed or efficiency.
Bitmaps If you want to begin to see some even cooler effects, throw the following line into the file, right after creating the Bitmap object, bmp:
Loading and Embedding Assets One important topic in rendering graphics is the concept of getting external assets, such as bitmaps or external SWFs, into your movie. There are two ways of doing this. One is to pull the asset in while the movie is running. This is known as loading. The other way is to embed the asset right in the SWF during compilation.
Loading Assets To load an asset, you create a Loader object. This is an instance of the flash.display.loader class. You then tell the loader to load either an external SWF or a bitmap, such as a JPEG, PNG, etc. In AS 3, you need to create an instance of flash.net.urlloader, passing in the path as a string.
Loading Assets
Embedding Assets There are many times when you have some external graphic that you just want to include in the SWF itself. How do you include external assets in the SWF? The answer is to embed them using the [Embed] metadata tag. Metadata refers to statements that you include in an ActionScript file that aren t actually ActionScript. Instead, they instruct the compiler to do certain things during the compilation process. In the case of the [Embed] tag, it tells the compiler to include a particular external asset into the final SWF file.
Embedding Assets Directly after the metadata line, you declare a variable of type Class, like so: You can now use that variable to create a new instance of that asset, like so:
Embedding Assets Note that the object created is of type Bitmap. Had you embedded an external SWF, the object created would be of type Sprite, like so:
Important Formulas in This Chapter
Important Formulas in This Chapter