Posts filed under 'actionscript'
So for a couple of weeks, I’ve been messing around w/ building a simple using Facebook. I decided to use the new ActionScript 3 API created by Adobe and Facebook. I wanted to do a little tutorial because some of this information is hard to understand since most of the API has definitions like, ” “.
In this tutorial I will show you how to login to Facebook, retrieve your friends list and populate a TileList with their pictures. Ok, let’s get started.
Step 1: Get an account (If you don’t have a Facebook account, that would be wierd. People in nursing homes have them).
Step 2: Create a developer App (link to directions by Adobe)
Step 3: Set up a Flex Project (link again to Adobe. Stop on step 7)
Step 4: in Design view drop in two Buttons, a Text, ComboBox and TileList components.
Step 5: enter the text into the labels of the buttons as they are in the picture below.

Then the TileList
Step 6: Now to make changes to the TileList we need click on the TileList and look at Flex Properties in the Flex Development View. In the Flex Properties set Column Count to 4 (ignore the row count).

Ok now we have the visuals let’s get to my favorite, coding.
Step 7: We are going to make ids for all componets so we can reference them in the code. The first Button name “loginbutton”, the label name “title”, the combobox name “sortBox”. See below to check your code.
<mx:Button id="loginbutton"
label="Click after you log into Facebook"
x="10" y="10"/>
<mx:Label id="title"
text="Hello you" x="10" y="40"/>
<mx:Button label="get Friends"
x="10" y="66"/>
<mx:ComboBox id="sortBox" x="10" y="96"/>
<mx:TileList id="friendsList" columnCount="4" width="400" height="400"
x="10" y="126">
</mx:TileList>
Step 8: we are going to put in all of the imports and variables.
<mx:Script>
<![CDATA[
]]>
</mx:Script>
Wrap this in side of the Script block.
import com.facebook.commands.notifications.SendEmail;
import com.facebook.commands.notifications.SendNotification;
import mx.utils.StringUtil;
import com.facebook.data.FacebookErrorCodes;
import mx.controls.Alert;
import mx.events.ListEvent;
import mx.events.ItemClickEvent;
import mx.collections.Sort;
import mx.collections.SortField;
import com.facebook.data.users.FacebookUserCollection;
import mx.collections.ArrayCollection;
import mx.controls.List;
import com.facebook.data.friends.GetFriendsData;
import com.facebook.commands.friends.GetFriends;
import com.facebook.data.friends.FriendsData;
import com.facebook.data.friends.FriendsCollection;
import com.facebook.data.users.GetInfoData;
import com.facebook.data.users.FacebookUser;
import com.facebook.events.FacebookEvent;
import com.facebook.Facebook;
import com.facebook.utils.FacebookSessionUtil
import com.facebook.net.FacebookCall;
import com.facebook.commands.users.GetInfo;
import com.facebook.data.users.GetInfoFieldValues;
import com.facebook.data.users.FriendsGetData;
[Bindable]
private var _friendsCollection:ArrayCollection;
private var fbook:Facebook;
private var session:FacebookSessionUtil;
private var user:FacebookUser;
private var sortTypes:Object;
private var answerPerson:String;
private var answer:String;
private var alert:Alert;
private var _apiKey:String = "{YOUR APIKEY}";
private var _secret:String = "{YOUR SECRET CODE}";
private var _friendSearched:String;
private var quizFriendsCollection:ArrayCollection = new ArrayCollection();
[Bindable]
public var sorts:ArrayCollection = new ArrayCollection([{label: "A-Z", data: "last_name"}, {label: "Z-A", data: "last_name"}]);
Step 9: We are going to create an init function to be called on applicationComplete. THis will go out, log you in and create a session.
private function init():void
{
fbook=new Facebook();
session=new FacebookSessionUtil(_apiKey, _secret, stage.loaderInfo);
fbook=session.facebook;
<div><code>session.login();
session.addEventListener(FacebookEvent.CONNECT, onConnect);
}</code></div>
Don’t forget to add an applicationComplete to your Application Tag.
Step 10: we are going to create the response to us connecting to Facebook. It will return our id which we will make another call to get all of our info for our account.
private function onConfirmLogin():void
{
this.removeChild(loginbutton);
session.validateLogin();
}
//also change this button
<mx:Button id="loginbutton"
label="Click after you log into Facebook"
click="onConfirmLogin()" x="10" y="10"/>
private function onConnect(e:FacebookEvent):void
{
var call:FacebookCall=fbook.post(new GetInfo([fbook.uid], [GetInfoFieldValues.ALL_VALUES]));
call.addEventListener(FacebookEvent.COMPLETE, onGetInfo);
}
This should only return one result. The title text we named will display the account first and last name
private function onGetInfo(e:FacebookEvent):void
{
for (var i:int=0; i < (e.data as GetInfoData).userCollection.length; i++)
{
user=(e.data as GetInfoData).userCollection.getItemAt(i) as FacebookUser;
title.text="Hello " + user.first_name + " " + user.last_name;
}
}
Step 10:Let’s get some friends.
//This gives just the ids of your friends
private function getFriends():void
{
var call:FacebookCall=fbook.post(new GetFriends());
call.addEventListener(FacebookEvent.COMPLETE, onGetFriends);
}
private function onGetFriends(evt:FacebookEvent):void
{
if(evt.error)
{
alert = Alert.show(evt.error.errorMsg, "Error: " + evt.error.errorCode);
return;
}
var friends:FacebookUserCollection=(evt.data as GetFriendsData).friends;
var uids:Array=[];
var userFriend:FacebookUser;
for (var i:int=0; i < friends.source.length; i++)
{
userFriend=friends.getItemAt(i) as FacebookUser;
uids.push(userFriend.uid);
}
//get all the info of a friends
var call:FacebookCall=fbook.post(new GetInfo(uids, [GetInfoFieldValues.ALL_VALUES]));
call.addEventListener(FacebookEvent.COMPLETE, onHandleFriends);
}
Don’t forget to add the getFriends function to the click handler of the Button labeled “get Friends”
private function onHandleFriends(e:FacebookEvent):void
{
if(e.error)
{
var alert:Alert = Alert.show(e.error.errorMsg, "Error: " +e.error.errorCode);
return;
}
var data:GetInfoData=e.data as GetInfoData;
var friendCollection:FacebookUserCollection=data.userCollection as FacebookUserCollection;
createList(friendCollection);
}
private function createList(data:FacebookUserCollection):void
{
_friendsCollection=new ArrayCollection();
for (var i:int=0; i < data.length; i++)
{
_friendsCollection.addItem(data.getItemAt(i));
}
friendsList.dataProvider=_friendsCollection;
}
<mx:Button label="get Friends"
click="getFriends()" x="10" y="66"/>t;
Also we need to put in an itemRender to the TileList (for more info on itemRenders)
//This will allow you to show each friend's picture and when you hover over it will tell you there name.
<mx:TileList id="friendsList" columnCount="4" rowCount="1" width="400" height="400"
labelField="pic_big" allowMultipleSelection="false" x="10" y="126">
<mx:itemRenderer>
<mx:Component>
<mx:Image source="{data.pic_big}"
toolTip="{data.name}"/>
</mx:Component>
</mx:itemRenderer>
Step 11: (Almost there) add functionality to the comboBox.
private function closeHandler(event:Event):void
{
sort();
}
private function sort():void
{
var dataSortField:SortField=new SortField();
dataSortField.name= sortBox.selectedItem.data as String;
if(sortBox.selectedLabel == "Z-A")
{
dataSortField.descending = false;
}
else
{
dataSortField.descending = true;
}
var numericDataSort:Sort = new Sort();
numericDataSort.fields = [dataSortField];
_friendsCollection.sort = numericDataSort;
_friendsCollection.refresh();
}
//don’t forget to add the event handler for the comboBox
<mx:ComboBox dataProvider="{sorts}" id="sortBox" close="closeHandler(event)" x="10" y="96"/>
And we are done. Here is the code in it’s entirety.
< ![CDATA[
import com.facebook.commands.notifications.SendEmail;
import com.facebook.commands.notifications.SendNotification;
import mx.utils.StringUtil;
import com.facebook.data.FacebookErrorCodes;
import mx.controls.Alert;
import mx.events.ListEvent;
import mx.events.ItemClickEvent;
import mx.collections.Sort;
import mx.collections.SortField;
import com.facebook.data.users.FacebookUserCollection;
import mx.collections.ArrayCollection;
import mx.controls.List;
import com.facebook.data.friends.GetFriendsData;
import com.facebook.commands.friends.GetFriends;
import com.facebook.data.friends.FriendsData;
import com.facebook.data.friends.FriendsCollection;
import com.facebook.data.users.GetInfoData;
import com.facebook.data.users.FacebookUser;
import com.facebook.events.FacebookEvent;
import com.facebook.Facebook;
import com.facebook.utils.FacebookSessionUtil
import com.facebook.net.FacebookCall;
import com.facebook.commands.users.GetInfo;
import com.facebook.data.users.GetInfoFieldValues;
import com.facebook.data.users.FriendsGetData;
[Bindable]
private var _friendsCollection:ArrayCollection;
private var fbook:Facebook;
private var session:FacebookSessionUtil;
private var user:FacebookUser;
private var sortTypes:Object;
private var infoType:String = "activities";
private var answerPerson:String;
private var answer:String;
private var alert:Alert;
private var _apiKey:String = "{YOUR APIKEY}";
private var _secret:String = "{YOUR SECRET CODE}";
private var _friendSearched:String;
private var quizFriendsCollection:ArrayCollection = new ArrayCollection();
[Bindable]
public var sorts:ArrayCollection = new ArrayCollection([{label: "A-Z", data: "last_name"}, {label: "Z-A", data: "last_name"}]);
private function init():void
{
fbook=new Facebook();
session=new FacebookSessionUtil(_apiKey, _secret, stage.loaderInfo);
fbook=session.facebook;
session.login();
session.addEventListener(FacebookEvent.CONNECT, onConnect);
/*
sortTypes["ASC"] = {label:"A-Z", type:"last_name"};
sortTypes["DESC"] = {label:"Z-A", type:"last_name"}; */
}
private function onConfirmLogin():void
{
this.removeChild(loginbutton);
session.validateLogin();
}
private function onConnect(e:FacebookEvent):void
{
var call:FacebookCall=fbook.post(new GetInfo([fbook.uid], [GetInfoFieldValues.ALL_VALUES]));
call.addEventListener(FacebookEvent.COMPLETE, onGetInfo);
}
private function getFriends():void
{
var call:FacebookCall=fbook.post(new GetFriends());
call.addEventListener(FacebookEvent.COMPLETE, onGetFriends);
}
private function onGetFriends(evt:FacebookEvent):void
{
if(evt.error)
{
var errorCode:String;
switch(evt.error.errorCode)
{
case FacebookErrorCodes.API_EC_BAD_IP:
errorCode = "Bad IP";
break;
case FacebookErrorCodes.API_EC_DEPRECATED:
errorCode = "API deprecated";
break;
case FacebookErrorCodes.API_EC_HOST_API:
errorCode = "API"
break;
}
alert = Alert.show(evt.error.errorMsg, "Error: " + evt.error.errorCode);
return;
}
var friends:FacebookUserCollection=(evt.data as GetFriendsData).friends;
var uids:Array=[];
var userFriend:FacebookUser;
for (var i:int=0; i < friends.source.length; i++)
{
userFriend=friends.getItemAt(i) as FacebookUser;
uids.push(userFriend.uid);
}
var call:FacebookCall=fbook.post(new GetInfo(uids, [GetInfoFieldValues.ALL_VALUES]));
call.addEventListener(FacebookEvent.COMPLETE, onHandleFriends);
//createList(friends);
}
private function onHandleFriends(e:FacebookEvent):void
{
if(e.error)
{
var alert:Alert = Alert.show(e.error.errorMsg, "Error: " +e.error.errorCode);
return;
}
var data:GetInfoData=e.data as GetInfoData;
var friendCollection:FacebookUserCollection=data.userCollection as FacebookUserCollection;
createList(friendCollection);
quizMe();
}
private function onGetInfo(e:FacebookEvent):void
{
for (var i:int=0; i < (e.data as GetInfoData).userCollection.length; i++)
{
user=(e.data as GetInfoData).userCollection.getItemAt(i) as FacebookUser;
title.text="Hello " + user.first_name + " " + user.last_name;
}
}
private function createList(data:FacebookUserCollection):void
{
_friendsCollection=new ArrayCollection();
for (var i:int=0; i < data.length; i++)
{
_friendsCollection.addItem(data.getItemAt(i));
}
friendsList.dataProvider=_friendsCollection;
}
private function closeHandler(event:Event):void
{
sort();
}
private function sort():void
{
var dataSortField:SortField=new SortField();
dataSortField.name= sortBox.selectedItem.data as String;
if(sortBox.selectedLabel == "Z-A")
{
dataSortField.descending = false;
}
else
{
dataSortField.descending = true;
}
var numericDataSort:Sort = new Sort();
numericDataSort.fields = [dataSortField];
_friendsCollection.sort = numericDataSort;
_friendsCollection.refresh();
}
]]>
The next tutorial will be searching for a specific friend and sending them a message.
Here are some links for extra reading.
Item Renderers
Event Handlers
Heck, just read everything in here to get an understanding of Flex if you don’t have one.
June 24th, 2009
Merry Christmas, I got you guys present.
I was looking for a need to make an AIR app, though this isn’t the best one, I turned my converter class into one. Introducing Johnny V.
December 25th, 2008
This past week I worked on a porting exercise. I have always wanted to find out how you convert Roman Numerals to Arabic numerals and vice versa. So I starting searching and found a bunch of bloated code for converting these numbers then I stumbled on this page.
So in a few hours of screwing around w/ the loops (typing this correctly took a bit) I got it ported. Porting is fun cause all you have to do is translate.
Here is the zip flie and Here is the class.
package com.joshspoon.etc.utils
{
public class NumberUtils
{
public function NumberUtils(){}
public static function romanize(num:int):String {
var numerals:Array = ["M", "CM", "D", "CD", "C", "XC", "L", "XL", "X",
"IX", "V", "IV", "I"];
var numbers:Array = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1];
var lookup:Object = {M:1000,CM:900,D:500,CD:400,C:100,XC:90,L:50,XL:40,X:10,IX:9,V:5,IV:4,I:1}
var roman:String = "";
var i:int;
for( i = 0; i < numbers.length - 1; i++)
{
while(num >= numbers[i])
{
roman += numerals[i];
num -= numbers[i];
}
}
return roman;
}
public static function deromanize( roman:String ):int {
var numerals:Array = ["I", "V", "X", "L", "C", "D", "M"];
var numbers:Array = [1, 5, 10, 50, 100, 500, 1000];
var roman:String = roman.toUpperCase();
var arabic:int = 0;
var i:int = roman.length;
var compare1:int;
var compare2:int;
while (i--) {
var letter:String;
var listLetter:String;
for (var j:int = 0; j < = numerals.length - 1; j++)
{
letter = roman.charAt(i);
listLetter = numerals[j];
if(listLetter == letter)
{
compare1 = numbers[j];
}
}
for (j = 0; j <= numerals.length - 1; j++)
{
letter = roman.charAt(i + 1);
listLetter = numerals[j];
if(listLetter == letter)
{
compare2 = numbers[j];
}
}
if (compare1 < compare2 )
arabic -= compare1;
else
arabic += compare1;
}
return arabic;
}
}
}
December 17th, 2008
So after 13 year of off and on drumming I have learned a thing or two about music. Not much about tuning a guitar. Thanks to a class that I got a D in, Musical Acoustics, I know every note produces a frequency and a wavelength. With that you can now you Flash to produce a frequency and that is what I did, the six notes from left to right are the notes of a regularly tuned guitar.
Since I lost my Musical Acoustics book from UNT I had to look it up to find the Frequency of All Notes
and that pick the ones I wanted starting w/ E4.
So if you don’t have a guitar tuner…here you go.
View Code:
[as]
package
{
import flash.display.*;
import flash.events.*;
import flash.media.Sound;
import flash.text.TextField;
public class GuitarTuner extends Sprite
{
private var _key1:Sprite;
private var _key2:Sprite;
private var _key3:Sprite;
private var _key4:Sprite;
private var _key5:Sprite;
private var _key6:Sprite;
private var _sound:Sound;
private var _note:Number = 0;
private var noise:Number = 0;
private var text:TextField = new TextField();
//Constants
private static const E4:String = “E4″;
private static const A4:String = “A4″;
private static const D4:String = “D5″;
private static const G5:String = “G5″;
private static const B5:String = “B5″;
private static const E6:String = “E6″;
public function GuitarTuner()
{
stage.scaleMode = StageScaleMode.NO_SCALE;
stage.align = StageAlign.TOP_LEFT;
_key1 = makeKey();
_key1.name = GuitarTuner.E4;
_key1.addEventListener(MouseEvent.CLICK, onClick, false, 0, true);
addChild(_key1);
_key2 = makeKey();
_key2.name = GuitarTuner.A4;
_key2.addEventListener(MouseEvent.CLICK, onClick, false, 0, true);
addChild(_key2);
_key2.x = spaceFromSibling(_key1, _key2);
_key3 = makeKey();
_key3.name = GuitarTuner.D4;
_key3.addEventListener(MouseEvent.CLICK, onClick, false, 0, true);
addChild(_key3);
_key3.x = spaceFromSibling(_key2, _key3);
_key4 = makeKey();
_key4.name = GuitarTuner.G5;
_key4.addEventListener(MouseEvent.CLICK, onClick, false, 0, true);
addChild(_key4);
_key4.x = spaceFromSibling(_key3, _key4);
_key5 = makeKey();
_key5.name = GuitarTuner.B5;
_key5.addEventListener(MouseEvent.CLICK, onClick, false, 0, true);
addChild(_key5);
_key5.x = spaceFromSibling(_key4, _key5);
_key6 = makeKey();
_key6.name = GuitarTuner.E6;
_key6.addEventListener(MouseEvent.CLICK, onClick, false, 0, true);
addChild(_key6);
_key6.x = spaceFromSibling(_key5, _key6);
addChild(text);
text.x = 300;
}
private function onCallback(e:SamplesCallbackEvent):void
{
for(var i:uint=0; i<512; i++)
{
noise += _note/ 44100;
var sample:Number = noise * Math.PI * 2;
_sound.samplesCallbackData.writeFloat(Math.sin(sample));
_sound.samplesCallbackData.writeFloat(Math.sin(sample));
}
}
private function onClick(evt:MouseEvent):void
{
_sound = new Sound();
_sound.addEventListener(Event.SAMPLES_CALLBACK, onCallback);
_sound.play();
var sprite:Sprite = Sprite(evt.currentTarget);
switch(sprite.name)
{
case “midC”:
_note = 277.18;
break;
case GuitarTuner.E4:
_note = 329.63;
break;
case GuitarTuner.A4:
_note = 440.00;
break;
case GuitarTuner.D4:
_note = 587.33;
break;
case GuitarTuner.G5:
_note = 783.99;
break;
case GuitarTuner.B5:
_note = 987.77;
break;
case GuitarTuner.E6:
_note = 1318.51;
break;
}
text.text = String(_note);
}
private function makeKey():Sprite
{
var key:Sprite = new Sprite()
key.graphics.lineStyle(1, 0×000000);
key.graphics.beginFill(0xFFFFFF, 1);
key.graphics.drawRect(0, 0, 20, 50);
key.graphics.endFill();
return key;
}
public function spaceFromSibling(sibling:DisplayObject, target:DisplayObject,
coordinate:String = “x”, distance:Number = 0):Number
{
var value:int;
switch(coordinate)
{
case “x”:
value = sibling.x + sibling.width + distance;
break;
case “y”:
value = sibling.y + sibling.height + distance;
break;
}
return Math.floor(value);
}
}
}[/as]
If this code doesn’t make sense check out Lee Brimelow’s tutorial on Dynamic Sound.
May 20th, 2008
I miss writing classes w/ 50 or so lines of code and here is one. This is a take off of Lee Brimelow’s Example of Dynamic Sound Generation. I’m using the BitmapData to create a tone.
[as]
package
{
import flash.display.*;
import flash.events.*;
import flash.media.*;
import flash.net.URLRequest;
import flash.system.Capabilities;
import flash.text.TextField;
public class DynamicSound extends Sprite
{
private var sound:Sound;
private var noise:Number = 0;
private var _loader:Loader;
private var _bm:Bitmap;
private var _verText:TextField;
public function DynamicSound():void
{
stage.align = StageAlign.TOP_LEFT;
stage.scaleMode = StageScaleMode.NO_SCALE;
_verText = new TextField();
_verText.text = Capabilities.playerType + ” (” + Capabilities.version + “)”;
_loader = new Loader();
_loader.contentLoaderInfo.addEventListener(Event.COMPLETE, onComplete, false, 0, true);
_loader.load(new URLRequest(”http://www.scarlet.nl/~ivo/photo_ASTRO3.JPEG”));
}
private function onComplete(evt:Event):void
{
_bm = Bitmap(_loader.content);
addChild(_bm);
addChild(_verText);
sound = new Sound();
sound.addEventListener(Event.SAMPLES_CALLBACK, onCallback);
sound.play();
}
private function onCallback(e:SamplesCallbackEvent):void
{
for(var i:uint=0; i<512; i++)
{
noise += _bm.bitmapData.getPixel(mouseX, mouseY)/ 44100;
var sample:Number = noise * Math.PI * 2;
sound.samplesCallbackData.writeFloat(Math.sin(sample));
sound.samplesCallbackData.writeFloat(Math.sin(sample));
}
}
}
}
[/as]
Quick and Dirty!
May 20th, 2008
As many of you know ASTRO is in Public beta.
Download browser plugin
Here are some links on how to compile:
Text instruction – by Mike Chanmbers
Video Instruction – by Lee Brimelow
Flash Magizine Article
A promising sound example:
flash produced sound example – by Keith Peters
Here is my “3D” example, quick and dirty:
[as]
package {
import flash.display.Loader;
import flash.display.MovieClip;
import flash.display.Sprite;
import flash.display.StageAlign;
import flash.display.StageScaleMode;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.geom.Vector3D;
import flash.net.URLRequest;
public class ASTRO extends Sprite
{
private var _loader:Loader;
private var mc:MovieClip;
public function ASTRO()
{
stage.align = StageAlign.TOP_LEFT;
stage.scaleMode = StageScaleMode.EXACT_FIT;
_loader = new Loader()
_loader.contentLoaderInfo.addEventListener(Event.COMPLETE, loadComplete, false, 0, true);
_loader.load(new URLRequest(”record.gif”));
}
private function loadComplete(evt:Event):void
{
mc = new MovieClip();
mc.rotationY = 0;
mc.rotationZ = 0;
stage.addEventListener(MouseEvent.MOUSE_MOVE, onMove, false, 0, true);
mc.opaqueBackground = true;
_loader.x = – (_loader.width * 0.5);
_loader.y = – (_loader.height * 0.5);
mc.addChild(_loader);
mc.x = (_loader.width * 0.5);
mc.y = (_loader.height * 0.5);
addChild(mc);
}
private function onMove(evt:MouseEvent):void
{
mc.rotationZ = stage.mouseY;
mc.rotationX = stage.mouseX
}
}
}
[/as]
Also here are some classes that I saw through code completion. I don’t really know what to do with them yet. Maybe someone else will and will let me know (I have too much work and GTAing to do
).
- flash.text.engine Package (over a dozen classes)
- __AS3__.vec.Vector (that is wierd)
- flash.display.GraphicsBitmapFill
- flash.display.GraphicsPathCommand
- flash.display.TriangleCulling (that sounds interesting)
- flash.geom.Vector3D
- flash.filters.ShaderFilter
Happy Coding!
May 16th, 2008

Alright, in this example, I am cutting each pixel in an image and piecing it back together again. Only this time I animating the pixel to a new location, piecing back the image at 200%. I think this can open a lot doors in what you can do with a bitmap.
Here is the Bitmap test 2 example
bitmaptest2.fla
Here is the code
[as]import flash.display.*;
import caurina.transitions.Tweener;
//holds all the pixels
var pixHolder:Sprite = new Sprite();
//linkage to img in library
var img:Img = new Img();
addChild(pixHolder);
//array that will hold info of each pixel
var pixels_array:Array = [];
//bitmapdata of the img
var bmd:BitmapData = new BitmapData(img.width, img.height, false);
//put the img bitmapdata in the new bitmapdata object
bmd.draw(img, new Matrix());
//I heard this helps performance
bmd.lock();
//loop thru each pixel
//i.e. i= 0; j = 0 then i=1; j = 0 then i = 2; j = 0 you get it right?
for (var i:int = 0; i < img.width; i++)
{
for (var j:int = 0; j < img.height; j++)
{
//create an obj to hold each pixels info
var coords:Object = {};
//in this example I decided to use a rect graphic instead of a single bitmap
//for fun
var pixSprite:Sprite = new Sprite();
//make a pixSprite for each pixel
pixSprite.graphics.beginFill(bmd.getPixel(i, j), 1);
pixSprite.graphics.drawRect(0, 0, 1, 1);
pixSprite.graphics.endFill();
// add an event listener to each pixel to animate
pixSprite.addEventListener(MouseEvent.MOUSE_OVER, updating, false, 0, true);
//put pixels in their right place
pixSprite.x = i;
pixSprite.y = j;
pixHolder.addChild(pixSprite);
}
}
bmd.unlock();
//you don’t need the data in memory any more
bmd.dispose();
function updating(evt:MouseEvent):void
{
//the moused over pixel removes listener, scales 200% and moves down to make a img at 200%
evt.currentTarget.removeEventListener(MouseEvent.MOUSE_OVER, updating);
trace(”over”);
Tweener.addTween(evt.currentTarget, {scaleX:2, scaleY:2, x: img.width + evt.currentTarget.x * 2, y: img.height + evt.currentTarget.y * 2, transition:”linear”, time:.5});
}
[/as]
April 23rd, 2008

So the last couple of weeks I have been jacking around w/ Bitmaps and BitmapData. I’ve always wanted to try it but never had the courage. Now that I have, I wish I’d have done it sooner.
In this first example I’m just copying each pixel throwing it to the wind and using Tweener to animate it to a spot. I don’t think Tweener is the best option course as you can see it runs slow. I’m also using Grant Skinner’s Memory Gauge to illustrate how slow it is. This is just a proof of concept anyway.
Here is the Bitmap and BitmapData src v1
Here is the code
[as]
// code written by Josh Weatherspoon of http://swfitgood.com
import flash.display.*;
import caurina.transitions.Tweener;
//holds all the “pixels”
var pixHolder:Sprite = new Sprite();
//image of me in the library thru linkage
var img:Img = new Img();
//pixHolder.opaqueBackground = true;
addChild(pixHolder);
//array that will hold info of each pixel
var coords_array:Array = [];
//bitmapdata of the img
var bmd:BitmapData = new BitmapData(img.width, img.height, false);
//put the img bitmapdata in the new bitmapdata object
bmd.draw(img, new Matrix());
//I heard this helps performance
bmd.lock();
//loop thru each pixel
//i.e. i= 0; j = 0 then i=1; j = 0 then i = 2; j = 0 you get it right?
for (var i:int = 0; i < img.width; i++)
{
for (var j:int = 0; j < img.height; j++)
{
//create an obj to hold each pixels info
var coords:Object = {};
//var pixData:BitmapData = new BitmapData(1, 1, false, bmd.getPixel(i, j));
//var pixBit:Bitmap = new Bitmap(pixData, PixelSnapping.ALWAYS, true);
//in this example I decided to use a circlular graphic instead of a single bitmap
//for fun
var pixSprite:Sprite = new Sprite();
//make a pixSprite for each pixel
pixSprite.graphics.beginFill(bmd.getPixel(i, j), 1);
pixSprite.graphics.drawCircle(0, 0, 1);
//set the pixel to a random location on the stage
pixSprite.x = Math.random() * stage.stageWidth;
pixSprite.y = Math.random() * stage.stageHeight;
//pixSprite.filters = [new BlurFilter(5, 5, 3)];
//pixSprite.addChild(pixBit);
pixHolder.addChild(pixSprite);
//gather info to access each pixel individually
coords.sprite = pixSprite;
coords.x = i;
coords.y = j;
coords_array.push(coords);
}
}
bmd.unlock();
// on mouse over start animating
stage.addEventListener(MouseEvent.MOUSE_OVER, updating, false, 0, true);
function updating(evt:MouseEvent):void
{
// loop thru each pixel and move it to the original location
stage.removeEventListener(MouseEvent.MOUSE_OVER, updating);
for(var k:int = 0; k < coords_array.length; k++)
{
Tweener.addTween(coords_array[k].sprite, {x:coords_array[k].x, scaleX:1, scaleY:1, delay: .3, y:coords_array[k].y, transition:”linear”, time:10});
}
}
[/as]
April 21st, 2008
So since PureMVC has updated twice and also I never talked about garbage collection of the app, I have refactored PurelyKuler to work with PureMVC 2.3. Thate are quite a few changes, some being:
- the framework is being ported to many languages like PHP, Ruby, Python, Coldfusion, C# and many others.
[as]import org.puremvc.as3.interfaces.IFacade;
import org.puremvc.as3.patterns.facade.Facade;[/as]
as oppose to
[as]import org.puremvc.interfaces.IFacade;
import org.puremvc.patterns.facade.Facade;[/as]
- there is a new way to notify observers:
[as]facade.sendNotification(PurelyKulerConstants.STARTUP, app);[/as]
as oppose to
[as]facade.notifyObserver(new Notification(PurelyKulerConstants.STARTUP, app))[/as]
- also the Mediators are can be named from outside the class, so you can have many instances of the class and remove specific instances and not all.public function PurelyKulerMediator(mediatorName:String = null, viewComponent:Object=null){
_tf = new TextField();
super(NAME, viewComponent);// the colorContainer
}
Those are just a few.
Alright back to PurelyKuler.
So if you look at the last example I did, it was just about getting data from a Proxy to a Mediator.
This time I’m adding garbage collection and using the new, to ver2.3, onRemove method in IMediator to delete all the ui and variables. Like this.
[as]override public function onRemove():void
{
vo.removeEventListener(MouseEvent.CLICK, changeColor);
vo.graphics.clear();
vo.parent.removeChild(_tf);
_tf = null;
_ka = null;
cc = undefined;
trace(”_tf: ” + _tf);
}[/as]
Alright enough typing, here it is. Click on a mediator name.
Source | PurelyKuler2
March 30th, 2008
I was messing around last night with AIR and I stumbled apon this:
- start an AIR app in flash cs3
- add a list component
- name it dir_list
- drop the code below in the actions panel
- And Viola!
- PS – PC people, I put a test to see if My Documents in in that Directory.

[as]
import flash.filesystem.*;
var userDirFiles:Array = File.userDirectory.getDirectoryListing();
for (var i:uint = 0; i < userDirFiles.length; i++) {
if (userDirFiles[i].isDirectory) {
//this.display_txt.text = String(userDirFiles[i].nativePath);
dir_list.addItem({label:userDirFiles[i].nativePath })
var tmpString:String = userDirFiles[i].nativePath;
if(tmpString.search(/My Documents/) != -1)
{
dir_list.addItem({label:”working”});
break;
}
}
} [/as]
March 1st, 2008
Previous Posts