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

Beginning ActionScript 2.0 2006

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

Chapter 14

3.Navigate to an image on your drive and select the image you would like to use.

4.After the image is on the stage, select the instance so that it is focused.

5.Select Modify Convert to Symbol.

6.Select Movieclip as the symbol type and give your instance a logical name for the library, such as sampleImage.

7.With the movie clip selected, change its name in the properties panel to clip1. Use this name to reference your image in the ActionScript.

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

import flash.filters.*;

function addDropShadow(handle, controlX, controlY, quality) { var dropShadow:DropShadowFilter = new DropShadowFilter(); dropShadow.blurX = controlX;

dropShadow.blurY = controlY; dropShadow.quality = quality;

var cacheFilters:Array = handle.filters; cacheFilters.push(dropShadow); handle.filters = cacheFilters;

}

clip1.onPress = function() {

var greyScaleKernal:Array = [.25, .25, .25, 0, 0];

greyScaleKernal = greyScaleKernal.concat([.25, .25, .25, 0, 0]); greyScaleKernal = greyScaleKernal.concat([.25, .25, .25, 0, 0]); greyScaleKernal = greyScaleKernal.concat([0, 0, 0, 1, 0]);

var sepiaKernal:Array = [1.25, .25, .25, .25, 0]; sepiaKernal = sepiaKernal.concat([0, 1, 0, 0, 0]); sepiaKernal = sepiaKernal.concat([0, 0, 1, 0, 0]); sepiaKernal = sepiaKernal.concat([0, 0, 0, 1, 0]);

var greyScaler:ColorMatrixFilter = new ColorMatrixFilter(greyScaleKernal); var sepiaToner:ColorMatrixFilter = new ColorMatrixFilter(sepiaKernal); this.filters = [greyScaler, sepiaToner];

_root.addDropShadow(this, 8, 8, 8);

};

9.Test your SWF by selecting Control Test Movie. Click the clip1 movie clip. Your image will become sepia toned.

How It Works

The bit of code to focus on here is the addDropShadow function. This function adds a very simple drop shadow to any movie clip. The function itself can be expanded to control more properties of the drop shadow, but keep it minimal so you can focus on the code problem at hand.

In this example the image’s color was changed in the onPress event. You could have set up the drop shadow filter within this event. However, in an imaginary setting, say there are more clips with color modifications that will be different, but all clips will have a drop shadow you would want to externalize and reuse a code block to keep your file efficient.

348

Applying Filter Effects

One specific problem with applying a filter using a function is that the object might have filters already applied to it. In most cases it is desirable to retain these filters when the new filter is added. You cannot modify the handle.filters array directly as an array. You must create a temporary object to make the modification.

The code that specifically handles this filter retention is as follows:

var cacheFilters:Array = handle.filters; cacheFilters.push(dropShadow); handle.filters = cacheFilters;

Here you can see that the existing filters are cached into a temporary array object called cachedFilters. The temporary array object allows you to take a snapshot of the filter property as well as add to the filter array.

Using a simple array push method, the drop shadow filter is added to the existing filters. Finally, the filters property of the handle clip is reassigned. Thus, the filters are reapplied to the movie clip.

Trying It Out Give a Bitmap Image a Pinhole Camera Look

1.Open a new Flash document, name it pinHoleCamera.fla, and save it in your work folder.

2.Select File Import Import to Stage.

3.Navigate to an image on your drive and select the image you would like to use.

4.After the image is on the stage, select the instance so that it is focused.

5.Select Modify Convert to Symbol.

6.Select Movieclip as the symbol type and give your instance a logical name for the library, such as sampleImage.

7.With the movie clip selected, change its name in the properties panel to clip1. Use this name to reference your image in the ActionScript.

8.Click the first frame in the timeline, open the Actions panel, and type the following ActionScript:

import flash.filters.ColorMatrixFilter; import flash.filters.GlowFilter; import flash.filters.BlurFilter; import flash.display.BitmapData; import flash.geom.Matrix;

