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

Essential ActionScript 3.0 PHẦN 8 pdf

94 350 0

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

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

THÔNG TIN TÀI LIỆU

Cấu trúc

  • Essential ActionScript 3.0

    • Part II Display and Interactivity

      • Programmatic Animation

        • Velocity-Based Animation

        • Moving On to Strokes ’n’ Fills

      • Drawing with Vectors

        • Graphics Class Overview

        • Drawing Lines

        • Drawing Curves

        • Drawing Shapes

        • Removing Vector Content

        • Example: An Object-Oriented Shape Library

        • From Lines to Pixels

      • Bitmap Programming

        • The BitmapData and Bitmap Classes

        • Pixel Color Values

        • Creating a New Bitmap Image

        • Loading an External Bitmap Image

        • Examining a Bitmap

          • getPixel32() Versus getPixel()

          • Transparency’s Effect on Color-Value Retrieval

          • ColorPicker: A getPixel32() Example

          • Retrieving the Color of a Region of Pixels

          • Other Examination Tools

        • Modifying a Bitmap

          • Improve Performance with BitmapData.lock()

          • ScribbleAS3: A setPixel32() Example

          • Assigning the Color of a Region of Pixels

          • Other Manipulation Tools

          • Resizing a Bitmap

        • Copying Graphics to a BitmapData Object

          • The BitmapData Class’s Instance Method draw()

            • How draw() handles Alpha channel values

            • No arbitrary screen captures

          • The BitmapData Class’s Instance Method copyPixels()

        • Applying Filters and Effects

          • Applying Filters

        • Freeing Memory Used by Bitmaps

        • Words, Words, Words

      • Text Display and Input

        • Creating and Displaying Text

          • Word Wrapping

          • Automatic Resizing

          • Rotated, Skewed, and Transparent Text Requires Embedded Fonts

        • Modifying a Text Field’s Content

        • Formatting Text Fields

          • Formatting Text with the TextFormat Class

            • Available TextFormat variables

            • Embedded font warning: Bold and italic require separate fonts

            • setTextFormat() does not apply to future text assignments

            • Applying paragraph-level formatting

            • Retrieving formatting information for a span of characters

            • Default formatting for text fields

          • Formatting Text with HTML

Nội dung

