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

Beginning ActionScript 2.0 2006

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

13

Working with Vector

Graphics

Flash 8 provides unprecedented control over every pixel on the stage. In previous versions of Flash you had the drawing API coupled with tricks and techniques to accomplish drawing tasks that required pixel-level precision. Pixel-level control had not been one of Flash’s strong points. But all that’s changed in Flash 8, which provides a drawing API that encompasses a wide range of graphic control including color matrices and gradients.

One of the most important Flash 8 pixel-control objects is the Bitmap object. It allows specific pixel examination and modification. With methods such as getPixel, setPixel, and others, most detail-oriented developers will be thrilled with the Bitmap object.

Flash 8 also provides a good selection of blending modes, including Luminosity, Lighten, Darken, and Multiply. Blending modes enable you to composite one layer of a movie clip into the next clip by displaying only those pixels that are, for example, darker than the underlying layers. You may be familiar with blending modes used in popular image editing programs. They permit a wider range of movie clip effects than ever before.

The capability to apply real-time filters to pixel data on the stage is also new. These filters, which are similar to those found in image editing programs, include drop shadows, blurring, gradients, bevels, and more.

Flash 8 also enables robust video integration, and not only on a user interface level — using filters, color, and blending modes, you can integrate video so well that the video rectangle is a thing of the past.

In this chapter you explore the Flash 8 drawing API as it has changed in Flash 8 and find out how to work with filters.

Chapter 13

Using the Drawing API

The drawing API (application programming interface) enables you to use ActionScript to draw vector shapes directly to the stage.

For beginners, it is easy to draw an object on the stage using the IDE tools, wrap the object in a movie clip, and call it onto the stage when needed from the library. That’s certainly an avenue you can choose, but many situations call for dynamic graphics and user interface elements that are much more easily managed using reusable code blocks that create graphics very quickly, while keeping initial SWF file load size down.

You should keep a couple of things in mind if you’ve used the drawing API in past versions of Flash. You must take into consideration your target player version and publish for that version. If you attempt to use Flash 8 syntax and compile to Flash 7, some of the drawing methods may not act as expected. Also, if you use Flash 6 or 7 syntax and publish for Flash 8, you may see unexpected results.

The Flash 8 drawing API provides bitmap fills, line gradients, and color matrixes. The Matrix is not just a movie, it is an object that is used to transform and manipulate the behavior of bitmap and vector pixels.

Tools for Drawing Vectors with ActionScript

The drawing methods of the MovieClip object are very simple and follow conventions found in other languages that are capable of the same task:

 

lineStyle()

 

moveTo()

 

beginFill()

 

lineTo()

 

beginBitmapFill()

 

curveTo()

 

beginGradientFill()

 

clear()

endFill()

That might not seem to be very many methods, but in combination and with the Matrix object, there’s almost nothing you can do with IDE tools that you can’t do with ActionScript. ActionScript enables a few features not seen in the IDE, whereas the IDE offers only one or two capabilities not found in ActionScript. You’ll notice these as you read through the methods.

The following sections explore ActionScript’s drawing methods.

lineStyle()

The lineStyle()method is used to set specific properties about the behavior of a line when one is drawn. Each time you need a new type of line, this method must be called.

lineStyle() has eight parameters (five more than it had in Flash 6 and 7). Following are their descriptions:

320

 

 

Working with Vector Graphics

 

 

 

 

Parameter

Description

 

 

 

 

thickness:Number

thickness specifies in pixels the width of the line along its axis. A

 

 

higher number creates a fatter line. When these lines are scaled up,

 

 

they appear thicker and thicker, unless you use the noScale

 

 

parameter. thickness can also be used to specify a zero-width

 

 

line, which produces a one-pixel-wide line that, when scaled, does

 

 

not change thickness regardless of the noScale parameter value.

 

rgb:Number

rgb is the hexadecimal value of the color of the line. The RGB

 

 

value accepts a number with the format 0xRRGGBB. The 0x is sim-

 

 

ply a hexadecimal designator that tells Flash how to handle the

 

 

number values to convert to red, green, and blue values.

 

alpha:Number

A numeric value of 0–100 that sets the alpha value (transparency) of

 

 

the line. It is not an RGBA value. Values between –255 and 255 do not

 

 

affect this value. Numbers below 0 are ignored and are rendered as 0.

 

 

Numbers higher than 100 also are ignored; they’re rendered as 100.

 

pixelHinting:Boolean

