Posts filed under ‘ActionScript’

Flash CS4 Tutorial – Copy Motion – Animation

Flash CS4 Tutorial – Copy Motion

Learn how to use Flash CS4 and ActionScript to create complex animations.

From Flash CS3 onwards Adobe introduced a new feature that enables users to copy timeline animation and paste it straight into the actions panel. This allows developers to cut corners when creating complex animations that aren’t so easy to create with just pure Actionscript. The pasted animation has several arrays and variables, take a look at Example 1.1 for an example. The example motions an object from the left of the stage to the right, nothing fancy just a simple animation. At first glance you’ll notice some familiar Actionscript properties such as scaleX and scaleY, these properties are what essentially make up the animation. In this article we’ll be at this technique in greater detail by adding making the code reusable by adding it to other stage objects and building a reusable class.

The files used in this Flash tutorial can be downloaded here

Example 1.1

  import fl.motion.MotionBase;

  import flash.filters.*;

  import flash.geom.Point;

  var __motion_ps:MotionBase;

  if(__motion_ps == null) {

  import fl.motion.Motion;

  __motion_ps = new Motion();

  __motion_ps.duration = 39; 

__motion_ps.addPropertyArray("x", [0,5.78946,11.5789,17.3684,
23.1579,28.9473,
34.7368,40.5263,46.3158,52.1052,57.8947,63.6842,
69.4736,75.2631,81.0526,86.8421,92.6315,98.421,
104.21,110,115.789,121.579,127.368,133.158,
138.947,144.737,150.526,156.316,162.105,167.895,
173.684,179.474,185.263,191.053,196.842,
202.632,208.421,214.211,220]);

 __motion_ps.addPropertyArray("y", [0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]);

  __motion_ps.addPropertyArray("scaleX", [1.000000]);

  __motion_ps.addPropertyArray("scaleY", [1.000000]);

  __motion_ps.addPropertyArray("skewX", [0]);

  __motion_ps.addPropertyArray("skewY", [0]);

  __motion_ps.addPropertyArray("rotationConcat", [0]);

  __motion_ps.addPropertyArray("blendMode", ["normal"]);
var __animFactory_ps:AnimatorFactory = new AnimatorFactory(__motion_ps);

__animFactory_ps.transformationPoint = new Point(0.500000, 0.500000);

// __animFactory_ps.addTarget(<instance name goes here>, 0);


  }

In this first part of this tutorial we’ll use the Copy Motion as Actionscript 3.0 technique to make an advertisement banner that’ll have 3 spinning adobe logos. In the download file the stage is already set up with some text and a single spinning Flash logo created on the timeline. The timeline consists of 6 layers that include actions, text, fl, ps and dw. The layer that’s important to us is the fl layer; this layer contains the Motion Tween that we’ll copy and paste into the actions panel, using the Copy Motion as Actionscript 3.0 feature.

Step 1 – Copy The Animation

The first step is to copy the animation itself, so with the very last Keyframe of the fl layer selected we drag and hold the mouse button back to the first Keyframe, highlighting every frame of the animation layer. So it looks like this;

With the frames highlighted we right click and select Copy Motion as Actionscript 3.

Step 2 – Adding The Code To Another MovieClip

Our first objective after copying the timeline animation is to paste the animation into the actions panel, we’ll then be able to add the animation to another MovieClip by making a few changes. To add this too another object in Flash CS4 is simple, near the bottom of the packaged animation you’ll find a line that’s been commentated shown in Example 2.3

Example 2.3

//__animFactory_fl.addTarget(<instance name goes here>, 0);

All that is required is to uncomment the line by deleting the 2 forward slashes then, add the instance name of the object we want to animate, and then enter the amount of times we want the animation to fire. In this case we’re animation the DW MovieClip on the stage and telling the animation to fire once.

Example 2.4


__animFactory_fl.addTarget(dw, 1);

To add the animation to more than one stage object just copy and paste the same line but add a different instance name. For example;


__animFactory_fl.addTarget(dw, 1);

  __animFactory_fl.addTarget(ps, 1);

This would animate the Dreamweaver and Photoshop logos.

Build a Custom Class

Now this animation may not be worth building into a custom class as it only fades and spins an object, but the techniques used to create the class will come in handy. We’ll start by creating a new actionscript file, saving it and calling it Spinner. Inside actionscript file we’ll create the bare bones of a class file.

Package{

Public class Spinner extends MovieClip{

public function spin():void

  {

}

  }

  }

Step 2 – Pasting the Animation Code

We need to copy the animation again using the Copy as Actionscript 3.0 feature so we can paste it inside the Actionscript file. The copied animation should still be on the clipboard but we’ll repeat this anyway. Switching back to the Spinner actionscript file we paste the code below the class code, keeping it out of the way for the time being.

Step 3 –Importing Classes

We need to import the relevant classes or otherwise the animation won’t work. We already have the appropriate classes imported inside the pasted timeline animation; it’s just a matter of having them in correct part of the code. To do this we simply scroll down and copy all the classes from inside the copied timeline animation and paste them inside our package.

Package{

import fl.motion.AnimatorFactory;

  import fl.motion.MotionBase;

  import flash.filters.*;

  import flash.geom.Point;

Public class Spinner extends MovieClip{

 

public function spin():void

  {

}

  }

  }

Step 4 – Declaring the AnimatorFactory

In this next step we’ll declare the AnimatorFactory inside our class, looking at the pasted timeline animation we have an AnimatorFactory object declared inside the function. This is fine but we want to make sure we’re declaring it as an element of the class and not just the function.

Package{

import fl.motion.AnimatorFactory;

  import fl.motion.MotionBase;

  import flash.filters.*;

  import flash.geom.Point;

Public class Spinner extends MovieClip{

var __animFactory_fl:AnimatorFactory;

public function spin():void

  {

}

  }

  }

 

Step 5 – Adding the Animation 

Inside the our spin() function we paste the remaining animation code.

