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

Học Actionscript 3.0 - p 25 ppsx

10 333 0

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

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 10
Dung lượng 5,12 MB

Nội dung

Applied Examples Chapter 8: Drawing with Vectors 219 1 package com.learningactionscript3.color { 2 3 import flash.display.Sprite; 4 import flash.display.GradientType; 5 import flash.geom.Matrix; 6 import flash.display.Graphics; 7 8 public class ColorPickerGraphics extends Sprite { 9 10 public function ColorPickerGraphics() { 11 12 var colors:Array = [0xFF0000, 0xFFFF00, 0x00FF00, 13 0x00FFFF, 0x0000FF, 0xFF00FF, 14 0xFF0000]; 15 var alphas:Array = [1, 1, 1, 1, 1, 1, 1]; 16 var ratios:Array = [0, 42, 84, 126, 168, 210, 255]; 17 18 var spectrum:MovieClip = drawGradientBox(100, colors, 19 alphas, ratios); 20 addChild(spectrum); 21 22 colors = [0x000000, 0x000000]; 23 alphas = [0, 1]; 24 ratios = [0, 255]; 25 26 var overlay:Sprite = drawGradientBox(100, colors, 27 alphas, ratios, 28 deg2rad(90)); 29 addChild(overlay); 30 } In addition to the aforementioned arrays, the method also requires a size for the artwork (100 for both components) and, optionally, a rotation (90 degrees, in the case of the overlay, sent to the method in line 28). The rotation value can be omitted from the method call that creates the spectrum (lines 18 and 19), not just because it isn’t needed, but also because the matrixRotation parameter of the method (line 34) has a default value. Lines 35 and 36 create a sprite and reference to its graphics property, but the movie clip is not yet added to the display list. Instead, it is returned by the method in line 48 and added to the display list by the constructor, as discussed previously. Because the gradient data is sent to the method through its parameters, all that remains in lines 38 through 41 is to specify a linear gradient, create the matrix, and modify the matrix with the specified size and rotation, if any. The matrix is then applied using the createGradientBox() method (lines 40 and 41), a 1-pixel black line is specified in line 43, and all the gradient values are passed to the beginGradientFill() method in lines 44 and 45. Finally, lines 46 through 48 draw the rectangle, close the fill, and return the sprite to the constructor. N O T E Because the rotation angle is easier to specify in degrees, the value is converted to radians using the function at the end of the class. Download from Wow! eBook <www.wowebook.com> Part II: Graphics and Interaction 220 Applied Examples 31 //creating the gradient artwork 32 private function drawGradientBox(size:Number, colors:Array, 33 alphas:Array, ratios:Array, 34 matrixRotation:Number=0):Sprite { 35 var canvas:Sprite = new Sprite(); 36 var g:Graphics = canvas.graphics; 37 38 var fill:String = GradientType.LINEAR; 39 var matrix:Matrix = new Matrix(); 40 matrix.createGradientBox(size, size, 41 matrixRotation, 0, 0); 42 43 g.lineStyle(1, 0x000000); 44 g.beginGradientFill(fill, colors, alphas, 45 ratios, matrix); 46 g.drawRect(0, 0, size, size); 47 g.endFill(); 48 return canvas; 49 } 50 51 private function deg2rad(deg:Number):Number { 52 return deg * (Math.PI/180); 53 } 54 } 55 } To add this first step of our color picker to your project, all you need to do is create an instance of the class and add it to the display list. The source file color_picker_graphics_example.fla has already been created for this purpose. import com.learningactionscript3.color.ColorPickerGraphics; var picker:ColorPickerGraphics = new ColorPickerGraphics(); addChild(picker); Don’t forget that this example just demonstrates the dynamic creation of the picker. (No assets—all code!) In the next chapter, we’ll show you how to retrieve color values from the picker so you can use it in your own projects. A Custom Button Class The next applied example is a class that creates functioning buttons entirely with code, and it’s based on your work with the Graphics class in this chapter. The RoundRectButton_example.fla source file shows the class at work. This example introduces two new concepts. The first is the use of the SimpleButton class, which allows you to dynamically create traditional buttons that have up, over, down, and hit states, as well as cursor feedback. As such, they will behave just like buttons you create manually on the stage using Flash Professional’s drawing and symbol tools. The button’s behavior is simulated in Figure 8-25, showing not only cursor feedback in the over and down states (middle and bottom) showing up, over, and down states, but also the use of a brighter color in the over state, and darker color in the down state. RoundRectButton RoundRectButton RoundRectButton Figure 8-25. A custom button created by the RoundRectButton class Download from Wow! eBook <www.wowebook.com> Applied Examples Chapter 8: Drawing with Vectors 221 This color change is a result of the other new concepts discussed in this example: the ability to automatically interpolate a color that falls between two given color values. For example, given red and blue, the code will return purple. This is accomplished through the Color class, which is part of the fl.motion package. Our custom button class starts with the standard package syntax through line 19, declaring the package, importing classes, and declaring the class and class properties. Note, again, the custom package path. See the introduction to “Starting a Color Picker” earlier in this chapter for more information. 1 package com.learningactionscript3.ui { 2 3 import flash.display.Graphics; 4 import flash.display.MovieClip; 5 import flash.display.Shape; 6 import flash.display.SimpleButton; 7 import flash.text.TextField; 8 import flash.text.TextFieldAutoSize; 9 import fl.motion.Color; 10 11 public class RoundRectButton extends MovieClip { 12 13 private var _w:Number; 14 private var _h:Number; 15 private var _rad:Number; 16 private var _linW:Number; 17 private var _col:uint; 18 private var _txt:String; 19 private var _txtCol:uint; The constructor begins with lines 21 through 31, populating the class vari- ables with the parameter values passed in when instantiating the class. These include values for width, height, corner radius, line weight, color, text, and text color. It follows with the creation of a button and text field (both of which we’ll discuss in just a moment), and adding both to the display list of the class instance. 20 //constructor 21 public function RoundRectButton(w:Number, h:Number, 22 rad:Number, linW:Number, 23 col:uint, txt:String, 24 txtCol:uint){ 25 _w = w; 26 _h = h; 27 _rad = rad; 28 _linW = linW; 29 _col = col; 30 _txt = txt; 31 _txtCol = txtCol; 32 33 var btn:SimpleButton = createBtn(); 34 addChild(btn); 35 var labl:TextField = createLabel(); 36 addChild(labl); 37 } N O T E As mentioned previously, the Color class is available to Flash Professional users only. However, we have repro- duced the functionality in the com. learningactionscript3.color. ColorUtils class for users of other ActionScript editors. The sample source code for this chapter includes notes on its use. Download from Wow! eBook <www.wowebook.com> Part II: Graphics and Interaction 222 Applied Examples The createBtn() method assembles the button using the SimpleButton class. The createBtn() method calls createRoundRect() (reviewed in just a moment) to create a shape that serves as the background for each button state. The latter method requires only one parameter, which is the color used for the background shape. We determine these colors in lines 40 and 41 using the static method interpolateColor() from the Color class. Given two colors, the method cal- culates a color between the two. A third parameter indicates how close to either color the new value should be. For example, if you provided black and white and a weighting of 0.1, the new color would be closer to the first, or a charcoal gray. A weighting of 0.9 would be closer to the second color, or near white. To create the over-state color (lines 40 through 42), we calculate a value 30 percent between the main button color (visible in the button’s up state) and white. To determine the down state color (lines 43 through 45), we calculate a value 30 percent between the main button color and black. Accordingly, the over state is lighter than the up state, and the down state is darker than the up state. After each state is added to the SimpleButton instance (lines 47 through 50), the button is returned to the constructor. 38 //create all button states 39 private function createBtn():SimpleButton { 40 var ovCol:uint = Color.interpolateColor(_col, 41 0xFFFFFF, 42 0.3); 43 var dnCol:uint = Color.interpolateColor(_col, 44 0x000000, 45 0.3); 46 var btn:SimpleButton = new SimpleButton(); 47 btn.upState = createRoundRect(_col); 48 btn.overState = createRoundRect(ovCol); 49 btn.downState = createRoundRect(dnCol); 50 btn.hitTestState = btn.upState; 51 return btn; 52 } The createRoundRect() method (lines 54 through 62) presents no new mate- rial, but reviews an idea discussed in Chapter 4 about display lists. Notice that the method returns a shape instead of a sprite or movie clip. You can now create shapes with code, an improvement over prior versions of ActionScript. Unlike sprites and movie clips, shapes don’t support interactivity like mouse event listeners. However, they do require fewer resources to create. Because these shapes will be used inside a SimpleButton instance, which provides all the necessary interactivity, they are well suited for this situation. N O T E Static methods are called from the class, not an instance of the class. As such, the new keyword is not used to create an instance before invoking the method. Download from Wow! eBook <www.wowebook.com> Applied Examples Chapter 8: Drawing with Vectors 223 53 //create background shape for button states 54 private function createRoundRect(col:uint):Shape { 55 var rRect:Shape = new Shape(); 56 var g:Graphics = rRect.graphics; 57 g.lineStyle(_linW, _col); 58 g.beginFill(col, 0.5); 59 g.drawRoundRect(0, 0, _w, _h, _rad); 60 g.endFill(); 61 return rRect; 62 } Finally, the createLabel() method in lines 64 through 74 adds text to the button. Line 65 creates the text field, line 66 sets the width of the field to the width of the button, and line 67 sets the y location to slightly above the midpoint of the button, centering the text vertically. The text is centered hori- zontally in line 68, and line 69 sets the color of the text to the value passed into the class during instantiation. Finally, the specified button’s text is added to the field in line 70, all mouse interaction with the field is disabled in line 71, and the field is returned to the constructor in line 73. 63 //create text overlay for button 64 private function createLabel():TextField { 65 var txt:TextField = new TextField(); 66 txt.width = _w; 67 txt.y = _h / 2 - 6; 68 txt.autoSize = TextFieldAutoSize.CENTER; 69 txt.textColor = _txtCol; 70 txt.text = _txt; 71 txt.mouseEnabled = false; 72 73 return txt; 74 } 75 } 76 } Using this class is one way to present interface buttons to the user without having to precreate them in the Flash Professional interface. This restricts the ability to use custom artwork for individual buttons but keeps file size to a minimum. This is a simple demonstration, so the class is not very feature- rich when it comes to button styling options. However, that fact presents an ideal opportunity for you to practice what you’ve learned. Try to improve on this class by drawing specialized button shapes or, perhaps, by offering a choice between circular, rectangular, or rounded button shapes. N O T E As discussed in prior chapters, disabling mouse interaction with the text field is vital because if this step is omitted, the field will interfere significantly with the operation of the button. The cursor will change to an I-beam text editing cursor, the text will be selectable, and the field will intercept mouse events. Download from Wow! eBook <www.wowebook.com> Part II: Graphics and Interaction 224 What’s Next? learningactionscript3 Package The project package for this chapter includes ColorUtils , which provides color interpolation and tinting options to those using an ActionScript editor other than Flash Professional. ColorUtilsExample.fla, the example file in this chapter’s source archive, demonstrates its use. Also included is RoundRectButton , a custom code- only button class, and ColorPickerGraphics , the beginnings of a color picker that we’ll expand in Chapter 9. We will make use of one or more of these classes in future chapters to create small exercise files without building custom assets, and to increase your comfort with using classes. What’s Next? Manipulating visual assets with ActionScript is one of the most fun and most satisfying ways to learn the language. Drawing vectors does more than mini- mize file size. It also provides nearly limitless possibilities for creating genera- tive art. Combining data from other corners of the ActionScript world (user input, sound, mathematical calculations, random numbers, and so on) with vectors opens the door to compelling and instructional experiments. Vectors, however, are only half of the puzzle. Flash also provides an impressive range of classes for manipulating pixel-based assets at runtime. In the next chapter, we’ll look at working with bitmaps, including: • Drawing bitmaps at runtime • Applying blend modes such as lighten, screen, and Flash-specific options • Using simple filters like drop shadow, bevel, and blur, to enhance assets • Using complex filter techniques like convolution, color mixing, and dis- placement maps for special effects • Encoding custom bitmap data and saving those graphics to your hard drive Download from Wow! eBook <www.wowebook.com> 225 IN THIS CHAPTER Bitmap Caching The BitmapData Class Blend Modes Bitmap Filters Color Effects Image Encoding and Saving Adding Functionality to Your Color Picker What’s Next? Though largely known for its focus on vector assets, ActionScript also has an impressive arsenal of bitmap compositing features—options that work by layering, blending, and filtering pixel-based assets. ActionScript can even take a snapshot of vectors and manipulate the snapshot—behind the scenes with no loss in vector quality—giving you additional compositing options and, in many cases, performance gains. Although it’s unrealistic to expect ActionScript to achieve the feature breadth and depth of a pixel-editing application like Adobe Photoshop, you really can accomplish quite a bit with it. Among others, ActionScript features include a set of blend modes (darken, lighten, multiply, screen, and others that closely resemble Photoshop blend modes), basic filters (like drop shadow, bevel, and blur, akin to Photoshop layer styles), and advanced filter effects (like convolu- tion and displacement mapping, similar to Photoshop filters). Today, ActionScript 3.0’s speed and efficiency make bitmap manipulation practical in more processor-intensive scenarios than ever before. In this chap- ter, we’ll discuss several ways to add pixel pushing to your projects, including: • Bitmap Caching. Moving pixels on screen is a lot more efficient than recalculating the math required to display moving vectors every time a frame renders. Temporarily caching a bitmap representation of a vec- tor asset can reduce this strain and increase performance. • The BitmapData Class. Just as you use the Graphics class to draw with vectors, you can use the BitmapData class to draw with pixels. • Blend Modes. ActionScript can blend assets together to alter the appearance of one or more assets. Included are a standard set of blend modes, which you might find in a typical bitmap editing application, such as Darken, Multiply, Lighten, Screen, and so on. We’ll also dis- cuss a few ActionScript-specific blend modes that use transparency to great effect. draWIng WIth PIxeLs CHAPTER 9 Download from Wow! eBook <www.wowebook.com> Part II: Graphics and Interaction 226 Bitmap Caching • Bitmap Filters. Advanced filtering techniques such as blurring, sharpening, embossing, and distorting images can also be applied at runtime. They can even be applied to vector symbol instances, as well as bitmaps, without losing any fidelity or access to vector properties. • Color Effects. ActionScript 3.0 offers a few ways to manipulate color, ranging from applying simple tints to full manipulation of red, green, blue, and alpha channels of bitmap data. • Image Encoding. Bitmap data can even be encoded and saved in an external graphics format like JPG or PNG, using additional ActionScript libraries. Bitmap Caching First, we need to clear up a misconception: manipulating bitmaps in ActionScript does not mean you’ll lose all the advantages of crisp, clean vectors. ActionScript offers multiple ways to work with bitmap information, and, as you’ll see, vectors and bitmaps can work together well. In fact, using bitmaps judiciously can help you improve the look and performance of your vector animations. Vector animations can sometimes lag behind comparable bitmap animations because they’re much more processor intensive to manipulate. The resources needed to render all the vectors every time an update is required is invariably more demanding than moving and compositing bitmaps. With that in mind, ActionScript has the capability of caching, or temporar- ily storing, a version of a vector asset as a bitmap. It can then work with the bitmap instead of the original vector until it’s no longer optimal to do so. For example, consider a complex vector background over which other vectors are changing. If the background is unchanging, there’s no need to redraw the vector background repeatedly. Instead, it’s more efficient to work with the changing foreground elements on top of a bitmap. This situation is ideal for bitmap caching, the syntax for which is shown here: displayObject.cacheAsBitmap = true; By setting the cacheAsBitmap property to true, you can tell Flash Player to create a surface, a cosmetically identical bitmap representation of a symbol, to use for display purposes. Viewers won’t notice the difference, because the bitmap snapshot of the symbol is always kept current, through any changes, to prevent degradation of image quality. For example, if the symbol is scaled, the original cached bitmap is discarded and a new version is generated. Download from Wow! eBook <www.wowebook.com> Bitmap Caching Chapter 9: Drawing with Pixels 227 Because of this automatic updating feature, knowing when, and when not, to use bitmap caching is important. For example, if you’re moving several complicated vector assets around the stage, but doing little to alter their appearance, bitmap caching can dramatically improve performance. However, it’s usually unwise to enable caching if you’ll be scaling, rotating, or chang- ing the opacity of a display object frequently. These operations change the appearance of the display object, and it must be composited again with any surrounding elements. Therefore, a new cache is created each time such a change is made, so making many changes (and therefore caching frequently) in quick succession can slow things down. Soft-Edged Masks Optimizing performance isn’t the only reason to use cacheAsBitmap. Some features require this property to be true in order to function. For example, although you can use ActionScript to assign one display object to mask another, the mask has sharp edges by default because it can’t use varying degrees of alpha transparency. That is, any nontransparent pixel, no matter what its alpha value, is considered opaque when added to the mask. N O T E A mask is used to reveal a portion of a display object. Only the areas of the display object that overlap with the mask area are visible. If you use bitmap caching for both the masker (the display object that will serve as the mask) and maskee (the display object that will be masked), how- ever, ActionScript can composite the two elements as bitmaps. This allows alpha masks to composite semitransparent pixels using their actual alpha values to create a soft edge. Figure 9-1 illustrates this effect. The top image is of the mask itself, showing a soft edge. The middle image is the default appearance of an ActionScript mask, even when the mask contains varying degrees of opacity. The bottom image shows the same mask in use, but this time both the mask and revealed display object have their cacheAsBitmap property set to true. The following code snippet can be found in the as_mask.fla source file, which has two movie clips on the stage, with instance names of maskee and masker. 1 masker.cacheAsBitmap = true; 2 maskee.cacheAsBitmap = true; 3 maskee.mask = masker; Mask Mask applied without bitmap caching Mask applied with bitmap caching Figure 9-1. The same alpha mask applied without bitmap caching (above) and with bitmap caching (below) Download from Wow! eBook <www.wowebook.com> Part II: Graphics and Interaction 228 The BitmapData Class The BitmapData Class The BitmapData class is the real workhorse when it comes to ActionScript pixel-based manipulations. As its name implies, an instance of the BitmapData class contains not a bitmap, but the pixel color and alpha data that often comprise a bitmap. As with bitmap caching, you need not be confined to working with actual bitmaps to create a bitmap data instance. You can draw bitmap data from scratch or derive it from vector assets just as easily as from bitmap assets. Think of the latter process as working with a screenshot. Whether the display object contains a bitmap or a vector shape is immaterial. You can capture the bitmap data of that object in either case. Let’s start by looking at creating bitmap data from scratch and highlighting the difference between bitmap data and a bitmap. Creating Opaque Bitmaps There are two parts to creating a bitmap. One is the bitmap display object, and the other is the bitmap data. The bitmap display object is the picture you see on stage, and the bitmap data is a detailed description of the number of pixels used, their individual colors and alpha values, and so on. Your ultimate goal may be to display a bitmap, but you may also find it advantageous to work with bitmap data without ever actually displaying the pixels in ques- tion! (You’ll do just that later in the chapter when we demonstrate using a displacement map.) In our next example, we want to see the fruit of our labors, so we’ll work with both bitmap data and a bitmap. The following script, found in the bitmap_ from_scratch.fla source file, creates an instance of the BitmapData class, creates a bitmap using that data, and adds the bitmap to the display list. Without setting the x or y property of the bitmap, it appears at (0, 0). 1 var bmd:BitmapData = new BitmapData(100, 100, false, 0xFF0000FF); 2 var bm:Bitmap = new Bitmap(bmd); 3 addChild(bm); The first two arguments sent to the BitmapData class are the dimensions of the instance (100 × 100 pixels, in this example), and are required. If you intend only to create an empty BitmapData instance into which you’ll add content later, you need not add the remaining arguments. If you want to add visible pixels to your data instance at this stage, however, you can dictate the transparency and color of the data. The third parameter tells the class that this instance will not be transpar- ent. The last parameter is the color desired, but it uses a format we haven’t discussed previously. Instead of using the familiar 0xRRGGBB format, this class parameter must communicate alpha values, and thus requires the 32-bit 0xAARRGGBB hexadecimal format. This format adds two digits for alpha data at the beginning of the number. Line 1 of this code specifies FF, or full N O T E The maximum size of a BitmapData object in Flash Player 10 is determined by a combination of total number of pixels and dimensions. It can’t exceed 16,777,215 pixels. When creating a bit- map, square dimensions can’t exceed 4095 × 4095 pixels, and a single side can’t exceed 8,191 pixels. Currently, it’s possible to load bitmaps that exceed these side restrictions, as long as the total pixel count doesn’t exceed 16,777,215 pixels. This may change in the future. For more information, see http://kb2.adobe.com/cps/496/ cpsid_49662.html. Flash Player 9 limits are considerably more restrictive. BitmapData instances can’t exceed 8,294,400 pixels (2880 × 2880) or 2880 pixels on any side. If you exceed the maximum value in either dimension, in either player ver- sion, an instance is not created. Download from Wow! eBook <www.wowebook.com> . drawGradientBox( 100 , colors, 19 alphas, ratios); 20 addChild(spectrum); 21 22 colors = [0x 000 000 , 0x 000 000 ]; 23 alphas = [0, 1]; 24 ratios = [0, 255 ]; 25 26 var overlay:Sprite = drawGradientBox( 100 , colors,. import flash.display.Graphics; 7 8 public class ColorPickerGraphics extends Sprite { 9 10 public function ColorPickerGraphics() { 11 12 var colors:Array = [0xFF 000 0, 0xFFFF 00, 0x00FF 00, 13. 0x00FF 00, 13 0x00FFFF, 0x 000 0FF, 0xFF00FF, 14 0xFF 000 0]; 15 var alphas:Array = [1, 1, 1, 1, 1, 1, 1]; 16 var ratios:Array = [0, 42, 84, 126, 168, 2 10, 255 ]; 17 18 var spectrum:MovieClip = drawGradientBox( 100 ,

Ngày đăng: 06/07/2014, 18:20

TỪ KHÓA LIÊN QUAN