Velocity-Based Animation | 627 When creating user interface controls with animated effects, consider extending the Flex framework’s mx.core.UIComponent class rather than creating a custom animation library. The UIComponent class comes equipped with an extensive toolset for adding effects to custom user interface controls. Velocity-Based Animation In the Flash runtime, the specific timing of both scheduled screen-update checks and TimerEvent.TIMER events is not guaranteed. The Event.ENTER_FRAME event often exe- cutes later than the time scheduled by the designated frame rate, and TimerEvent.TIMER events often occur later than the time specified by a Timer object’s delay variable. These delays can result in unpredictable animation. To guarantee that a given object will travel a specified distance in a specified amount of time, we must set its position according to its velocity (i.e., its rate of speed in a particular direction). Example 24-10 shows the basic technique. // Create a circle to animate var circle:Shape = new Shape( ); circle.graphics.lineStyle(10, 0x666666); circle.graphics.beginFill(0x999999); circle.graphics.drawCircle(0, 0, 25); addChild(circle); // Create an Animator to animate the circle circleAnimator = new Animator(circle); // Register for mouse clicks stage.addEventListener(MouseEvent.MOUSE_DOWN, mouseDownListener); } // When the user clicks the stage, animate the // circle to the point that was clicked. private function mouseDownListener (e:MouseEvent):void { // Convert the point from the Stage instance's coordinate system // to this AnimationLibDemo instance's coordinate system var mousePt:Point = globalToLocal(new Point(e.stageX, e.stageY)); circleAnimator.animateTo(mousePt.x, mousePt.y, 500); } } } Example 24-10. Calculating position based on velocity package { import flash.display.*; import flash.events.*; import flash.utils.*; Example 24-9. An Animator demo (continued) 628 | Chapter 24: Programmatic Animation The Animator class shown earlier in Example 24-7 likewise uses velocity to guarantee that the object it animates will travel a specified distance in a specified amount of time. Moving On to Strokes ’n’ Fills Over the past few chapters, we’ve spent most of our time working with interactivity and animation. Over the next several chapters, we’ll change our focus to the cre- ation of three specific kinds of visual content: vectors, bitmaps, and text fields. // Moves an object a specified number of pixels per second, no matter what // the frame rate public class Animation extends Sprite { private var distancePerSecond:int = 50; // Pixels to move per second private var now:int; // The current time private var then:int; // The last screen-update time private var circle:Shape; // The object to animate public function Animation ( ) { // Create the object to animate circle = new Shape( ); circle.graphics.beginFill(0x0000FF, 1); circle.graphics.lineStyle(1); circle.graphics.drawEllipse(0, 0, 25, 25); addChild(circle); // Initialize timestamps then = getTimer( ); now = then; // Register for notification of scheduled screen-update checks addEventListener(Event.ENTER_FRAME, enterFrameListener); } // Handles Event.ENTER_FRAME events private function enterFrameListener (e:Event):void { // Calculate how much time has passed since the last move then = now; now = getTimer( ); var elapsed:int = now - then; var numSeconds:Number = elapsed / 1000; // Calculate the amount move based on the amount of time that // has passed since the last move var moveAmount:Number = distancePerSecond * numSeconds; // Move the object. In this case, the object's direction is 0 degrees. circle.x += moveAmount; } } } Example 24-10. Calculating position based on velocity (continued) 629 Chapter 25 CHAPTER 25 Drawing with Vectors26 In ActionsScript, primitive vectors, lines, and shapes are drawn via the Graphics class. However, the Graphics class is never instantiated directly; instead, each Action- Script class that supports programmatic vector drawing creates a Graphics instance automatically and provides access to it via the instance variable graphics. The dis- play classes that support vector drawing are Sprite, MovieClip, and Shape. Shape objects consume less memory than Sprite and MovieClip objects. Hence, to conserve memory, vector content should be drawn in Shape objects whenever the containment and interactive capabili- ties of the Sprite and MovieClip classes are not required. Graphics Class Overview As shown in Table 25-1, the Graphics class’s drawing tools can be broken down into five general categories: drawing lines, drawing shapes (also known as fills), defining line styles, moving the drawing pen, and removing graphics. Conceptually, lines and curves are drawn in ActionScript by a theoretical “draw- ing pen.” For all new Sprite, MovieClip, and Shape objects, the pen starts out at position (0,0). As lines and curves are drawn (via lineTo( ) and curveTo( )), the pen Table 25-1. Graphics class overview Purpose Graphics method Drawing lines curveTo( ), lineTo( ) Drawing shapes beginBitmapFill( ), beginFill( ), beginGradientFill( ), drawCircle( ), drawEllipse( ), drawRect( ), drawRoundRect( ), drawRoundRectComplex( ), endFill( ) Defining line styles lineGradientStyle( ), lineStyle( ) Moving the drawing pen moveTo( ) Removing graphics clear( ) 630 | Chapter 25: Drawing with Vectors moves around the object’s coordinate space, resting at the end point of the last line or curve drawn. The pen’s current position always indicates the starting point of the next line or curve to be drawn. To arbitrarily set the starting point of a line or curve, we use the moveTo( ) method, which “picks up” the drawing pen and moves it to a new position without drawing a line to the specified point. Drawing Lines To draw straight lines we use the lineTo( ) method, which draws a line from the cur- rent drawing pen position to a specified point (x, y). For example, the following code creates a new Sprite object and draws a line in it from (0, 0) to (25, 35): var canvas:Shape = new Shape( ); canvas.graphics.lineTo(25, 35); addChild(canvas); However, if you try that code as is, you may be surprised to find that no line appears on screen! By default, all lines and shapes drawn have no stroke. To cause a stroke to appear, we must use the lineStyle( ) method, which sets the visual stroke characteris- tics (thickness, color, etc.) for all lines and shapes subsequently drawn. For refer- ence, here is the method signature for lineStyle( ), showing the visual options available and their default values. Consult Adobe’s ActionScript Language Reference for details on each parameter. lineStyle(thickness:Number = 1.0, color:uint = 0, alpha:Number = 1.0, pixelHinting:Boolean = false, scaleMode:String = "normal", caps:String = null, joints:String = null, miterLimit:Number = 3) The lineStyle( ) method must be invoked explicitly for each new Sprite, MovieClip, and Shape object, or no stroke will appear (although filled regions can still be drawn without a stroke). Let’s look at a few examples showing various ways to modify the line style of canvas. The following code clears the line style (subsequent lines, curves, and fills are not stroked): canvas.graphics.lineStyle( ) The following code sets the line style to 1 pixel-thick, solid black: canvas.graphics.lineStyle(1) The following code sets the line style to 1 pixel-thick, solid green: canvas.graphics.lineStyle(1, 0x00FF00) Drawing Lines | 631 The following code sets the line style to 2 pixels thick, 50% transparent green: canvas.graphics.lineStyle(1, 0x00FF00, 50) Now let’s draw a line from (0, 0) to (25, 35), as before, but this time we'll apply a 3 pixel-thick blue stroke, causing the line to appear on screen: var canvas:Shape = new Shape( ); canvas.graphics.lineStyle(3, 0x0000FF); // Apply blue stroke canvas.graphics.lineTo(25, 35); addChild(canvas); Note that if the preceding line were drawn in a Sprite or MovieClip containing child display objects, it would appear behind those objects. Child display objects are always displayed in front of their parent and, hence, always obscure vector content drawn with ActionScript in that parent. For example, the following code adds a TextField object to a new Sprite object and then draws a line in that Sprite object. The TextField object obscures the line because the TextField object is the Sprite object’s child. // Create the Sprite and put it on screen var container:Sprite = new Sprite( ); addChild(container); // Create the TextField var msg:TextField = new TextField( ); msg.text = "Hello"; msg.border = true; msg.background = true; msg.autoSize = TextFieldAutoSize.LEFT; container.addChild(msg); // Draw the line container.graphics.lineStyle(3, 0x0000FF); container.graphics.lineTo(25, 35); Figure 25-1 shows the result of the preceding code. Content drawn via graphics in a Sprite or MovieClip always appears behind (i.e., is obscured by) any child objects of that Sprite or MovieClip. Figure 25-1. Vector content behind a TextField Hello 632 | Chapter 25: Drawing with Vectors When drawing multiple lines, each line’s stroke style can be set individually by call- ing lineStyle( ) before drawing each line. For example, the following code draws a square with progressively thicker lines, colored black, red, green, and blue: var canvas:Shape = new Shape( ); canvas.graphics.lineStyle(1, 0x000000); canvas.graphics.lineTo(100, 0); canvas.graphics.lineStyle(5, 0xFF0000); canvas.graphics.lineTo(100, 100); canvas.graphics.lineStyle(10, 0x00FF00); canvas.graphics.lineTo(0, 100); canvas.graphics.lineStyle(15, 0x0000FF); canvas.graphics.lineTo(0, 0); addChild(canvas); Figure 25-2 shows the results. Notice the end of the lines (known as the line caps) in Figure 25-2 are rounded by default. To select square caps instead of round ones, use the lineStyle( ) method’s caps parameter. For example, the following code creates a 10 pixel-thick green line with square caps: canvas.graphics.lineStyle(10, 0x00FF00, 1, false, LineScaleMode.NORMAL, CapsStyle.SQUARE); A thickness of 0 sets the stroke to hairline (a one-pixel line that does not increase in thickness when the object is scaled up or the Flash runtime’s display area is zoomed in). Other line-scaling options can be set via the lineStyle( ) method’s scaleMode parameter. To turn the stroke off completely, set thickness to undefined or call lineStyle( ) with no parameters. For example: canvas.graphics.lineStyle(undefined); // Turn off lines in canvas canvas.graphics.lineStyle( ); // Same thing To move the drawing pen without drawing any line at all, use moveTo( ). For exam- ple, suppose we want to draw a single straight line from (100,100) to (200, 200) in a new Shape object. We first move the pen from (0,0) to (100,100) using moveTo( ) and then draw a line from there to (200,200) using lineTo( ), as follows: var canvas:Shape = new Shape( ); // Create the Shape to draw in canvas.graphics.lineStyle(1); // Set the stroke to 1 point, black canvas.graphics.moveTo(100, 100); // Move the pen without drawing a line canvas.graphics.lineTo(200, 200); // Draw the line (this also moves the pen) Figure 25-2. Lines of varying thicknesses Drawing Curves | 633 Drawing Curves To draw curved lines we use the curveTo( ) method, which has this signature: curveTo(controlX:Number, controlY:Number, anchorX:Number, anchorY:Number) The curveTo( ) method draws a quadratic Bézier curve from the current drawing pen position to the point ( anchorX, anchorY) using an off-curve control point of (controlX, controlY). The curve tangents at each endpoint run in the direction of the line from the endpoint to the control point. The Bézier curve is contained in the convex hull of its three control points. Conceptually speaking, the straight line that would run from the pen position to the end point ( anchorX, anchorY) is pulled by the control point (controlX, controlY)to make a curve. If any of curveTo( )’s arguments are missing, the operation fails silently, and the position of the drawing pen remains unchanged. As with lineTo( ), the stroke characteristics of the curve (thickness, color, alpha, etc.) are determined by the most recent call to lineStyle( ). The following code draws a four-point black curve from the drawing pen’s default position (0, 0) to the anchor point (100, 0) using the control point (50, 100). The resulting curve is shown in Figure 25-3. var canvas:Shape = new Shape( ); addChild(canvas); canvas.graphics.lineStyle(4); // Set the stroke to 4-point, black canvas.graphics.curveTo(50, 100, 100, 0); // Draw the curve After a curve is drawn, the drawing pen remains at the end point of the curve. Hence, multiple calls to curveTo( ) and/or lineTo( ) can be used to draw complex curves or closed shapes, such as circles and polygons, as discussed in the next section. Figure 25-3. A quadratic Bézier curve (0, 0) pen position (100, 0) anchor point (50, 100) control point 634 | Chapter 25: Drawing with Vectors Curves drawn on fractional pixels often appear blurry. To sharpen blurry, antialiased lines, set lineStyle( )’s pixelHinting parameter to true. Sometimes it is more convenient to specify three points on a curve rather than two anchor points and a control point. The following code defines a custom curveThrough3Pts( ) method that accepts three points as arguments and draws a qua- dratic curve that passes through them. The second point is assumed to be halfway along the curve in time (t = .5): // Adapted from Robert Penner's drawCurve3Pts( ) method public function curveThrough3Pts (g:Graphics,startX:Number, startY:Number, throughX:Number, throughY:Number, endX:Number, endY:Number) { var controlX:Number = (2 * throughX) - .5 * (startX + endX); var controlY:Number = (2 * throughY) - .5 * (startY + endY); g.moveTo(startX, startY); g.curveTo(controlX, controlY, endX, endY); } // Usage var canvas:Shape = new Shape( ); addChild(canvas); canvas.graphics.lineStyle(2, 0x0000FF); curveThrough3Pts(canvas.graphics, 100, 100, 150, 50, 200, 100); For more information on curve mathematics in ActionScript, see Jim Armstrong’s “TechNotes,” at http://www.algorithmist.net/technotes.html. Drawing Shapes To draw an arbitrary shape (i.e., to paint a color into the geometric area between three or more points), follow these steps: 1. Choose the starting point of the shape (either the default (0,0) or a point speci- fied via moveTo( )). 2. Start the shape with the beginBitmapFill( ), beginFill( ),orbeginGradientFill( ) method. 3. Draw the shape’s outline with a series of lineTo( ) and/or curveTo( ) calls, the last of which should end at the starting point specified in Step 1. 4. Close the shape with endFill( ). The beginFill( ) method fills the shape with a solid color; the beginGradientFill( ) method fills the shape with a gradient (a blend between two or more colors); and the beginBitmapFill( ) method fills a shape with the specified bitmap (tiled if desired). Drawing Shapes | 635 For example, the following code draws a red triangle with a five pixel-thick black outline. Notice that the default start point (0, 0) matches the endpoint: var triangle:Shape = new Shape( ); triangle.graphics.beginFill(0xFF0000, 1); triangle.graphics.lineStyle(20); triangle.graphics.lineTo(125, 125); // Draw a line down and right triangle.graphics.lineTo(250, 0); // Draw a line up and right triangle.graphics.lineTo(0, 0); // Draw a line left triangle.graphics.endFill( ); addChild(triangle); Figure 25-4 shows the result of the preceding code. Notice that the corners of the triangle in Figure 25-4 are rounded. To set the render- ing style for corners, we use lineStyle( )’s joints parameter. For example, the follow- ing code changes the corner-rendering style to “mitered” by assigning the constant JointStyle.MITER to the joints parameter: triangle.graphics.lineStyle(20, 0, 1, false, LineScaleMode.NORMAL, CapsStyle.ROUND, JointStyle.MITER); Figure 25-5 shows the result; pay special attention to the new corners of the triangle. To draw various kinds of rectangles and ellipses, the Graphics class provides the fol- lowing convenience methods: drawCircle( ), drawEllipse( ), drawRect( ), drawRoundRect( ), and drawRoundRectComplex( ). The “round rect” methods draw rectangles with rounded corners. All of the shape-drawing convenience methods are used with the familiar lineStyle( ) and beginFill( ) methods. However, it is not neces- sary to call endFill( ) after drawing the shape because each convenience method does so automatically. Figure 25-4. A triangle Figure 25-5. Triangle with mitered joints 636 | Chapter 25: Drawing with Vectors The following code shows the general use of the shape drawing methods. It uses drawRect( ) to draw a blue rectangle with a black one-pixel outline: var canvas:Shape = new Shape( ); addChild(canvas); // Set line thickness to one pixel canvas.graphics.lineStyle(1); // Set the fill color to blue canvas.graphics.beginFill(0x0000FF); // Draw the shape canvas.graphics.drawRect(0, 0, 150, 75); // Notice no call to endFill( ) here Removing Vector Content To remove all vector drawings in an object, we use the Graphics class’s instance method clear( ). For example: var canvas:Shape = new Shape( ); // Draw a line canvas.graphics.lineStyle(3, 0x0000FF); // Apply blue stroke canvas.graphics.lineTo(25, 35); addChild(canvas); // Erase the line canvas.graphics.clear( ); When the clear( ) method is invoked, the object’s line style reverts to undefined (no stroke). After calling clear( ), lineStyle( ) must be called again, or no stroke will appear on lines and shapes. Calling clear( ) also resets the drawing pen position to (0, 0). Note that clear( ) affects vector content in a single object only; if that object is a Sprite or MovieClip instance, clear( ) does not erase any vector content in its chil- dren, nor does it remove them. The following code draws a single line with a random stroke style every 250 millisec- onds. It uses clear( ) to erase the previously drawn line. package { import flash.display.*; import flash.utils.*; import flash.events.*; public class RandomLines extends Sprite { private var s:Shape; public function RandomLines ( ) { s = new Shape( ); addChild(s); [...]... a sampling of common bitmap programming techniques Bear in mind, however, that exhaustive coverage of bitmap programming in ActionScript could well fill a book of its own For further study, consult Adobe’s ActionScript Language Reference 6 48 The BitmapData and Bitmap Classes In ActionScript, the BitmapData class represents bitmap-formatted image data such as that in Figure 26-1 Each BitmapData instance... (BitmapData), ActionScript s bitmap architecture lets many different Bitmap objects simultaneously display the same BitmapData object, each with its own display characteristics (i.e., different scale, rotation, cropping, filters, transforms, and transparency) Before we learn how to create a new bitmap image, let’s take a quick look at how colors are represented in ActionScript Pixel Color Values In ActionScript, ... succeeds var imgData:BitmapData = new BitmapData(20, 20, true, 0x330000FF); trace(imgData.getPixel32(0, 0)); // Displays: 85 56 382 71 // (Alpha is 0x33) getPixel32() Versus getPixel( ) To provide a convenient way to retrieve a pixel’s color value without its Alpha channel information, ActionScript offers the BitmapData class’s instance method getPixel( ) The getPixel( ) method takes the exact same form... color channels The amount of each channel in a given color ranges from 0 to 255 Accordingly, in binary, each channel occupies 8 of the 32 bits in the color value, as follows: Alpha, Pixel Color Values | 649 bits 24–31 (the most significant byte); Red, bits 16–23; Green, bits 8 15; and Blue, bits 0–7 The higher the value of Red, Green, or Blue, the more each color contributes to the final color If all... ( ):int { return (value >> 8) & 0xFF; } public function getBlue ( ):int { return value & 0xFF; } public function toString ( ):String { return toStringARGB( ); } public function toStringARGB (radix:int = 16):String { var s:String = "A:" + ((value >> 24)&0xFF).toString(radix).toUpperCase( ) + " R:" + ((value >> 16)&0xFF).toString(radix).toUpperCase( ) + " G:" + ((value >> 8) &0xFF).toString(radix).toUpperCase(... object using the following general code: new BitmapData(width, height, transparent, fillColor) The width and height parameters indicate the pixel dimensions of the image, which have a maximum value of 288 0 The image dimensions cannot be changed after the BitmapData object is created The transparent parameter indicates whether the image should support per-pixel transparency (i.e., whether the Alpha channel... top-left pixel (i.e., the pixel at coordinates (0, 0)): var imgData:BitmapData = new BitmapData(20, 20, false, 0xFF0000FF); trace(imgData.getPixel32(0, 0)); // Displays: 42 781 90335 The pixel’s color value is a large number (42 781 90335) because the alpha channel’s value is 255, so the bits in the color value’s most significant byte are all 1’s: 11111111 00000000 00000000 11111111 In decimal format,... 0x330000FF); trace(imgData.getPixel32(0, 0)); // Displays: 42 781 90335 // (Alpha is 0xFF, not 0x33) The alpha value of pixels can be set in transparent bitmaps only (i.e., bitmaps created with the value true passed to the transparent parameter of the BitmapData constructor) For example, the following code again creates a blue square bitmap but 6 58 | Chapter 26: Bitmap Programming this time enables transparency... BasicShape extends Shape { // Fill style protected var fillColor:Number = 0xFFFFFF; protected var fillAlpha:Number = 1; // Line style Use mitered joints instead of round (the ActionScript // default) All other defaults match ActionScript' s defaults protected var lineThickness:Number = 1; protected var lineColor:uint = 0; protected var lineAlpha:Number = 1; protected var linePixelHinting:Boolean = false;... shadow As we’ll see later, the BitmapData class can even be used to create animated effects and to perform bitmap-based collision detection To use most of BitmapData’s tools, we must understand the format ActionScript uses to describe a pixel’s color value, discussed in the next section As the name suggests, a BitmapData object is not, itself, an image; it is only the bitmap-formatted data representing . ); canvas.graphics.lineStyle(1, 0x 000 000 ); canvas.graphics.lineTo( 100 , 0) ; canvas.graphics.lineStyle(5, 0xFF 000 0); canvas.graphics.lineTo( 100 , 100 ); canvas.graphics.lineStyle( 10, 0x00FF 00) ; canvas.graphics.lineTo (0, 100 ); canvas.graphics.lineStyle(15,. (i.e., a 3- sided Polygon) poly = new Polygon( [0, 50, 100 ], [ 50, 0, 50] ); poly.setStrokeStyle(4, 0x 333 333 ); poly.setFillStyle(0x00FF 00) ; // Create a star star = new Star(5, 30 , 80 ) ; star.setStrokeStyle(4,. Rectangle( 50, 100 ); rect.setStrokeStyle(1, 0xFF 000 0); rect.setFillStyle(0x 000 0FF); // Create an ellipse ell = new Ellipse(2 50, 50) ; ell.setStrokeStyle(2, 0xFFFF 00) ; ell.setFillStyle(0xED994F);

Ngày đăng: 12/08/2014, 16:21