Package{

import fl.motion.AnimatorFactory;

  import fl.motion.MotionBase;

  import flash.filters.*;

  import flash.geom.Point;

Public class Spinner extends MovieClip{

var __animFactory_fl:AnimatorFactory;

public function spin():void

  {

  var __motion_fl:MotionBase;

  if(__motion_fl == null) {

  import fl.motion.Motion;

  __motion_fl = new Motion();

  __motion_fl.duration = 39;

 __motion_fl.addPropertyArray("x", [0]);

  __motion_fl.addPropertyArray("y", [0]);

  __motion_fl.addPropertyArray("scaleX", [1.000000]);

  __motion_fl.addPropertyArray("scaleY", [1.000000]);

  __motion_fl.addPropertyArray("skewX", [0]);

  __motion_fl.addPropertyArray("skewY", [0]);

  __motion_fl.addPropertyArray("rotationConcat", [0,-66.3156,-132.631,
-198.947,-265.263,-331.579,-397.894,
-464.21,-530.526,-596.842,-663.158,
-729.473,-795.789,-862.105,-928.421,
-994.736,-1061.05,-1127.37,-1193.68,
-1260,-1326.32,-1392.63,-1458.95,
-1525.26,-1591.58,-1657.89,-1724.21,
-1790.53,-1856.84,-1923.16,-1989.47,
-2055.79,-2122.1,-2188.42,-2254.74,
-2321.05,-2387.37,-2453.68,-2520]);

  __motion_fl.addPropertyArray("blendMode", ["normal"]);

  __motion_fl.addPropertyArray("alphaMultiplier", [0.000000,0.026316,
0.052632,0.078947,0.105263,0.131579,0.157895,0.184210,0.210526,
0.236842,0.263158,0.289474,0.315789,0.342105,0.368421,0.394737,
0.421052,0.447368,0.473684,0.500000,0.526316,0.552631,0.578947,
0.605263,0.631579,0.657895,0.684210,0.710526,0.736842,0.763158,
0.789474,0.815789,0.842105,0.868421,0.894737,0.921053,
0.947368,0.973684,1.000000]);

 var __animFactory_fl:AnimatorFactory = new AnimatorFactory(__motion_fl);

  __animFactory_fl.transformationPoint = new Point(0.500000, 0.500000);

 //__animFactory_fl.addTarget(<instance name goes here>, 0);

  }

}

}

Step 6 – Adding this Keyword

At the bottom of the code inside our constructor function we have one final piece of code to alter. Just like earlier we uncomment the addTarget line (example 6.1) but this time instead of adding an instance name we use the “this” keyword. The “this” keyword references the object that contains the script. So basically it will animate any object that we connect to this actionscript file.

Example 6.1


//__animFactory_fl.addTarget(<instance name goes here>, 0);

Example 6.2


__animFactory_fl.addTarget(this,1);

Now Lets See The Classes In Action

Now we have our new class lets see it in action. In a new Flash file we have a square drawn out onto the stage that has been converted to a MovieClip, and then has been exported to our Spinner Actionscript class (shown in example 7.1).

Example 7.1

Inside the actions panel of the new Flash file we add the following code. This code creates an instance of our spinner class, adds it to the stage using the addChild() method and finally calls the spin() function.

var test:Spinner = new Spinner();

  addChild(test);

  test.spin();

January 30, 2009 at 12:31 am Leave a comment

Beginners Flash Tutorial – Filters in AS3

For users who prefer to learn Flash visually we have a range of Adobe Flash CS3 video tutorials, this method of training greatly enhances learning and allows beginners to master even the most complex aspects of Adobe Flash with ease.
View the Beginners Flash CS3 Training Video

.

Beginners Flash Tutorial – Filters in AS3

Filters in Actionscript 3.0
In this beginners Flash tutorial we’ll create some filters using Actionscript 3.0. The power of Actionscript 3 allows us to create powerful filter effects and add them to any object. If you’re familiar with blend modes in graphic applications such as Photoshop you’ll recognise some of the blend modes that we’ll be looking at, if your not we’ll go through and explain exactly what each type of effect does. We’ll look at four common filters the drop shadow filter, the bevel filter, the blur filter and the glow filter. We’ll add each of these filters to four separate rectangles and go through their different properties. By the end of this Flash tutorial you will have a fundamental understanding of how to write ActionScript code to create and apply filters to dynamically created graphics and objects.

First we’ll briefly go through creating a basic rectangle for our filter effects;

We create a new Sprite object called filterEffect, this Sprite object will hold all our graphic information. A Sprite is just a movie-clip without a timeline; think of it as a container.

var filterEffect:Sprite = new Sprite();

Using the lineStyle() method we declare the outline properties of the rectangle. This method has 3 parameters available to it, thickness of the line measured in pixels, colour of the line measured in hexadecimal format and finally alpha scale that’s measured in percent (1 = 100%, .25 = 25%). In our code below we have a 2px black line with a 100% alpha property. We assign this method to graphics property of the Sprite object and assign the graphics property to our filterEffect Sprite object.

filterEffect.graphics.lineStyle(2,0x000000,1);

We use the beginFill() method to choose the colour of the rectangle. The beginFill() method has 2 parameters colour and alpha scale, for our code we’ve used a shade of red and set the alpha scale to 90%.

filterEffect.graphics.lineStyle(2,0x000000,1);

Now that we have the colour and outline properties it’s time to draw out the rectangle. Drawing the rectangle itself is pretty straight forward, using the drawRect() method we set the properties we require for the rectangle. The drawRect() method requires 4 parameters, X and Y values, and width and height. The X and Y values indicate the position of where you want to draw out the rectangle, and the width and height determine the size of the rectangle. In our code we’ve positioned the rectangle to a position of 50px by 50px and set the size to 100px by 100px.

filterEffect.graphics.drawRect(50,50,100,100);

Using the X and Y properties we set the position of the Sprite object on the stage to 50px respectively.

filterEffect.x = 50;
filterEffect.y = 50;

Bevel Filter Effect
The first filter we’ll look at is the bevel filter, using the bevel filter gives objects a three dimensional effect. The bevel class allows us to customize the bevel by changing angle, blur and placement properties of the bevel. Below we’ll create a bevel filter and add it to the rectangle we have just created.

First thing we need to do is create a new bevel filter object. We’ll name this bevel object “bevel”. We can manipulate the bevel by adding some parameters; there are a number of different parameters available to us shown below. We’ll be focusing on distance and angle, the distance measures how far or much the bevel gives off a 3d effect and the angle measures the angle of the actually bevel itself. For our code below we’ve given the bevel a distance of 4.0 and a 45-degree angle.

Parameters Available

(distance:Number = 4.0, angle:Number = 45, highlightColor:uint = 0xFFFFFF, highlightAlpha:Number = 1.0, shadowColor:uint = 0×000000, shadowAlpha:Number = 1.0, blurX:Number = 4.0, blurry:Number = 4.0, strength:Number = 1, quality:int = 1, type:String = “inner”, knockout:Boolean = false)

var bevel:BevelFilter = new BevelFilter();
  bevel.distance = 4.0;
  bevel.angle = 45;

We want to make sure that our Sprite object is using the Sprite object is using the correct filters, that means adding the “bevel” filter we’ve just created.

filterEffect.filters = [bevel];

All there’s left to do is add everything to the display list so it’s visible when the file is previewed. Using the addChild() method we add our filterEffect Sprite object to the stage.

addChild(filterEffect);

Bevel Filter Code in Full

var filterEffect:Sprite = new Sprite();
var bevel:BevelFilter = new BevelFilter();
bevel.distance = 4.0;
bevel.angle = 45;
filterEffect.filters = [bevel];
filterEffect.graphics.lineStyle(2,0x000000,1);
filterEffect.graphics.beginFill(0x3174d0,.9);
filterEffect.graphics.drawRect(50,50,100,100);
filterEffect.x = 50;
filterEffect.y = 50;
addChild(filterEffect);

Drop Shadow Filter
We’ve already covered most the code above means, so for the next few examples we’ll just be looking at the code that we haven’t already looked at. In this example we’ll be creating another common filter effect, the drop shadow filter. In the example below we’ll create a new drop shadow object and alter some of its properties to get the effect we want.

Parameters Available

(distance:Number = 4.0, angle:Number = 45, highlightColor:Uint = 0xFFFFFF, highlightAlpha:Number = 1.0, shadowColor:Uint = 0×000000, shadowAlpha:Number = 1.0, blurX:Number = 4.0, blurry:Number = 4.0, strength:Number = 1, quality:int = 1, type:String = “inner”, knockout:boolean = false)

Just like in the previous example we create a new filter effect called dropShadow, in this case it’s a DropShadowFilter. We then add that filter effect to our Sprite object.

var dropShadow:DropShadowFilter = new DropShadowFilter();

dsEffect.filters = [dropShadow];

We’ll give our dropShadow some properties to alter the drop shadow effect. The first property we’ll give it is distance; the distance property alters the offset distance for the shadow, in pixels. The default value is 4. In our code we’ve given it a value of 50px.

dropShadow.distance = 50;

At the moment the drop shadow doesn’t look that realistic so we’ll add some blur to it using the blurX and blurY properties. The blurX and blurX properties dictate the amount of horizontal and vertical blur that’s added, valid values are 0 to 255.0 and the default value is 4.0. In our code below we’ve given the horizontal and vertical blur a value of 10.

dropShadow.blurY = 10;
dropShadow.blurX = 10;

Using the alpha property we’ll change the alpha scale of the drop shadow filter to 60%.

dropShadow.alpha = .6;

Drop Shadow Filter Code in Full;

var dsEffect:Sprite = new Sprite();
var dropShadow:DropShadowFilter = new DropShadowFilter();
dsEffect.filters = [dropShadow];
dropShadow.distance = 50;
dropShadow.blurY = 10;
dropShadow.blurX = 10;
dropShadow.alpha = .6;
dsEffect.graphics.lineStyle(1,0x000000);
dsEffect.graphics.beginFill(0x3174d0,.9);
dsEffect.graphics.drawRect(50,50,100,100);
dsEffect.graphics.endFill();
dsEffect.x = 200;
dsEffect.y = 50;

addChild(dsEffect);

Glow Filter Effect
The GlowFilter class lets us apply a glow effect to objects. In our example we’ll use the color and alpha properties to get the effect we want.

Parameters Available

(color:uint = 0xFF0000, alpha:Number = 1.0, blurX:Number = 6.0, blurry:Number = 6.0, strength:Number = 2, quality:int = 1, inner:Boolean = false, knockout:Boolean = false)

Like with the previous examples we create a new filter object and add it to our Sprite. In our code we create a new GlowFilter object called glow

var glow:GlowFilter = new GlowFilter();

  gEffect.filters = [glow];

We’ll give our GlowFilter 3 properties color, alpha and inner. Lets take a look a closer look at these 3 properties.

The color property indicates the colour of the glow in hexadecimal format.

glow.color = 0xFFFFCC;

The alpha scale we’ve already discussed earlier, we’ve given it an alpha scale of 80%.

glow.alpha = .8;

The inner property specifies whether the object has a knockout effect, this property has 2 values, true or false. True makes the object’s fill transparent and reveals the background colour of the document and false would indicate no knockout effect. In our code we’ve given it a value of false.

glow.inner = false;

Glow Effect Filter Code in Full;

var gEffect:Sprite = new Sprite();
var glow:GlowFilter = new GlowFilter();
gEffect.filters = [glow];
glow.color = 0xFFFFCC;
glow.alpha = .8;
glow.inner = false;
gEffect.graphics.lineStyle(1,0x000000);
gEffect.graphics.beginFill(0x3174d0,.9);
gEffect.graphics.drawRect(50,50,100,100);
gEffect.graphics.endFill();
gEffect.x = 350;
gEffect.y = 50;
addChild(gEffect);

Blur Filter Effect
The blur effect allows us to add a simple blur to any object. This can be good for creating navigation hovers or used in cartoon animations for extra effect.

Parameters Available

(blurX:Number = 4.0, blurry:Number = 4.0, quality = 1)

Again we go through the same process of first creating a new BlurFilter object and assigning it to the Sprite object.

var blur:BlurFilter = new BlurFilter();
bEffect.filters = [blur];

We’ll use the blurX and blurY properties to change the horizontal and vertical blur of the object. Both properties accept value between 0 and 255, for our code below we’ve given both a value of 10.

blur.blurX = 10;
blur.blurY = 10;
Blur Filter Code in Fullvar bEffect:Sprite = new Sprite();
var blur:BlurFilter = new BlurFilter();
bEffect.filters = [blur];
blur.blurX = 10;
blur.blurY = 10;
bEffect.graphics.lineStyle(1,0x000000);
bEffect.graphics.beginFill(0x3174d0,.9);
bEffect.graphics.drawRect(50,50,100,100);
bEffect.x = 50;
bEffect.y = 200;
addChild(bEffect);
We hoped you enjoyed this ActionScript / Flash Tutorial.

December 11, 2008 at 2:42 pm Leave a comment

ActionScript 3 Tutorial – Using HTML and CSS

Beginners with Flash ActionScripting often don’t realize you can embed basic HTML and CSS into their code.

ActionScript Tutorial – HTML and CSS in AS 3

In this tutorial we’ll be looking at how incorporate HTML and CSS into your Actionscript. You’re probably wondering why you would want to do this and how it would be beneficial? Well, you may be working on a large Flash project that may require several different fonts. This can be pretty time consuming, as you’d have to create all the different text field and text format properties individually in Actionscript. Using HTML and CSS as a sort of text editor would reduces the amount of code you’d have to write. The Flash player has limited support for HTML and CSS tags (shown below) however it does cover the most common tags, certainly enough to use it as text editor. Below we’ll create 2 examples of an application, first we’ll create the Stylesheet within our Actionscript and secondly we’ll use an external CSS file and load it into our application.

Code Example Download ( includes working files and code examples )

HTML and CSS tags supported by the Flash player;

HTML Tags

<p> </p>
<b> </b>
<I></I>
<span></span>
<textFormat></textFormat>
<a></a>
<u></u>
<font></font>
<img></img>
<li></li>

CSS Tags

<font-family> <font-size> <font-style> <font-weight> <color> <text-align> <margin-left> <margin-right> <display>

Inside Actionscript

In this method we’ll be creating everything inside our actionscript, this means we’ll effectively have to create all the stylesheet properties using actionscript. We’ll do this by creating new objects that’ll act as our CSS selectors; we’ll then target these objects inside our text fields using HTML tags. As we are creating the Stylesheet inside Actionscript we need access to the StyleSheet class, so the first thing we’ll do is create a new StyleSheet object called cssStyle. This will give us access to all the properties, methods and events of the StyleSheet class.

var cssStyle:StyleSheet = new StyleSheet();

We’ll create a new object called body this will give us access to the Object class; the object class is at the root of the ActionScript class hierarchy. Think of the objects in the rest of the code as a HTML tags, for example we have body, header and manContent.

var body:Object = new Object();

We’ll set the font for this Object using the fontFamily property to Arial.

var body.fontFamily = “Arial”;

Next we’ll create the header for the application, headers have to stand out so we’ll make sure our properties reflect that. Again we start by creating a new Object but this time it’s called header.

var header:Object = new Object();

We want the header to stand out so we’ll change the font size using the fontSize property to 18px.

header.fontSize = 18;

Using the color property we’ll change the colour of the header text to red.

header.color = “#FF0000″;

To make it stand out that little bit more we’ll make the header bold by changing the fontWeight property to bold.

header.fontWeight = “bold”;

We’ll create another object called mainContent and set the fontSize property to 14 px.

var mainContent:Object = new Object(); mainContent.fontSize = 14;

Using the setStyle() method we add each style to the css instance of the stylesheet class.

cssStyle.setStyle(“.header”, header); cssStyle.setStyle(“.mainContent”, mainContent); cssStyle.setStyle(“body”, body);

We create a new TextField object called theText, this TextField object will give us access to all the properties, methods and events of the TextField class. We’ll use this TextField object to hold all our text.

var theText:TextField = new TextField();

Using the X and Y properties we position the TextField where we want on the stage.

theText.x = 425; theText.y = 100;

We set the width of the TextField to 300px using the width property.

theText.width = 350;

We need to set the multiline property to true to ensure that the text is set on multiple lines, if this was set to false all the text would remain on a single line.

theText.multiline = true;

We want to make sure the text inside the TextField always word wraps the text. To do this we set the wordWrap value to true.

theText.wordWrap = true;

We set the TextFieldAutoSize property to LEFT; this sets the text to left justified.

theText.autoSize = TextFieldAutoSize.LEFT;

We use the styleSheet property to set the cssStyle stylesheet to our TextField.

theText.styleSheet = cssStyle;

Think of these next lines as an HTML page, we have our body tag along with our header and mainContent classes.

theText.htmlText = “<body>”; theText.htmlText += “<span class=’header’>HTML and CSS in ActionScript 3.0</span><br><br>”; theText.htmlText += “<span class=’mainContent’>In this method we’ll be creating everything inside our actionscript, this means we’ll effectively have to create all the stylesheet properties using actionscript. We’ll do this by creating new objects that’ll act as our CSS selectors; we’ll then target these objects inside our text fields using HTML tags. As we are creating the Stylesheet inside Actionscript we need access to the StyleSheet class, so the first thing we’ll do is create a new StyleSheet object called cssStyle. This will give us access to all the properties, methods and events of the StyleSheet class.</span><br><br>”; theText.htmlText += “</body>”;

Finally we add our TextField to the display list by using the addChild() method.

addChild(theText);

External Method

In this method we’ll load an external CSS file into our Actionscript and use that to format the text in the application. This requires us to create a simple loader to load the CSS file into the application, let’s take a closer look at the code below.

First thing we’ll do is create a new String object called pageContent. Inside this String object we have the text that’ll be used in the application, you’ll notice inside the String there is some HTML tags. The HTML tags will be styled by our external Stylesheet.

var pageContent:String = “<H1>External Method</H1>\n\n<P> In this method we’ll load an external CSS file into our Actionscript and use that to format the text in the application. This requires us to create a simple loader to load the CSS file into the application, let’s take a closer look at the code below.</P>”;

Next we create a new Sprite object called textContainer, this Sprite object will hold all our content. A Sprite is just a movie-clip without a timeline.

var txtContainer:Sprite = new Sprite();

We position the Sprite object on the stage by changing the X and Y properties to 50 and 100px respectively.

 txtContainer.x = 50; txtContainer.y = 100;

Using the addChild() method we add the Sprite object to the stage, this will add it to the display list making it visible when we preview or publish the file.

addChild(txtContainer);

First we create a new TextField object called myText, this TextField object will give us access to all the properties, methods and events of the TextField class. Later we’ll add our String content to this TextField, for now we’ll just add some basic properties such as width, height and word wrap.

var myTxt:TextField = new TextField();

Using the width property we’ll change the width of the TextField to 300px.

myTxt.width = 300;

We want to make sure the text inside the TextField always word wraps the text. To do this we set the wordWrap value to true.

myTxt.wordWrap = true;

We set the TextFieldAutoSize property to LEFT; this sets the text to left justified.

myTxt.autoSize =TextFieldAutoSize.LEFT;

We want the TextField to be added to the Sprite container object, by assigning the addChild() method to the txtContainer adds the TextField to the Sprite object.

txtContainer.addChild(myTxt);

Since we’re using an external document we need to load that document into our Actionscript, we’ll do this by setting up a simple loader.

First we’ll create a new URLLoader object called cssLoader. This object will give us access to all the properties, methods and events of the URLLoader class.

We’ll use this to load the data. var cssLoader:URLLoader = new URLLoader();

Next we want to request the file to load, we do this by creating a new URLRequest object. Inside the brackets we point to the file that we want to load into our application, for our code we point to the CSS file.

var cssRequest:URLRequest = new URLRequest(“/loadercss.css”);

We’ll give our cssLoader an addEventListener() method to listen for a COMPLETE event. The COMPLETE event essentially listens for when the loader has finished loading, it’s basically listening for the css file to finish loading. We’ll call this addEventListener() cssLoaderComplete.

cssLoader.addEventListener(Event.COMPLETE, cssLoaderComplete);

Using the load method of the URLLoader class we load in the file from the URLRequest object. cssLoader.load(cssRequest);

Next we’ll set up a function for our cssLoaderComplete eventListener, this function will fire when the css file has finished loading. Inside the function we have a number of different things happening, first we create a new Stylesheet object called css this will give us access the stylesheet class. The parseCSS() method of the stylesheet class fills our stylesheet object with the CSS we have loaded into the application. We then set our myTxt TextField to use the CSS Stylesheet object and finally we add the text inside the pageContent String into our TextField.

function cssLoaderComplete(evt:Event):void { var css:StyleSheet = new StyleSheet(); css.parseCSS(URLLoader(evt.target).data); myTxt.styleSheet = css; myTxt.htmlText = pageContent; }

December 3, 2008 at 4:04 pm Leave a comment

Flash CS3 Tutorial – Gradient Fills in Actionscript 3

For users who prefer to learn Flash visually we have a range of Adobe Flash CS3 video tutorials, this method of training greatly enhances learning and allows beginners to master even the most complex aspects of Adobe Flash with ease.
View the Adobe Flash Video Tutorial – Training.

.

Gradient Fills in Actionscript 3

Creating Gradients using Flash is not hard, but how about using ActionScript to dynamically create a Gradient? Following on from our earlier Flash Tutorials : Creating Lines and Shapes with ActionScript this Beginners ActionScript tutorial shows you how.

In this tutorial we’ll go through at creating some gradient fills using Actionscript 3.0. We’ll take a look at radial and linear gradients; we’ll add angle and use different spread methods to manipulate the gradients effect. In the swf example below we have 6 different gradients each with different effects, from left to right we have a radial gradient, linear gradient, linear gradient with matrix angle, linear gradient with reflect spread method, linear gradient with repeat spread method and finally linear gradient with pad spread method. We’ll break each of these gradients down and go through and explain how they work.

Download a larger html version and the SWF / FLA files used in this tutorial

Radial Gradient

First we create a new Sprite object called gradients. This Sprite object will hold all the gradients information. A Sprite is just a Movie-Clip without a timeline.

var gradients:Sprite = new Sprite();

At the moment the Sprite object isn’t part of the display list. To add the Sprite object to the display list we use the addChild() method, adding an object to the display list essentially adds it to the stage making it visible when you preview or publish the file.

addChild(gradients);

Now we’re ready to start creating the gradient. We have to let Actionscript know what type of gradient we are creating; with the use of the GradientType class Actionscript gives us the choice of either a radial or linear gradient. In this case we’ll choose the RADIAL property, we store this data inside a String object called radType so we can use it later on in the code.

var radType:String = GradientType.RADIAL;

The main ingredients of a gradient are the colours themselves; we’ll choose 2 different colours that will act as the colours for the gradient. We’ll create an Array called radColours to hold the colour information. Using Arrays allow us to hold multiple data in a single variable, since we need to store 2 separate values this comes in handy. Actionscript reads colours in hexadecimal format, if you’re not sure about colours in hexadecimal format have a look at the colour picker in the Flash interface. In the code below we’ve chosen 0x3174d0 and 0x15396f giving us 2 different shades of blue.

var radColours:Array = [0x3174d0, 0x15396f];

We have the colours for the gradient but we can change the alpha scale of either of them. Again we’ll use an Array to hold this information, but this time we’ll call it radAlphas. Inside this Array we’ll change the alpha values of the colours, alpha scale in Actionscript is measured in percent (1 = 100%, .25 = 25%). The first value inside the Array will alter the first colour inside the radColours Array. In our code we’ve set both colours to 1 keeping them at 100%.

var radAlphas:Array = [1, 1];

Next we’ll look at the scale of each colour, for example we might want to show a lot of dark blue and just a little bit of the lighter blue blue. This method works in the same way as if we were to change the gradient scale in graphic applications such as Photoshop. Take a look at the image below, it shows the gradient properties box from Photoshop. The value 0 represents the left-hand position in the gradient box, and 255 indicates the right-hand position in the gradient box. In this current position both colours are distributed equally, but if we wanted to show more of the light blue we’d simply increase the left hand value, and to show more of the dark blue we’d decrease the right hand value. In our code we’ve kept it at 0 and 255 giving each colour an equal share.

var radRatios:Array = [0, 255];

Example of Photoshop Gradient Box;

To gain more control over gradients we can use the methods from the Matrix Class. It’ll enable us to change the height, width and rotation of the gradient. We’ll start by creating a new instance of the Matrix class giving us access to all the properties methods and events of that class.

var radMatrix:Matrix = new Matrix();

The method from the Matrix class we’ll use to manipulate the gradient is called createGradientBox(). This method has 5 parameters available to it, width, height, rotation, tx, and ty. For this gradient we’ll just use the width and height parameters, for our code we’ve set the width and height to 120px by 120px.

radMatrix.createGradientBox(120,120);

We’ll move the Sprite object by changing the x and y properties to 50px.

gradients.x = 50;
   gradients.y = 50;

We have a lot of variables with different data types but they don’t actually make up the gradient, to bring everything together we use a method called beginFillGradient(). Before we get into that method you’ll notice it’s assigned to a couple of elements, it’s attached to the graphics property and that in turn is attached to the gradients Sprite Object. We want all the data to be part of the Sprite object we created in the first line of code, to do this we first assign the method to “graphics” which will draw out the gradient and then finally that’s assigned to the gradients Sprite object. Looking at the beginFillGradient() method you’ll see it has a number of parameters available to it, but we’ve actually already done most of the work for it. When your typing out your parameters a little yellow help box pops up, this help box shows what values are required for the method. The first value required is gradient type, but we’ve already stored the gradient inside the String object so all we have to do is type “radGrad”. That will insert all the data from the String into our beginFillGradient() method. The same goes for the rest of the parameters; the next values required are the colours, we chose the colours earlier and stored them inside an Array, so we simply insert that Array into the method. We continue this process for the ratios, alphas and Matrix data.

//start code block
gradients.graphics.beginGradientFill(radType, radColours, radAlphas, radRatios,radMatrix)
//end code block

Using the drawRect() method we’ll create a rectangle for the gradient to reside in. The drawRect() method has 4 parameters available to it, x and y values, and width and height. For our code we’ll keep the x and y values at 0 because we’ll move the gradient by changing the x and y position of the gradients Sprite object, remember all the gradients information will be added to that Sprite object. We’ll make the rectangle the same height and width as the gradient box we created in the previous line, this now ensures that the radial gradient will sit in the centre of the rectangle.

gradients.graphics.drawRect(0, 0, 120, 120);

Linear Gradient
We’ll make a few changes to the linear gradient; the most notable and obvious is gradient type, which is obviously changed to LINEAR. We’ve also added a gradient angle to the createGradientBox() method by changing the rotation value to 45, changing the angle of the gradient.

var linGrad:String = GradientType.LINEAR;
   var linMatrix:Matrix = new Matrix();
   linMatrix.createGradientBox(120,120,45);
   var linColors:Array = [0xb61322, 0x580408];
   var linAlphas:Array = [1, 1];
   var linRatios:Array = [0, 255];
   var lin:Sprite = new Sprite();
   lin.graphics.beginGradientFill(linGrad, linColors, linAlphas, linRatios,linMatrix)
   lin.graphics.drawRect(0, 0, 120, 120);
   lin.x = 350;
   lin.y = 50;
   addChild(lin);

Adding Spread Methods
To add some spread methods we first let Actionscript know what type of spreadMethod we are using. This works in the same way as choosing the gradientType, we place the spreadMethod inside a string and then add it to the beginGradientFill method.

//Reflect Spread Method
var reflectGrad:String = GradientType.LINEAR;
   var reflectMatrix:Matrix = new Matrix();
   var spreadReflect:String = SpreadMethod.REFLECT;
   reflectMatrix.createGradientBox(20,20,0,0,0);
   var reflectColors:Array = [0xb61322, 0x580408];
   var reflectAlphas:Array = [1, 1];
   var reflectRatios:Array = [0, 255];
   var reflect:Sprite = new Sprite();
   reflect.graphics.beginGradientFill(reflectGrad, reflectColors, reflectAlphas, reflectRatios,reflectMatrix,spreadReflect)
   reflect.graphics.drawRect(0, 0, 120, 120);
   reflect.x = 50;
   reflect.y = 200;
   addChild(reflect);
//Repeat Spread Method
var spreadGrad:String = GradientType.LINEAR;
   var spreadMatrix:Matrix = new Matrix();
   var spreadMeth:String = SpreadMethod.REPEAT;
   spreadMatrix.createGradientBox(20,20,0,0,0);
   var spreadColors:Array = [0xb61322, 0x580408];
   var spreadAlphas:Array = [1, 1];
   var spreadRatios:Array = [0, 255];
   var spread:Sprite = new Sprite();
   spread.graphics.beginGradientFill(spreadGrad, spreadColors, spreadAlphas, spreadRatios,spreadMatrix,spreadMeth);
   spread.graphics.drawRect(0, 0, 120, 120);
   spread.x = 200;
   spread.y = 200;
   addChild(spread);
//Pad Spread Method
var padGrad:String = GradientType.LINEAR;
   var padMatrix:Matrix = new Matrix();
   var spreadPad:String = SpreadMethod.PAD;
   padMatrix.createGradientBox(20,20,0,0,0);
   var padColors:Array = [0xb61322, 0x580408];
   var padAlphas:Array = [1, 1];
   var padRatios:Array = [0, 255];
   var pad:Sprite = new Sprite();
   pad.graphics.beginGradientFill(padGrad, padColors, padAlphas, padRatios,padMatrix,spreadPad)
   pad.graphics.drawRect(0, 0, 120, 120);
   pad.x = 350;
   pad.y = 200;
   addChild(pad)

November 11, 2008 at 1:37 pm Leave a comment

Beginners OOP ActionScript Tutorial – part 3

For users who prefer to learn Flash visually we have a range of Adobe Flash CS3 video tutorials, this method of training greatly enhances learning and allows beginners to master even the most complex aspects of Adobe Flash with ease.
View the Beginners Flash CS3 Video Tutorial.

.

Instance Variables

Instance Variables are variables that are contained in each ‘instance’ of the Class; so every instance of the TextHandler Class will have it’s own TextFormat variable. Instance Variables should be initialised (given an initial value) in the constructor function, which is called whenever an Object of the Class is created. It is important, however, to refer to the instance variables outside the constructor, as in the above example, so that they are ‘visible’ to the entire Class.

Constructor Function

When you use the keyword ‘new’ to create an Object of a Class, what actually happens is that the ActionScript code within the constructor function for the Class is executed, returning an Object of the Class. The constructor function does not have to have the return type specified, as it is identified by having the same name as the Class itself.

To illustrate, imagine you wanted to create several of the TextHandler Objects, each with different formatting (i.e. different colour, font etc); you could alter the Class declaration so that the constructor function takes parameters indicating e.g. the colour, and these properties of the TextFormat object could be set within the constructor code. This way your main application code could create several different Objects of the TextHandler Class, each handling the textfields that you want to format in the same way (make the changes to your Class declaration and Flash document code):

//class code constructor
public function TextHandler(col:Number)
{
tf=new TextFormat();
tf.color=col;
}

//main code creating object
var myHandler:TextHandler = new TextHandler(0xFF0000);

To test this, place another dynamic textfield on your stage and name it other_txt, again with arbitrary text in it. Now add the following to your Flash document code:

var otherHandler:TextHandler = new TextHandler(0x0000FF);
otherHandler.formatText(other_txt);
//When you test the movie, other_txt should appear blue.

This trivial example may appear odd at first, but once you have gotten into the habit of thinking in terms of Objects, you’ll soon see how the techniques can save you a lot of stress. Experiment within your applications by creating Classes and Objects, with the following additional guidance:

  • Functions can have as many parameters (of any datatypes) as you need, but can only have one return type; you must declare this when you devise the method (as in the stripChars function above where the return type is specified as String).
  • The functions within a Class that are declared with the keyword ‘public’ are those that can be called on any Object of that type, wherever it has been created, as with the formatText method above.
  • Additionally, Classes may feature private functions that are for use within the Class only; these are referred to as ‘helper’ functions and are used in much the same way as the stripChars function was in our original example. You will use such functions within your Classes where processing is repetitive or where the code contained within a function becomes overly long or complicated.

Class Overview

Look again at the (amended) version of your TextHandler Class declaration. In terms of the interface, the Class contains a constructor function (which takes one parameter of the type Number, representing the colour) and a single function for formatting text, which takes one parameter of the type textfield, and returns nothing.

Try adding more functions to the Class – e.g. add the stripChars function, using the keyword ‘public’ in front of it, then try calling it from your movie, passing it a String as in the original example.

In theory, the TextHandler Class could have been created by someone else and you could still use it as long as you know: what the Class is for, what the functions are called (and what their purpose is), what parameters they take, and what data they return, if any. If you think about it, this is all you know about the built-in Classes that you use regularly.

The ‘interface’ can also be made more explanatory through the use of documentation and comments, as is the case with the built-in Classes. You can see an example of this with the official Adobe documentation for the TextFormat Class in ActionScript 3.0 here: http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/flash/text/TextFormat.html

- this gives you limited insight into the TextFormat Class declaration.

As with the stripChars helper function example above, if at any stage during your development process, you decide to change any of the implementation details within your Classes’ functions, you should be able to do so without upsetting any other code, as long as your interface remains the same. e.g. If you decided to change the for loop in the stripChars function to a while loop (for whatever reason) it wouldn’t affect the rest of the code, as long as it performs the same function.

Summary

The Object Oriented design method is a good way to achieve well-organised applications, but the success of the technique does depend strongly on Classes being defined in a clear manner. If you’re struggling at all to grasp the technical notions, have a try at using Classes anyway; as long as you stick to the principles outlined above, you should be able to define and create useful Objects.

It can be challenging to understand these notions when you’re starting out as a programmer and have built only relatively small applications. However, even where you are developing applications single-handed, Object Oriented design can make for efficient programs that are easily manageable.

If you’re interested in exploring Object Oriented development further, advanced areas to study include: Packages; Inheritance; Polymorphism; Interfaces; Abstract Classes.

November 7, 2008 at 12:15 pm 1 comment

Beginners ActionScript OOP Tutorial Part 2

For users who prefer to learn Flash visually we have a range of Adobe Flash CS3 video tutorials, this method of training greatly enhances learning and allows beginners to master even the most complex aspects of Adobe Flash with ease.
View the Flash CS3 Training CD.

.

Beginners OOP with ActionScript – part 2

Using Objects

To use an Object Oriented approach, you need to learn to characterise your applications in terms of ‘Objects’, interacting with one another to deliver your program. With larger applications, this will be a ‘high-level’ analysis of the various program requirements, and is carried out before any programming takes place. For example, with languages for which Object Oriented development is often used, such as Java and C++, applications are normally built by a team of people. In these circumstances, each member/ section of a team will be responsible for developing specific parts of the application. When it comes to building the application as a whole out of these component parts, it is vital that the parts have what’s called a ‘well-defined interface’. This means that the different components can work together, without having to know each others details.

For example, when you use the Classes built-in to ActionScript as in the above example, you can create Objects of the TextFormat class and use its various methods easily, without having to understand how these methods are actually implemented in the underlying code. Similarly, when you create your own Classes, you will decide on the data and functions that any Objects of the Class will have, but the details of how these functions are carried out will remain relevant only within the Class itself. So in order for this approach to be successful, you need to ensure that your Classes have meaningful, clearly defined behaviour.

To demonstrate, let’s create a simple Flash application with a Class declaration. In this example, you are creating a movie that carries out various operations on text/ textfields (among other things). Given that this is a regular feature of your program, you decide to create an Object that will be responsible for all tasks relating to text; meaning that it will contain all text/textfield-related code. Your Class declaration might be something like this (further explanation follows):

class TextHandler
{
//class instance variable
var tf:TextFormat;

//constructor function - initialises any instance variables
public function TextHandler()
{
tf=new TextFormat();
tf.color=0xFF0000;
}

//function to format text with the TextFormat
public function formatText(txtField:TextField):Void
{
txtField.setTextFormat(this.tf);
}

//the class would also have other functions relating
//to text processing
}

This code should be saved in a file named ‘TextHandler.as’ identifying it as an ActionScript class file. Once you’ve defined a Class declaration like this, you can then create ‘instances’ of the Class in your main code; these are the ‘Objects’. You can then use the Objects to carry out the functionality contained in the Class declaration. To do this, create a new Flash document and save it in the same directory as your TextHandler.as file, then create a dynamic textfield on the stage, giving it the instance name my_txt, and put some arbitrary text in it:

//in your main code - Flash file in the same directory
//as the class import TextHandler;
//create an object of the class TextHandler
var myHandler:TextHandler = new TextHandler();
//call a function on it - the movie contains my_txt textfield
myHandler.formatText(my_txt);

When you test your movie, the text should appear red.

To explain a little further about the Class declaration see part 3 of this ActionScript OOP Tutorial:

November 7, 2008 at 12:12 pm 1 comment

Beginners ActionScript Object Oriented Programming part1

For users who prefer to learn Flash visually we have a range of Adobe Flash CS3 video tutorials, this method of training greatly enhances learning and allows beginners to master even the most complex aspects of Adobe Flash with ease.
View the Adobe Flash CS3 Tutorial.

.

Object Oriented Programming with ActionScript – part 1

As your Flash applications grow more complex, relying on substantial amounts of ActionScript code, efficiency will become more of an issue. Applications that use well-organised code are more reliable, and lend themselves better to future extension. One approach to developing such systems is Object Oriented design, which we will explore in this tutorial. Even if you’re new to the concept of Object Oriented design, you may find that you have already adopted some of the techniques on which it is based.

The Concept of OOP with ActionScript

You will likely already have used Objects in your ActionScript code whether you’re aware of it or not. For example, your code may have used the TextFormat class:

var tf:TextFormat = new TextFormat();

In this example, we create a new Object of the Class TextFormat. This means that the Object has the properties and behaviour that are defined in the TextFormat Class declaration. This Class is part of ActionScript itself, and you can therefore create and use TextFormat Objects just by inserting the single line above. With Object Oriented design, you will be designing your own Objects, by creating Class declarations for them in ActionScript, then importing them into your Flash for use there.

The concept of Object should be familiar to you if you have used Library items and Symbols in Flash. When you create a MovieClip, for example, and define what happens within it, the MovieClip symbol in your library is like a blueprint or prototype for that kind of Symbol. When you then use instances of the MovieClip Symbol within your Flash movie itself, each of these instances has the properties and behaviour that you defined when you created the MovieClip originally. This process is analogous to what you’ll do with your ActionScript Classes. The Class declaration is where you define the properties (in ActionScript) that any instances of the Class will have when you create them, as with the TextFormat object above.

Well-organised code

The reason for adopting any design methodology is to produce applications that are reliable, efficient and easy to perform future amendments or extensions upon. This is similarly the case with Object Oriented development. To begin, we will look at some of the simple efficiency measures that you can take during your regular programming routine, and demonstrate how these form the basis for the Object Oriented approach.

There are many techniques to achieving well-organised code when creating Flash applications. The simple act of including plenty of comments and whitespace in your code makes for a component that is easier to debug and extend. Similarly, organising your code into sensible chunks of related processing is helpful. When doing this, creating what are referred to as ‘helper’ functions (something that you may have already done), illustrates the basic principle behind Object Oriented design.

Let’s look at a simple example. When you are writing ActionScript code, you will often find that you are carrying out similar processes repetitively. When this is the case, you should consider creating functions to carry out those processes, effectively allowing you to cut down on the amount of code you need to achieve the same functionality. Imagine you have a Flash movie that contains several text Strings whose content varies, maybe the text is being imported from some external file which has unpredictable content. You have decided that you don’t want to display any content that isn’t alphanumeric, i.e. you only want letters and numbers. For this reason you will have to perform text processing on each of the Strings before you display them. Your code might look like this (feel free to paste this into a Flash document to try it out – don’t worry too much about the String processing code if it’s unfamiliar to you, the details are unimportant, but pay attention to the overall structure of the code):

//strings - nonsense
var first_str:String="kdfHGKj kkv e$ deagf% /.;fghlkjsf'h'";
var second_str:String="bcn'l;gH;'(fghsf ";
var third_str:String="bcnf..,\\gj[] *dFG";

//strip out non alphanueric from first
var firstStripped_str:String="";
for(var i:Number=0; i="0" && ch<="9") || (ch>="a" && ch<="z"))
firstStripped_str+=first_str.charAt(i);
}
trace(firstStripped_str);