Pixel hinting is a means of smoothing the look of the line. This

 

 

parameter is a Boolean. A true value renders the line with interpo-

 

 

lated pixels along its edges so it blends more smoothly with the

 

 

pixels surrounding it. The default value is false.

 

noScale:Boolean

The noScale parameter’s default is a Boolean false. Setting it to

 

 

true preserves the thickness of the line on its axis regardless of

 

 

length changed during scaling. (To see how this works, create an

 

 

example line and scale the clip, setting this value to false, and

 

 

then to true.)

 

capsStyle:String

This parameter is a String that defaults to round. In the past, all lines

 

 

ended with a rounded tip. When creating corners, this caused a

 

 

square to look somewhat less sharp than what might have been

 

 

needed. Flash 8 makes line tip control much more precise. The three

 

 

string values available are round, square, and none. square gives

 

 

you a squared-off line end, producing an extremely sharp line.

 

 

round makes a line that has a much softer appearance at its tip. This

 

 

might sound not as desirable, but round-tipped lines easily create

 

 

simple circles and large rounded corners on squares. A value of none

 

 

creates a line tip similar to the square value, although the line ends

 

 

abruptly at whatever control point is specified. It can be used when

 

 

specific height values are required, such as for absolutely square line

 

 

joints, or lines used to show precise values in information graphics.

 

jointStyle:String

The jointStyle parameter is also a String. It is similar to

 

 

capStyle, except it defines how lines connect to one another when

 

 

lineTo is called consecutively. The values are miter, round, and

 

 

beveled. A miter joint produces a very sharp point, and a round

 

 

joint produces a rounded joint, giving a softer look. The beveled

 

 

joint is a squared-off joint that does not come to a sharp point, but

 

 

each line ends abruptly in a style similar to capStyle:none.

 

 

Table continued on following page

321

Chapter 13

Parameter

Description

 

 

miterLimit:Number

miterLimit is a Number value from 0 to 255 that stipulates how

 

many pixels a corner should be allowed to extend beyond the con-

 

trol point when using a miter joint. There are, of course, limits to

 

this value depending upon the angle of the two lines being joined.

 

If two lines join at an acute angle, for example, the miter corner can

 

only extend so far before it becomes a sharp point.

beginFill()

beginFill()remains unchanged and works as it did in Flash 6 and 7. It defines the color that should fill the space created by lineTo. This method fills a space with color regardless of whether lineTo closes a final gap. An open gap is ignored and the fill uses the shortest distance between the last lineTo and the previous lineTo method calls to close the shape. Using fragmented shapes can lead to undesired behavior. Always be sure to close your shapes with the appropriate lineTo set. beginFill() accepts the following two parameters:

Parameter

Description

 

 

rgb:Number

rgb is the hexadecimal value of the fill color, a number in the for-

 

mat 0xRRGGBB.

alpha:Number

The alpha value is a Number from 0 to 100. It is not an RGBA

 

alpha value, and it does not accept a value below 0 or above 100.

beginBitmapFill()

beginBitmapFill() is similar to the beginFill() method, except that it fills a shape with the contents of a bitmap instead of a single specified color. You choose how the bitmap fills the shape: repeating or nonrepeating. A repeating image tiles until the entire bitmap is filled; a nonrepeating image does not tile. Methods also exist that determine how the bitmap is smoothed. You can specify any Bitmap object to occupy the target shape and use all of the bitmap methods available to manipulate the bitmap.

beginBitmap() takes the following four parameters:

Parameter

Description

 

 

source:BitmapData

The source parameter defines the source bitmap to fill the shape.

 

You can modify the bitmap any way you want before defining this

 

parameter. If you make changes to your bitmap you will need to

 

call the beginBitmapFill() method again to reflect changes.

322

 

 

Working with Vector Graphics

 

 

 

 

Parameter

Description

 

 

 

 

matrixObject:Matrix

This parameter is a Matrix object, which is found in the Flash.geom

 

 

object. It defines transformations to apply on the bitmap at the time

 

 

it is drawn within the shape. Subsequent transformations must be

 

 

called again by beginBitmapFill() to reflect changes. You may

 

 

transform your bitmap before calling this method. The bitmap

 

 

transforms from the state it is received in. Here’s an example

 

 

matrix:

 

 

var myMatrix = new flash.geom.Matrix();

 

 

myMatrix.scale(.5,.5);

 

 

In it, the bitmap is scaled to half its original size. Many properties

 

 

associated with the Matrix object enable you to manipulate the

 

 

