Categories
Articles

Actionscript 3 Spray Paint with BitmapData

By Lon (Alonzo) Hosford

This my own version of of Keith Peter’s Foundation Actionscript 3.0 Animation: Making Things Move chapter 4 use of the BitmapData class to create a spray paint example.

Download files
[August 10 2010 – I updated this to an Actionscript project in Flex Builder 4. ]

You can build this with the free Flex SDK by using the code in the src folder. Same for Flash CS3 and later versions. You need to create a Flash Document in the src folder and set the document class to Chapter04_SprayPaint. For your convenience the Flash CS4 example download is included.

Keith Peters AS3 Animation
Learn More

This article shows the code for the Flex project. This Flex version is a spark implementation.

Application Class – Chapter04_SprayPaint
The canvas instance of the BitmapData class is instantiated line 32. The BitmapData class setPixel32(...) method on line 83 is used to set the color and alpha transparency values of a single 32 bit pixel.

The overall user interaction is mouse down start the enter frame events that call the draw() method and also to select a random color.

<?xml version="1.0" encoding="utf-8"?>
<!--
	Application class to demonstrate use of the BitmapData class along with animation trigonometry. 
	<p>Author: Lon Hosford https://www.lonhosford.com 908 996 3773</p>
    <p>Reference: Keith Peter's Actionscript 3.0 Animation Chapter 4</p>
	
-->
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009" 
			   xmlns:s="library://ns.adobe.com/flex/spark" 
			   xmlns:mx="library://ns.adobe.com/flex/mx" width="400" height="400"
			   creationComplete="creationCompleteHandler(event)" 
			   viewSourceURL="srcview/index.html">
	<fx:Script>
		<![CDATA[
			import mx.events.FlexEvent;
			
			// Properties for background
			private static const backgroundColor:Number = 0xffffff;
			private static const backgroundBorderColor:Number = 0x666666;
			private static const backgroundBorderWeight:Number = 2;
			private var canvas:BitmapData;			// Pixel level access
			private var color:uint;					// Randomly generated spray brush colors
			private var size:Number = 20;			// Size of the spray brush
			private var density:Number = 50;		// Number of pixels sprayed per frame
			/**
			 * Handler for Application creationComplete event
			 * */
			protected function creationCompleteHandler(event:FlexEvent):void
			{
				
				// Create BitmapData object allowing use to work with pixels
				canvas = new BitmapData( background_bc.width,background_bc.height, true, 0x00000000);
				var bmp:Bitmap =  new Bitmap(canvas);
				
				// Add itmapData object to a SpriteVisualElement
				arrowVisualElement.addChild(bmp);
				// Handlers for mouse events to signal drawing.
				addEventListener(MouseEvent.MOUSE_DOWN, mouseDownEventHandler);
				addEventListener(MouseEvent.MOUSE_UP, mouseUpEventHandler);
			}
			/**
			 * Event handler for MouseEvent.MOUSE_DOWN
			 * */
			private function mouseDownEventHandler(event:Event):void 
			{
				// Random color from 0 to highest color value which is white
				// and then add alpha channel of opaque
				color = Math.random() * 0xffffff + 0xff000000;
				// Start enter frame events
				stage.addEventListener(Event.ENTER_FRAME, enterFrameEventHandler);
			}
			/**
			 * Event handler for MouseEvent.MOUSE_UP
			 * */
			private function mouseUpEventHandler(event:Event):void 
			{
				stage.removeEventListener(Event.ENTER_FRAME, enterFrameEventHandler);
			}
			/**
			 * Event handler for Event.ENTER_FRAME
			 * */
			private function enterFrameEventHandler(event:Event):void 
			{
				draw();
			}

[ad name=”Google Adsense”]
The draw method uses the density variable on line 72 to determine the number of pixels to color using randomization to compute an angle and a radius within the size of the brush.

Each pixel is basically a point on its own circle. The mouse is becomes a center point for a random circle with a diameter up to the size variable. Line 77 computes the radius for that circle.

Keith’s formulas for computing points on a circle math from chapter 3 are then used to compute the position of the pixel on lines 79 and 81.


			/**
			 * Draw
			 * */
			private function draw():void 
			{
				// Repeat for number of pixels - density.
				for (var i:int = 0; i < density; i++)
				{
					// Random angle 0 - 6.2832 radians  (0 - 360)
					var angle:Number = Math.random() * Math.PI * 2;
					// Radius is random percentage of maximum radius (size / 2)
					var radius:Number = Math.random() * size / 2;
					// Center is mouseX to compute the x point
					var xpos:Number = mouseX + Math.cos(angle) * radius;
					// Center is mouseY to compute the y point
					var ypos:Number = mouseY + Math.sin(angle) * radius;
					//Set the color and alpha transparency values of a single 32 bit pixel.
					canvas.setPixel32(xpos, ypos, color);
					
				}
			}

		]]>
	</fx:Script>