//strip out from second
var secondStripped_str:String="";
for(var j:Number=0; j="0" && ch<="9") || (ch>="a" && ch<="z"))
secondStripped_str+=second_str.charAt(j);
}
trace(secondStripped_str);

//strip third
var thirdStripped_str:String="";
for(var k:Number=0; k="0" && ch<="9") || (ch>="a" && ch<="z"))
thirdStripped_str+=third_str.charAt(k);
}
trace(thirdStripped_str);

This can be easily improved by making a ‘parameterised’ function, meaning a function that will carry out the same processing but which takes the Strings as parameter, making it adapt to each different circumstance:

//strings - nonsense
var first_str:String="kdfHGKj kkv e$ deagf% /.;fghlkjsf'h'";
var second_str:String="bcn'l;gH;'(fghsf ";
var third_str:String="bcnf..,\\gj[] *dFG";

function stripChars(my_str:String):String
{
var stripped_str:String="";
for(var c:Number=0; c="0" && ch<="9") || (ch>="a" && ch<="z"))
stripped_str+=my_str.charAt(c);
}

return stripped_str;
}

trace(stripChars(first_str));
trace(stripChars(second_str));
trace(stripChars(third_str));

Notice how much more concise the code is – test the movie to check that both versions of the code have the same effect. What you have done is to give the function ‘responsibility’ for the text processing. One of the advantages to doing this is that, if you decide to change the process in any way, you only have to do it in one place (within the function) – this is a single ‘point of change’. Eventually, when you have gotten into the habit of thinking this way when writing your code, you will start to anticipate the practice, rather than carrying it out retrospectively, and will save yourself a lot of time and effort in doing so.