Bitmap object.

 

repeat:Boolean

The repeat parameter takes a Boolean value. If true, the image

 

 

is repeated until it fills the entire shape. If false (the default),

 

 

the edges of the image are extruded until they reach the edge of

 

 

the bitmap. repeat can produce some interesting fill effects.

 

 

Use it in conjunction with a Matrix object to create complex fill

 

 

transformations.

 

smooth:Boolean

The smooth parameter is a Boolean. If true, the pixels in the

 

 

bitmap are rendered with a smoothing method. Smoothing can

 

 

absorb CPU time, and cause complex transformations to slow

 

 

down. Consider the activities currently using CPU cycles in your

 

 

SWF before employing smoothing in large or complex bitmaps.

 

 

The default value is false.

beginGradientFill()

beginGradientFill() fills a shape with a gradient. In Flash 8 it enables complex transformations and effects. The method accepts seven parameters, as described here:

Parameter

Description

 

 

type:String

type’s values are linear or radial. A linear gradient fades from

 

the beginning index to an ending index without bending or wrap-

 

ping. A radial gradient begins from a specified focal point and

 

fades outward. Both can be modified using a matrix.

colors:Array

colors is an Array object of hexadecimal color values. The fill uses

 

the value to create the gradient.

alphas:Array

alphas is an array of 0–100 alpha values associated with each

 

value in the colors array. If an alpha array is defined, it must be the

 

same length as the color array.

 

Table continued on following page

323

Chapter 13

Parameter

Description

 

 

ratios:Array

ratios is an of array of 0–255 values. The value defines the per-

 

centage of width the corresponding color in the colors array may

 

occupy across the full width of the fill. This array must be the same

 

length as the colors array.

matrix:Object

The Matrix object has a createGradientBox method to conve-

 

niently manipulate a gradient fill. beginGradientFill() expects

 

the values in the matrix created by the createGradientBox.matrix

 

may fail if not all expected values are present. createGradientBox

 

is explained in “The Matrix Object” section later in this chapter.

spreadMethod:String

spreadMethod accepts String values of pad, reflect, or repeat.

 

pad, the default value, begins a gradient fill at the index specified

 

and takes it to the end point specified. If space within the shape

 

exists beyond the end point, the shape is filled with the last outer

 

rgb value of the fill until the shape is completely filled.

 

reflect begins and ends the fill at the index and end point speci-

 

fied. At that point the algorithm is reversed and the gradient is

 

filled, returning to the original values through the color array. This

 

flip-flopping of the color array direction continues until the shape

 

is completely filled.

 

repeat also begins the fill at the specified index and takes the gra-

 

dient to the specified end point. Then the fill starts again, repeating

 

the gradient until the entire shape is filled.

interpolationMethod:String

interpolationMethod accepts a String value of RGB or Linear

 

RGB. It specifies how the color should be spread out in a gradient fill

 

between colors. LinearRGB spreads the color evenly, creating new

 

mixed color values between two colors rather than the default RGB

 

interpolation method of fading the values between the two colors.

 

 

endFill()

The endFill() method commits the fill defined in any of the beginFill() methods. It has no parameters and uses the fill method values to fill the last closed shape created by the curveTo and lineTo methods.

moveTo()

The moveTo() method places the drawing position within a movie clip without defining a line. It defaults to 0,0 if no lineTo or curveTo methods have been called.

moveTo takes two parameters: moveTo(x:Number, y:Number). x and y are both Number values that specify their respective positions of the index of the drawing tool.

324

Working with Vector Graphics

lineTo()

You use the lineTo() method to move the index position of the drawing tool. If lineStyle is defined, a line is drawn from the previous index of the drawing object index using that line style. This last index may have been positioned using curveTo, moveTo, or lineTo methods.

lineTo takes two parameters: lineTo(x:Number,y:Number). x and y are Number values that specify their respective index of the drawing tool.

curveTo()

Use the curveTo() method to draw a curved edge from the last index position of the Drawing object. If lineStyle is defined, a line is drawn along the curve using the style specified. The last index may have been positioned using curveTo, lineTo, or moveTo.

The curve is a Bezier curve, which is made up of only three points (start, end, and one in between) that affect its shape. A control point basically manipulates a line to prefer a specific path as it is drawn toward the anchor (end) point. The maximum radius of the curve is determined by the difference in position between the anchor point and control point.

curveTo takes the following parameters:

Parameter

Description

 

 

controlX:Number