[ad name=”Google Adsense”]
The SpriteVisualElement component allows adding the canvas BitmapData object to the display list.

	<!--- 
	Background for app 
	--> 
	<s:BorderContainer id = "background_bc"
					   width="{width}" height = "{height}"
					   borderWeight="{backgroundBorderWeight}"
					   borderColor="{backgroundBorderColor}"
					   backgroundColor="{backgroundColor}">

		<!--- 
		Spark container for Sprite 
		--> 
		<s:SpriteVisualElement id="arrowVisualElement" />

	</s:BorderContainer>
	<!--- 
	Instructions 
	--> 
	<s:Label x="96" y="378" text="Click and drag mouse to spray paint."/>
					   
</s:Application>
Categories
Articles

Using MXMLC for Sharing Common Libraries

When using mxmlc (the Flash Flex AS3 command line compiler) I wanted to create a folder structure for sharing a common libraries but for different examples and apps that have their own sibling folders. This would keep the parent folder of both the library and the apps clean.

Ex:

com.hosford.core

com.hosford.controls

apps.clock

apps.diceRoller

I use Windows and batch files for mxmlc. I prefer to copy a new version of the batch for each need and edit rather than type at the command line. Thus I can just click the batch file in a Window for each iteration.

I also do not use any environment variables so the batch file allows for hard paths were needed.

Assume in apps.clock the source file was ClockApp.as

Its package would be:

package apps.clock{

The imports are as you can expect:

import com.hosford.controls.* 

The mxmlc line is in a Windows batch file is as follows:

"C:\Program Files\Adobe\Flex Builder 2\Flex SDK 2\bin\mxmlc.exe" "-source-path+=../../" "-file-specs=ClockApp.as"


The -source-path option is the item that allows ClockApp.as to find the com libraries. The += adds to any environment path you also have.

Categories
Articles

FlashTracer Extension For Firefox

Debugging Flash in a Web browser creates all sorts of issues and clever solutions. Anywhere to having one Flash movie talk to another through LocalConnection, to a floating TextField or TextArea object or Movie containing such with a grabber and perhaps some buttons to using the difficult built in remote debugging built-in.

Adobe now has a Flash Debugger version. One of its features is outputting the trace function to a local file. A bit geeky on how to go about setting up that but it can be done. And so others have created solutions already.

One solution is FlashTracer. This is a Firefox plug-in that uses the Flash debugger version.

Once installed you will be seeing trace statements from the millions of Flash Movies on the Internet where the publishers failed to check “Omit trace actions” on their final publish.

But more so you can debug tricky client server Flash web apps quicker seeing your trace statements in a Window.

FlashTracer Version 2.0 download Note the Mozilla plug-in page has the older 1.3.1 1 version of FlashTracer.Flash Player Debug Version Download

The author is Alessandro Crugnola in case the links above get moved.

A good instructional site that covers installation and use is Flash PowerTools: FlashTracer for Firefox just be careful as the links here take you to the Firefox plug-in pages and that has the older 1.3.1 1 version of FlashTracer.

Just be careful as the links here take you to the Firefox plug-in pages and that has the older 1.3.1 1 version of FlashTracer. Other than the download links, follow the few short instructions here and you are good. The instructions do not cover the new features in 2.0 however but the product is relatively simple with just a few buttons and options.

After the plug-in installation, the instructions have you enter in a path that you modify to the location and name of the output file.

In my case the path was: C:\Documents and Settings\MyUserName\Application Data\Macromedia\Flash Player\Logs\flashlog.txt

You also can open this same output file in an editor like Dreamweaver or TextPad and use their search functionality. The file will update as you are using Flash movies in FireFox as well.

Categories
Articles

Flash Simulations for Flash Animation and Interaction Development

Flash is very useful for creating simulations. One example I did was for the Avaya IP office phones.

The use of Flash for simulations is wide open territory of potential.

Using Flash to Simulate Flash

One use I think requires serious consideration is using Flash to simulate Flash development. With the widespread move to developing complex applications with Flash we find the problem of successfully communicating the interactivity and animation timings of creative ideas.

Add to that requirement the Flash movies dynamically consuming and generating data. The data may include user data such as ecommerce but could also be UI data to configure the UI dynamically. In other words they cannot be hand coded on the time lines in Flash. Rather the interaction and animation is communicated to software programmers to reproduce in Actionscript that consume data from a server for the dynamic processing.

The High Cost and Failure of Flash Development

This communication from creative to developers is where you have a lot of failure or at least a lot of costly repetitions. WE have various vehicles such as storyboards and “comps” and flow charts and use cases to help in the process.

The programmer produces from these communication vehicles the end product. A good programmer can produce exactly what was requested. Therein the problem begins. You can get what you ask for which is not what you think you want.

Often the finished result fosters reconsideration because a moving picture is worth a thousand words. Details such as how fast a fade out of an item like unselected menu choices or when another item such as the selected menu choice should begin to move becomes more visual as the programmer delivers your request.

Although such a simple set of animations seems easy to envision, it becomes more complicates as there is a need to also slide in a grid of product items from one direction and then fade out a background and more and more until words and screen shots fail your imagination.

Your  observation of what the programmer delivers then leads to the need to change it. Change then results in more costs and delays because the resource you are using for the iterative review need is incorrectly choosen.

Lack of Skills In Communicating Animation and Interactivity

In a project with a major international consumer products company I met very creative marketing talent. They had vast resources and skills for dealing with print and broadcast media. They along with interactive consultants also could envision very creative ideas for interactivity and animation on a broad level. Dealing with the details however revealed a handicap.

They used their expert skills in design communication in these medias to design a large rich internet application upgrade for their web site. During the development process completed complex Flash code was changed over and over as the review process produced a need to change.

Now you might say that is not a good. But in the case of a consumer products company, spending time and money to get it right for marketing is key. Despite creative visions they had on the broad scale, the details were missing. Somewhat like watching a movie over and over and seeing something new each time. Well that is what animation and interactive design is about.

Still this process of iterations to get it right resulted in delays and frustrations because they were missing an important step.

How to Use Flash Simulations in Flash Development

Along the way I recommended a solution. Continue to use the current communication vehicles such as Powerpoint storyboards and Photoshop renderings. However add one step between those and the programmer. That is to use Flash to simulate.

Simulation allows for viewing the end result without the pain of producing the full working model. To do this efficiently you simply use the standard Flash IDE. You can even use junior college students with Flash skills to take the story boards, graphics and do some or all of the work.

Simulations may or may not allow interaction. For example the simulation may start after a user interaction and merely show the sequence of events up to the next step. This is how storyboards are used. The storyboard shows the key frames. The animators make the in between frames.

Once the Flash simulation is complete, everyone can view and comment. The simulation can then be modified cheaply from tweaking to showing more detail to get it right.

Then the simulation along with the other supporting communication documentation become the starting material for the Flash programmer.

The result is less programming resources, better software and less frustration trying to visualize the end result.

Categories
Articles

Using External Style Sheets to Drive Flash Skins

One of my favorite items is to develop Flash components where the skins and even sizes are controlled by external data. Or as we say they are data driven.

One technique to deliver those parameters is via style sheets.

Flash allows you to create any style property you want. So you are not limited to just CSS standards. For example you can create a style named outerBorderGutterWidth. Flash will provide it nicely in the StyleSheet object.

I recently created a slide out menu component. It contains default skin and size parameters. Its data is dynamically driven as you might expect. But also its skin defaults are dynamically changeable both at design time and run time.

The component can open close by sliding up, right, down and left. The slide’s tween can do any of the easing in the Flash Tween component code such as bounce, elastic, regular, strong, back and none. As well the speed is a property of the component.

When the component is accessed on stage as a drag and drop or in code or in code, these properties can be set. On stage we use the Flash component parameters panel. In code we set these properties via the init parameter of attachMovieClip method. As well we can expose class properties for runtime access per design needs.

Great for the programmer! But can we give access to less technical user?

Part of the component properties is a style selector. As well as part of an overall site framework a style sheet is made available to component. If the style selector contains custom properties they override any created at instantiation either from attachMovie code or on the components parameters panel.For example a properties in the style sheet selectors may be

.testSelector{

backgroundColor:)xff0ff;
openDirection:up;
openCloseTweenEasing:Bounce;
openCloseTweenSeconds:1;
scrollBarVisiblity:always;

}