While the above technique does make the code more efficient, it is still ‘procedural’ rather than Object Oriented in structure. Procedural programs are basically a series of instructions being executed in turn. When the movie is run, the code listed on the main timeline is executed in a linear fashion, i.e. each line is processed one after the other until the machine is instructed otherwise. To adopt Object Oriented design, we need to extend the notion of creating ‘helper’ functions, and to develop ‘helper’ Objects to carry out the processing within a movie. In the same way that we allocated the text-processing responsibility to a function, we can assign responsibility for the individual parts of an application to Objects – we can ‘delegate’.

ActionScript Object Oriented Programming Tutorial Part 2

November 7, 2008 at 12:08 pm Leave a comment

Flash Tutorial – Embed Fonts in ActionScript 3

For users who prefer to learn Flash visually we have a range of Adobe Flash CS3 video tutorials, this method of training greatly enhances learning and allows beginners to master even the most complex aspects of Adobe Flash with ease.
View the Adobe Flash CS3 Training Videos.

.

Dynamically Embed Font In Actionscript 3.0

In this Flash tutorial we’ll be looking at how to embed Flash font dynamically using Actionscript 3.0. If you’ve ever used text in your Flash applications you’ve probably noticed that when you preview your Flash file the text doesn’t always render properly. Look at the image below as an example. The first example “Text Example A” has been embedded with Actionscript and the second example “Test Example B” was typed out on the stage using the basic text tool. You can clearly see the difference in the two.