import flash.geom.Rectangle; import flash.geom.Point;

9.In the preceding step you added the import statements so you can begin to work with some filters and shape objects. Now add two color matrix filters by entering the following code below the code you added in step 8:

var bitmapWidth = this.clip1._width; var bitmapHeight = this.clip1._height;

var myMatrix:Array = [.25, .25, .25, 0, 0];

349

Chapter 14

myMatrix = myMatrix.concat([.25, .25, .25, 0, 0]); myMatrix = myMatrix.concat([.25, .25, .25, 0, 0]); myMatrix = myMatrix.concat([0, 0, 0, 1, 0]);

var myTint:Array = [1.25, .25, 0, 0, 0]; myTint = myTint.concat([.25, 1, 0, 0, 0]); myTint = myTint.concat([0, 0, 1, 0, 0]); myTint = myTint.concat([0, 0, 0, 1, 0]);

var myFilter:ColorMatrixFilter = new ColorMatrixFilter(myMatrix); var myTintFilter:ColorMatrixFilter = new ColorMatrixFilter(myTint);

10.Step 9 changed the color to black and white and then sepia. Now give the bitmap an inner glow. Specify a dark color to give the effect an almost inner shadow look. Add the following code below the code you added in step 9:

var pinhole:GlowFilter = new GlowFilter(); pinhole.alpha = .4;

pinhole.blurX = 40; pinhole.blurY = 40;

pinhole.color = 0x000000; pinhole.inner = true; pinhole.quality = 9; pinhole.strength = 3;

11.In step 10 you created an inner glow. Apply the filters you created in steps 8–10 by adding following code below the code you added in step 10:

clip1.filters = [myFilter, myTintFilter, pinhole];

12.Test your SWF. Select Control Test Movie. You will see that you’ve applied the three filters to give your bitmap a sepia look. This is very similar to the sepia exercise outlined earlier in the chapter. In this example an inner glow is added. Now you can begin to add some more interesting effects. Close your SWF and return to the ActionScript in frame 1.

13.Add the following code below the code you added in step 10:

var copy:BitmapData = new BitmapData(bitmapWidth, bitmapHeight); _root.createEmptyMovieClip(“blurCopy”, 2); blurCopy.attachBitmap(copy, 1);

copy.draw(clip1); blurCopy._x = this.clip1._x; blurCopy._y = this.clip1._y;

14.The code in step 13 added a copy of clip1 as a bitmap that you’ll be able to blur without affecting the original clip1 movie clip. This copy will be masked to reveal parts of the original image. You need to create a mask with a radial gradient fill. You can do this with the beginGradientFill drawing API method. Add the following code below the code you added in step 13:

var myMatrix:Matrix = new Matrix();

myMatrix.createGradientBox(bitmapWidth, bitmapHeight, 0, 0, 0, “pad”, “RGB”); _root.createEmptyMovieClip(“alphaGradientMask”, 3); alphaGradientMask.beginGradientFill(“radial”, [0x000000, 0x000000], [0, 100], [50,

0xFF], myMatrix); alphaGradientMask.lineTo(0, bitmapHeight);

alphaGradientMask.lineTo(bitmapWidth, bitmapHeight); alphaGradientMask.lineTo(bitmapWidth, 0);

350

Applying Filter Effects

alphaGradientMask.lineTo(0, 0); alphaGradientMask.endFill();

alphaGradientMask._x = this.clip1._x; alphaGradientMask._y = this.clip1._y;

15.Before applying the mask, you want to blur the copy image. To do this, create a simple blur filter and apply it to the blurCopy movie clip. Add the following code below the code you added in step 14:

var blur:BlurFilter = new BlurFilter(); blur.blurX = 5;

blur.blurY = 5; blur.quality = 4; blurCopy.filters = [blur];

16.Stop and test the movie. Select Control Test Movie. You will see that the clip is now severely blurred. However, the blur is applied to the blurCopy clip only. You can now add a mask filter to show only a little bit of the blurCopy movie clip. Close the SWF and return to the frame 1 ActionScript.