controlX’s Number value is the x position of the curve’s control

 

point. A control point x that differs greatly from an anchor point x

 

creates a more extreme curve.

controlY:Number

controyY’s Number value is the y position of the curve’s control

 

point. A control point y that differs greatly from an anchor point y

 

creates a more extreme curve.

anchorX:Number

anchorX’s Number value is the x position of the end point of the

 

line. This point is the final x point of the line drawn.

anchorY:Number

anchorY’s Number value is the y position of the end point of the

 

line. This point is the final y point of the line drawn.

clear()

The clear() method clears all graphics drawn with the Drawing object on the timeline on which it is called. It has no parameters.

Drawing Vectors with ActionScript

To help you understand the basic concepts of the drawing API and how the coordinate values used in the drawing API relate to the stage, create a simple square. When you are done with the example, try making other shapes and lines. Experimenting with the methods helps you learn them quickly.

325

Chapter 13

Try It Out

Create a Simple Square

In this example you use some of the fundamental drawing methods to create two draggable anchor points as well as one draggable control point so that you can see how control points work.

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

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

with (this) { beginFill(0xFF0000, 60); lineStyle(2, 0x666666, 100); moveTo(20, 20);

lineTo(20, 120); lineTo(120, 120); lineTo(120, 20); lineTo(20, 20);

endFill();

lineStyle(2, 0xFF000000, 30); moveTo(60, 60);

lineTo(60, 160); lineTo(160, 160); lineTo(160, 60); lineTo(60, 60);

}

3.Test your movie in the debug player. You will see three squares on the screen. These are draggable. Move them around to see how the anchor points and control points interact to create Bezier curves.

How It Works

In this example you use drawing methods to create a simple shape and see how the beginFill method integrates with lineTo methods to create a unified vector object.

When lineTo is used without beginFill, no fill is created by default. You can create outline shapes by just using lines.

You can use as many points defined by lineTo method calls as you want to create complex shapes and lines; however, every point takes memory. The more points defined in a vector drawing, the more intensive it is for Flash to redraw that shape in an animation. Too many points in a vector shape can slow down your entire application. Be aware of the target machine, and test, test, test.

Finally, note that the first and last lineTo methods for each square are identical. Remove line 8 (lineTo(20, 20);) to see what happens to the fill shape. The fill shape closes the gap regardless of the fact that the shape isn’t closed in this case. Always be aware of closing shapes. Although a shape may appear closed, when modified by other ActionScript objects or functions it can produce unexpected results because the fill shape defaults to the closest pixel to close the shape.

Also try manipulating the alpha value in the beginFill method. If you change it to 100, which means it will be completely opaque, the second square, drawn after the first, is still completely visible. This is because any new points are drawn over old points. However, even when a new shape overlays an older

326

Working with Vector Graphics

shape, the older shape’s vector points remain in memory. It is up to you to use the clear method when appropriate, or a Bitmap or MovieClip object to separate and control each shape individually.

With this exercise under your belt, you’re ready to use a basic set of drawing API methods to create and manipulate more complex vector graphics at runtime using methods and interactivity.

Try It Out

Create a Bezier Curve Using a Control Point

In this example you use some of the fundamental drawing methods to create two draggable anchor points as well as one draggable control point so that you can see how the curveTo control points affect a line.

1.Open a new Flash Document. Save the Flash document as curveTo.fla in your work folder.

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

function connect() { this.clear();

this.lineStyle(3,0x660000,100); this.moveTo(anchorOne._x, anchorOne._y);

this.curveTo(controlOne._x, controlOne._y, anchorTwo._x, anchorTwo._y); updateAfterEvent();

}

This function refers to the control point and anchor point.

3.You’ll create the control and anchor point values based on the position of movie clips. Each movie clip contains a square, so add a simple createSquare() function using the lineTo method in succession. Just type the following below the code you entered in step 2:

function createSquare(handle, side, offset) { if (offset == undefines) {

offset = 0;

}

with (handle) { moveTo(offset, offset); lineTo(offset, side); lineTo(side, side); lineTo(side, offset); lineTo(offset, offset); endFill();

}

}

4.You want to be able to drag the anchor points and control points so that you can easily see what the control points do for you. The following code is a convenient method for adding draggability to any movie clip. Type the following function below the code you added in step 3:

function setDraggable(handle) { handle.onPress = function() {

clearInterval(_global.refreshScreen);

_global.refreshScreen = setInterval(this._parent, “connect”, 10); this.startDrag(false);

327