Embedding your flash font also has other advantages;

  • Embedded font characters are anti-aliased, making their edges appear smoother, especially for larger text.
  • You can rotate text that uses embedded fonts.
  • Embedded font text can be made transparent or semitransparent.
  • You can embed almost any type of font on your system.

Step 1 – Library Panel

Our first task is to create a new font symbol to do this we need to open up the Library Panel (Window – Library). Inside the library panel we create a new font by clicking the drop down arrow and selecting New Font from the drop down box, this will open up the Font Symbols Properties Dialog Box. Inside the dialog box we define a name for our font symbol and select the font styles and properties that we require.

 

We then export our Font Symbol for Actionscript so that Actionscript has access to the font symbol. To do this we Right Click the font name and select Linkage from the drop down menu.

 

Once we select Linkage from the menu the Linkage Properties Box pops up. Inside the Linkage properties box we check the “Export For Actionscript” checkbox and give it a class name, in this case we’ve just kept the default class name that flash has provided for us.

So to recap;

  1. Open the library panel (Window – Library).
  2. Select New Font from the Library Panel menu.
  3. Enter a name for the font in the Name field.
  4. Select the font and styles that you require for the application.
  5. Right click the new font inside the library and select Linkage.
  6. Check the export for Actionscript checkbox.
  7. Give it a unique class name or keep the default name (Font1).

