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>