17.Add the following code below the code you added in step 15:

blurCopy.cacheAsBitmap = true; alphaGradientMask.cacheAsBitmap = true; blurCopy.setMask(alphaGradientMask);

18.Test the movie. Select Control Test Movie. You will now see that the blurCopy movie clip is selectively transparent, becoming more opaque toward the edges and clearer toward the center. This should give a somewhat interesting esthetic, which could be considered a single filter approximating a pinhole camera effect.

How It Works

This was a complex example of a movie clip manipulation, which covered many aspects of this entire chapter. It covered the use of the drawing API, including an example matrix gradient, masking, filters, and color matrices.

By using the draw method of the Bitmap object, you were able to effectively duplicate the pixels of the original movie clip. It is important to remember that this is not the same as DuplicateMovieClip; Draw simply copies the bitmap pixels present in the clip at the time the draw method is called. When and if changes occur in clip1, and you want the effect to keep up with the clip1 animation changes, you will need to call the draw method each time the clip changes.

Also important in this example was the setMask method. Although this is a typical setMask method call, there is a distinct difference that affected it, which wasn’t possible in an earlier version of Flash. Flash 8 allows for 32-bit masking. That means a movie clip can be masked using a gradient fill with an alpha gradient in it. The pixels in the clip being masked will inherit the alpha values present in the mask. To do this, you must cache the movie clip as a bitmap. This was done in step 17 and is a simple property declaration.

Throughout this chapter you’ve seen the Bitmap object mentioned, and its attributes and abilities were taken for granted. Next you learn about the Bitmap object in a bit more detail and how you can apply filters directly to a nested bitmap without affecting an entire movie clip.

351

Chapter 14

Applying Blending Modes

BlendMode is a property of the movieClip object. The property expects a string parameter. Each possible string is listed in this section with an explanation of each. You declare a blendMode as a property. Calling BlendMode twice results in only the second being used. An object can have only one blend mode. However, by duplicating the pixels into a Bitmap object, you can combine several overlays to create a multi-blendMode effect.

Following are descriptions of the BlendMode values. Each is listed with its literal string value as the title. For example, to set the BlendMode to normal, call

myClip.BlendMode = “normal”;

“normal” — Commonly used to return the blendMode to the default state. It specifies that the pixels in the movie clip override any pixels below it without modification. Alpha values are preserved, and transparent areas allow underlying pixels to show through.

“layer” — Used by the other filters. It provides a buffer copy of the bitmap data of the movie clip to perform operations when multiple child clips are nested in the clip being blended. Some filter settings require this property to be explicitly set.

“multiply” — Tends to darken an image by multiplying the underlying pixel by the blend pixel and dividing by 255 to avoid burn. It is handy when the overlay is meant to appear to leave a shadow on the underlying pixels.

“screen” — Similar to “multiply”, but uses the complementary colors of the pixels being examined, producing a lighter effect.

“lighten” — Compares the pixel values beneath the image and the pixel in the image. The darker of the two values is ignored, and only the lighter pixel is retained. This has an overall lightening effect.

“darken” — Compares the pixel values beneath the image and the pixel in the image. The darker of the two values is retained, and only the lighter pixel is ignored. This has an overall darkening effect.

“add” — Adds the value of two superimposed pixels. It has a maximum value of 0xFF and is useful for creating burn-in and burn-out cross-fade effects.

“subtract” — Subtracts the original pixel value from the underlying pixel value, leaving a result with a floor of 0, or black. The value is absolute and does not consider whether the original value is greater than the subtracting pixel. It’s helpful in eliminating images via a smooth fade to black.

“difference” — Similar to “subtract”, but subtracts the larger value from the smaller value to produce the result (not an absolute value).

“invert” — Rejects the original image entirely, and the underlying pixel values are inverted completely.

“overlay” — Preserves the contrast value of the original image while the hue of the background pixel is used.

“hardlight” — Tends to turn up the contrast of the original image. Dark colors are multiplied while light colors are screened, generally preserving saturation while increasing contrast.