Step 2 – Adding Actionscript

Our next task is to create some Actionscript so select the first Keyframe on the timeline and press F9 to open up the actions panel. We need to create a text field for the text so we create a new TextField object and call it flashText. This creates an instance of the TextField class and gives us access to all the properties, methods and events of that class.

var flashText:TextField = new TextField();

Our TextField is empty so we use the text property to fill it with the text of our choice, in this case it’s “Text Example A”.

flashText.text = “Text Example A”;

We can position the TextField where we want on the stage by changing the X and Y properties. The X and Y properties in Actionscript are measured in pixels and the default value is 0.

flashText.x = 25;

flashText.y = 30;

 We want to access the font that we created in step one, by creating a new instance of the Font1 symbol object gives us access to it. We’ll name this object myFont.

var myFont:Font = new Font1();

Next we create a TextFormat object called textFormat, again giving us access to all the properties, methods and events available to that class. The TextFormat class will allow us to change the size and font properties.

var textFormat:TextFormat = new TextFormat();

This line sets the font property to the flashText object’s fontName property. Essentially making sure the textFormat font property is using the font we have embedded.

textFormat.font = myFont.fontName;

Set the text size of the text to 26px.

textFormat.size = 26;

The autoSize property controls automatic sizing and alignment of text fields. We’ll us this property to align the text inside the TextField to left-justified text, this just works in the same way as left justified in a word document for example.