Thus the open direction is up, it uses a bounce easing for one second. I do like bounce. And the scroll bar is visible even when there are not enough items to merit it.
When the component is used in a movie, the selector as well the other properties can be set via the attachMovie init object property or in the component parameters panel.
In the component we might have these as initialization parameters for example:

[Inspectable(name=”style selector (ex:myStyleSelector)”)]
public var _styleSelector:String;
private var __styleSelector:String;

[Inspectable(name=”open position” enumeration=”Top,Left,Right,Bottom”, defaultValue=”Bottom”)]
public var _openPosition:String = “Bottom” ;
private var __openPosition:String ;

[Inspectable(name=”Open close animation easing”, enumeration = “Strong, Bounce, Elastic, Regular, Back, None”)]
public var _openCloseTweenEasing:String = “Regular”;
private var __openCloseTweenEasing:String;

In the constructor I copy the initialization properties to a private variable to prevent access after initialization. Thus they are write once unless they are exposed via a method.

The component then will choose the selector properties as an override to those in code or in the components properties panel. For example in the constructor or in an initialization function.

Also in the constructor on in an initialization method at style object is obtained from the framework loaded stylesheet and the properties are checked for overrides as follows:

__styleSheet = _global.styleManager.getStyleSheet();
__style = __styleSheet.getStyle(“.” + __styleSelector);
if (__style.openCloseTweenEasing != undefined)
{
__openCloseTweenEasing = __style.openCloseTweenEasing;
}
This gives a level of component customization in the system that does not require touching code. Generally users do not change style sheets, so a technician without programming or Flash skills may be required. However via content server interfaces users can get at style values in a code controlled environment. The content servers can generate style sheets.

At least with AS 2 and Flash 8 we sure do have a number of ways to initialize a component: attachMovie init parameter, Flash components parameters panels and  dynamically from data sources including style sheets. Still we have traditional methods such as passing them as a constructor argument list or creating a constructor argument class.

Categories
Articles

Local SWF Launch and Actionscript 9 UrlRequest and Flex Sdk 2 mxmlc

I was recently trying the URLRequest class in Actionscript 9 and hit this runtime error:

SecurityError: Error #2148: SWF file file:///C|/Documents%20and%20Settings/Lon/My%20Documents/Flash/Flash9/mxmlc/Loader/LoaderEx01.swf cannot access local resource file:///C|/Documents%20and%20Settings/Lon/My%20Documents/Flash/Flash9/mxmlc/Loader/PablumPicasso.jpg. Only local-with-filesystem and trusted local SWF files may access local resources.
at flash.display::Loader/get content()
at LoaderEx01/::imgLoaded()