352

Applying Filter Effects

“alpha” — Causes the background pixel to adopt the alpha value of the original pixel. This filter works only when at least two movie clips reside within a parent movie clip to which the “layer” blendMode is applied.

“erase” — The inverse of the “alpha” blendMode. This filter works only when at least two movie clips reside within a parent movie clip to which the “layer” blendMode is applied.

Summar y

In this chapter you explored the many ways in which you can modify a movieClip and Bitmap object using basic available method sets and known formulas for manipulating images.

The ConvolutionMatrix proved particularly powerful.

Many of the methods and objects in this chapter contain the ability to be manipulated directly on a more advanced level. If a particular object suits your idea, or intent, look into the object further to see how you might customize or create a class to control it.

All of the filters, blend modes, and methods can be automated and reused efficiently in class objects. Seek out existing libraries and formulas to help automate the many tasks of these filters. The methods in this chapter can perform alone and in combination with one another. The pinhole camera effect provided a Try It Out, which showed how using many of these objects and methods together in a specific order can produce a result that is expected more from expensive image editing programs, not from a real-time animation rendering function set. Have fun with these methods. Don’t get bogged down with the mathematics involved and try out as many things as you can think of!

Exercises

1.Using PNG image files, use loadBitmap on a Bitmap object and attachBitmap in a movie clip to create a simple button.

2.Using the BlurFilter object, create a simple navigation menu that unblurs a button when the button is moused over.

3.Using a displacementMap, sphereize an image using the beginGradientFill method.

4.Using the getPixel method within a for loop, try to find the existence of a particular color in a bitmap by checking each pixel. Place a movie clip at the x and y position of the result.

353

15

Working Directly with Bitmap Data

A bitmap image is a graphic that is created using a grid. The grid is a set of pixels, each with a defined color. When you zoom in on a bitmap image, the grid is obvious. Zooming in on a bitmap causes the pixilated look you’ve probably seen on resized or low-resolution images. Bitmap images are different from vector images in this way. A vector image is defined by points. As a vector image is scaled, the points remain in the same relative position. Lines and fills are drawn between these points as the vector is scaled. Because the lines and fills are redrawn, no pixilation occurs. When vector images are converted to bitmaps based on their current scale within a specified pixel area, they are referred to as rasterized graphics.

Before Flash 8, Flash could not directly manipulate bitmap graphics at the pixel level. Flash has always been able to display bitmap images and modify them as a movieClip object, but ActionScript was never able to fetch the pixel information and work with the pixels directly.

Flash 8 represents a massive maturation of the Flash player capability. Flash can declare anything a Bitmap object. That is, even a vector image can be rasterized in a split millisecond to perform perpixel operation changes at runtime. You can even convert a movie clip to a bitmap so quickly that you can rasterize vector animations, videos, webcam feeds, and more. You also can work with their pixels and apply filters to them as they play, giving you unparalleled freedom in terms of design and implementation.

After you convert a movie clip to a bitmap, you can apply a multitude of effects. In fact, all of the filters described earlier in this book that were applied to movie clips used the Bitmap object to perform the effects. The filters were able to modify the image as a bitmap as needed. Sometimes you can be working with bitmaps in Flash 8 and not even realize it.

The main ingredient when working with bitmap data is the Bitmap object, which is accessed via the display class package. Simply converting a movie clip to a bitmap can improve the frame rate performance of some animation conditions. However, the Bitmap object has a lot more to offer. Robust method and property sets enable you to work with bitmaps directly as well as augment filters, movie clip drawing methods, animations, and more.

Chapter 15

The Bitmap Object’s Methods

Not every method is used in this chapter’s Try It Out sections. However, most are straightforward and do what they advertise. Taking advantage of combinations of the Bitmap object’s method set is likely worth a whole new book. Here the Bitmap object’s methods are introduced so you can get comfortable working with them. Explore and try the different methods available.

applyFilter()

The applyFiler() method applies a filter to the Bitmap object. The method returns a number: 0, indicating a failure, or 1, indicating that the filter was successfully applied.