flashText.autoSize = TextFieldAutoSize.LEFT;

The defaultTextFormat property specifies the format applied to newly inserted text, it sets the TextFormat properties to the TextField.

flashText.defaultTextFormat = textFormat;

Setting the TextField embedFonts value to true tells the Flash Player to use the embedded font instead of the default device font.

flashText.embedFonts = true;

Setting the antiAliasType property to AntiAliasType.ADVANCED sets the text inside the TextField to anti-aliasing to advanced anti-aliasing. This allows the font to be shown at a high quality when using smaller font sizes.

flashText.antiAliasType = AntiAliasType.ADVANCED;

The addChild()method adds the TextField to the stage, making it visible when the file is previewed.

addChild(flashText);

Code In Full;

var myFont:Font = new Font1();
var textFormat:TextFormat = new TextFormat();
textFormat.font = myFont.fontName;
textFormat.size = 26;
var flashText:TextField = new TextField();
flashText.autoSize = TextFieldAutoSize.LEFT;
flashText.defaultTextFormat = textFormat;
flashText.embedFonts = true;
flashText.x = 25;
flashText.y = 30;
flashText.antiAliasType = AntiAliasType.ADVANCED;
flashText.text = “Text Example A”;
addChild(flashText);

November 5, 2008 at 4:26 pm 1 comment

Flash Tutorial – Drawing Shapes with ActionScript