The code example is was trying is:

package {
import flash.display.*;
import flash.net.URLRequest;
import flash.events.Event;
import flash.system.Security;
import flash.text.TextField;
public class LoaderEx01 extends Sprite {

//private var context:LoaderContext = new LoaderContext();
private var container:Sprite = new Sprite();
private var pictLdr:Loader = new Loader();
public function LoaderEx01()
{

var sandBoxType:String = String(Security.sandboxType);
var display_txt:TextField = new TextField();
display_txt.text = sandBoxType;
addChild(display_txt);
addChild(container);
var pictURL:String = "PablumPicasso.jpg"
var pictURLReq:URLRequest = new URLRequest(pictURL);
// To load swf locally and use Flex SDK 2binmxmlc add -use-network=false
// argument. The Flash 9 Alpha will allow swf to load locally and load image.
pictLdr.load(pictURLReq);
pictLdr.contentLoaderInfo.addEventListener(Event.COMPLETE, imgLoaded);
}
private function imgLoaded(e:Event):void {
addChild(pictLdr.content);

}
}
}

I was using the Flex SDK 2 mxmlc compiler to create the swf file. Now it compiled perfectly. When I went to launch the swf from the local file server I got the security error message. However if I tried this in the Alpha version of the Flash 9 IDE it worked fine.

After a bit of research I found the option you need to set for mxmlc. It is -use-network=false. Once I added this switch to the command line the resulting swf could be loaded locally. I am using a Windows (DOS) batch file and so the resulting file appears as follows with the new switch:

"C:Program FilesAdobeFlex Builder 2Flex SDK 2binmxmlc" "-use-network=false" "C:Documents and SettingsLonMy DocumentsFlashFlash9mxmlcLoaderLoaderEx01.as"
Categories
Articles

Flash Player 9 Supports Full Screen Mode

This version of the Flash player supports Vista. It also supports full screen mode inside of web players. A short tutorial on full screen mode can be found at

Exploring full-screen mode in Flash Player 9

In addition to the above there are a number of bug fixes. More information at the following link:

Adobe Flash Player 9 Release Notes

Categories
Education Projects

Professor and Internet Media Curriculum Designer Raritan Valley Community College Computer Information Sciences 1988 to present

2007 -ICE  – Interactive Communications and Entertainment – Program

Lon provided advice and course development for the ICE program. This was a revamp of the old Multimedia Degree to encompass the changes in the industry.

1989 Web Developer Certification Program Designer

Lon participated with Dr. Ruth Malstrom, Chair for the Computer Department, to create one of the nation´s first Web Developers Certificate. The Web Developer Certificate is still granted today. Lon was on the receiving list of an internal email from then MIS Director Roger Doty. The email came from the academic director suggesting a virtual reality course at RVCC. Lon buzzed back accidentally to the entire mail list instead of just Roger and caught Ruth´s attention. Lon was invited in and within days had a curriculum in place for the next semester. Lon went on to teach Designing the New Media, the capstone course in the program. The Web Developer Certiciate became one of the most popular and highest enrollment programs in the Computer department.

1989 Multimedia Associate Degree

Lon also was asked by Dr. Malstrom to energize the new Multimedia Communications Degree. The program was languishing due to a lack of available reliable instructors and computer lab infrastructure. Lon took the two advanced courses for the degree and developed them to use the common technology in the industry and continued to provide input to RVCC to keep the technology up-to-date. As a result, many Multimedia Communications Degree graduates from RVCC experience with technology currently applied in the industry such as Director and Flash. To his credit, Lon offered temporary employment to students in the program to apply what they learned in real business appliations. Every student who participated with these projects obtained full time employment in their field on or before graduation.

Internet Media Adjunct Associate Professor

Lon continues as an Adjunct Associate Professor.

RVCC Web Site