The parameters of applyFilter are sourceBitmap:BitmapData; sourceRect:Rectangle; destPoint:Point; and filter:BitmapFilter. Here are descriptions of them:

sourceBitmap — Specifies the bitmap to draw within the Bitmap object. You can specify a different Bitmap object to replace the current bitmap data (if there is any), or you can refer to the bitmap itself.

sourceRect — A rectangle object. You define a rectangle as a flash.geom.rectangle object. The source bitmap carries a rectangle property if you do not need to modify the existing rectangle. You can refer to this property as sourceBitmap.rectangle. Providing a new rectangle defines a subsection of the source image.

destPoint — A flash.geom.point object that specifies the x and y coordinate within the original bitmap where you’d like to begin drawing the filter with the sourceBitmap.

filter — Specifies the filter to use. Filters are discussed in Chapter 14.

clone()

The clone() method is used to duplicate the bitmap. This is often handy for applying multiple filters on layers where you would like to preserve aspects of some filters beneath overlays of new filters such as noise, blur, and more. The method returns a bitmapData object. To display the cloned bitmap you need to use the attachBitmap method; otherwise you can work with the bitmap until it’s required to be displayed.

colorTransform()

colorTransform() applies a flash.geom.colorTransform object to a bitmap. This method differs from the colorMatrixFilter filter. The colorTransform object uses an array of values to multiply each existing channel, as well as an offset for each channel. This gives you plenty of color control, but not as much control as the colorMatrixFilter.

The parameters of colorTransform are rectangle:Rectangle and colorTransform:ColorTransform:

rectangle — The rectangle object describes the section of the source bitmap to apply the color transform.

colorTransform — A colorTransform object defined by the flash.geom.colorTransform object.

356

Working Directly with Bitmap Data

copyChannel()

The copyChannel() method transfers the color channel information from one bitmap to another. Only one channel can be transferred at a time.

The parameters of copyChannel are sourceBitmap:BitmapData; sourceRect:Rectangle; destPoint:Point; sourceChannel:Number; and destChannel:Number:

sourceBitmap — Specifies the bitmap from which to obtain a color channel.

sourceRect — A flash.geom.rectangle object specifying the section of the bitmap from which to obtain channel data.

destPoint — A flash.geom.point object specifying where, in the destination image, to start applying the color channel.

sourceChannel — A Number specifying which channel to copy. The possible values are 1 (red), 2 (green), 4 (blue), and 8 (alpha).

destChannel — A Number specifying which channel to replace. The possible values are 1 (red), 2 (green), 4 (blue), and 8 (alpha).

copyPixels()

copyPixels() is similar to the draw() method except that it enables you to obtain just a portion of the original bitmap. The sourceBitmap parameter must be a bitmap; you cannot refer to a movie clip. To use a movie clip with copyPixels, see the draw() method.

The parameters of copyPixels are sourceBitmap:BitmapData; sourceRect:Rectangle; destPoint:Point; alphaBitmap:BitmapData; alphaPoint:Point; and mergeAlpha:Boolean:

sourceBitmap — Specifies the bitmap from which to obtain pixels.

sourceRect — A flash.geom.rectangle object specifying the section of the bitmap from which to obtain pixels.

destPoint — A flash.geom.point object specifying where, in the destination image, to start applying the new pixels.

alphaBitmap — A secondary bitmap used for its alpha channel only. If this property is defined, the pixels are mixed with the alpha channel present in this bitmap.

alphaPoint — A flash.geom.point object representing the upper-left index within the alphaBitmap from which to begin obtaining alpha channel data.

mergeAlpha — A Boolean that determines whether the pixels in the sourceBitmap image should retain their alpha values when the pixels are transferred to the Bitmap object.

dispose()

The dispose() method has no parameters. When it is called, all attributes, properties, and data are removed from the Bitmap object. The Bitmap object remains accessible, however, its properties will return nothing. You can begin to create new bitmap data using the Bitmap object.

357