For users who prefer to learn Flash visually we have a range of Adobe Flash CS3 video tutorials, this method of training greatly enhances learning and allows beginners to master even the most complex aspects of Adobe Flash with ease.
View the Flash CS3 Tutorial Videos .

.

Flash Tutorial – Drawing Shapes with ActionScript

This Flash Tutorial follows on from the “Drawing Lines and Shapes in Flash Tutorial

Now we have managed to draw a straight line and a curve lets move on to making shapes. After reading this Flash Tutorial you should be able to dissect the code and use it in your own Flash content

Download Files Used in this tutorial

Drawing a Rectangle
We’ll first create a new Sprite object called container, this will hold all our shapes graphical information. This was covered in our last tutorial, but just as a reminder we shall briefly cover the steps again.

var container:Sprite = new Sprite();

We add the new Sprite object to the stage by using the addChild() method, using the addChild() method makes adds it to the display list essentially making it visible when you preview or publish the file.

addChild(container);

This next line is optional when drawing shapes and only has a use when you want to give your shape a specific outline colour. The lineStyle() method lets us style the outline of the shape. It has 3 parameters available to it thickness, colour and alpha scale. Thickness is measured in pixels, colour in decimal format and alpha, which is an optional parameter, is measure in percent (1 = 100%, .25 = 25%). We assign the method to the graphics property and then assign the graphics property to our Sprite object so that all the graphic information resides inside the Sprite object.

container.graphics.lineStyle(2,0x000ff0,.4);

We want to fill the rectangle with a colour. We use the beginFill() method to fill it with a colour of our choice. The beginFill() method has 2 parameters avalible to it colour and alpha scale, again the alpha scale is optional. In the code below we’ve given it the colour red and set the alpha scale to 80%.

container.graphics.beginFill(0xff0000, .8);

Now that we have the colour and outline properties it’s time to draw out the rectangle. Drawing the rectangle itself is pretty straight forward, using the drawRect() method we set the properties we require for the rectangle. The drawRect() method requires 4 parameters, X and Y values, and width and height. The X and Y values indicate the position of where you want to draw out the rectangle, and the width and height determine the size of the rectangle. In our code we’ve positioned the rectangle to a position of 20px by 20px and set the size to 100px by 100px.

container.graphics.drawRect(20,20,100,100);

To finish off the rectangle we use one final method called the endFill(). The endFill() method closes off the beginFill() method, basically telling it we no longer require the colour fill as we’ve finished the rectangle.

container.graphics.endFill();

Drawing a Round Rectangle

Drawing a round rectangle requires a little more thought, first we give it some line styles and colour fill properties using the lineStyle() and beginFill() methods just like we did previously. To draw a round rectangle we use the drawRoundRect() method, this method requires 6 parameters. The first 4 parameters are the same as the drawRect() method as they declare the position and size of the rectangle. It’s the last 2 parameters ellipseWidth and ellipseHeight that create the round corners of the rectangle, ellipseWidth measured in pixels declares the width of the ellipse and ellipseHeight measures the height of the ellipse. In our code the round rectangle has the ellipse width and height of 20px respectively.

Tip; An ellipse is a curve for which the sum of the distances from each point on the curve to two fixed points is equal.

container.graphics.lineStyle(4,0×000044);
container.graphics.beginFill(0×333333);
container.graphics.drawRoundRect(300,50,200,75,20,20);
container.graphics.endFill();

Drawing a Circle

Drawing a circle is straight forward, again we create the style and colour fill using the lineStyle() and beginFill() methods. To draw the circle itself we use the drawCircle() method, the drawCircle() method requires 3 parameters, X and Y values and a radius value. The X and Y values indicate where you want the circle positioned and the radius measured in pixels declares the size of the circle itself. Our circle below is positioned at 200px by 80px and has a radius of the 50px.

container.graphics.lineStyle(2,0xff0000,.4);
container.graphics.beginFill(0x00ff00, .8);
container.graphics.drawCircle(200,80,50);
container.graphics.endFill();

November 5, 2008 at 12:38 am 2 comments

Flash Tutorial – Drawing Lines and Shapes with ActionScript

For users who prefer to learn Flash visually we have a range of Adobe Flash CS3 video tutorials, this method of training greatly enhances learning and allows beginners to master even the most complex aspects of Adobe Flash with ease.
View the Flash CS3 Tutorial Videos .

.

Flash Tutorial – Drawing Lines and Curves using Actionscript 3.0

We all know you can create shapes and lines in Flash using the many drawing tools, but did you know you can unleash the power of ActionScript to create shapes on the fly.

In this Flash tutorial we’ll be looking at how to draw lines and curves using Actionscript 3.0. In the examples below we’ll use methods from graphics class to draw out the lines and curves. The benefit of drawing in Actionscript rather than using tools from the Flash interface is that it makes for a much smaller file size. Below we’ll go through the code line by line and draw out the line and curve in shown in the example .swf file.

Download the SWF File

Drawing Lines
First thing we’ll look at is how to draw a simple line. We’ll first create a new Sprite object called “container”, this will hold all our graphical information for the line. A Sprite is just a Movie-Clip without a Timeline.

Open up Flash and launch the Actions Panel.

var container:Sprite = new Sprite();

To display the new Sprite object or add it to the stage we use the addChild() method. This makes it visible when you preview or publish the file.

addChild(container);

Next we want to draw the line itself, our first task is to choose the style of the line. To do this we use the lineStyle() method, the lineStyle() method has 3 parameters available to it thickness, colour and alpha scale. Thickness is measured in pixels, colour is in decimal format and finally alpha scale, which is an optional parameter measured in percent (1 = 100%, .5 = 50%). We assign this method to the graphics property and then assign that graphics property to the Sprite object, so that everything is added to the Sprite object.

container.graphics.lineStyle(3,0×333333);

Now that we have the style properties of the line it’s time to decide on our starting point. The starting point will indicate where we are drawing from, to declare the starting point we use the moveTo() method. This method requires 2 parameters, X and Y position. The X and Y values will indicate the starting position of where we want to draw from.

container.graphics.moveTo(20,20);

We have the starting points and are now ready to draw the line. The starting point needs an ending point or somewhere to draw to. Using the lineTo() method we declare the point we’re drawing to. The lineTo() method uses the same parameters as the moveTo() method, the only difference is with the lineTo() method we’re declaring where we are drawing to instead of where we are drawing from.

container.graphics.lineTo(450, 20);

It is possible to draw shapes by continuing to use the lineTo() method, as Actionscript executes in linear fashion we can also change the style of the line at any given point. Adding the code below to the code we’ve already written draws a small rectangle, we draw out the rectangle but change the style of the line by inserting a new lineStyle() method. This means the last two lines will be drawn in red.

container.graphics.lineTo(450,50);
container.graphics.lineStyle(3,0xff0000);
container.graphics.lineTo(20, 50);
container.graphics.lineTo(20,20);

Drawing Curves
Drawing curves is also pretty straight forward but instead of using the lineTo() method we use the curveTo() method. The curveTo() method also works with the moveTo() method to determine our starting point. The curveTo() method however requires 4 parameters, x and y positions of the curve and X and Y positions of the ending point. Using this code below will give us a nice red curve.

var curve:Sprite = new Sprite();
addChild(curve);
curve.graphics.lineStyle(3,0xff0000);
curve.graphics.moveTo(50,150);
curve.graphics.curveTo(225, 0, 450, 150);

For a more clear explanation look at the diagram below, you can see the moveTo() starting points indicated by the arrow. The curveTo() parameters are also highlighted in green, the first 2 parameters show the X and Y points of the curve. The final 2 parameters also highlighted in green show the X and Y points of where the ending point of the curve is.

In the next Flash Tutorial we will move on to creating Shapes with ActionScript

November 3, 2008 at 6:48 pm 1 comment

Older Posts


Follow us on Twitter


Follow

Get every new post delivered to your Inbox.