Flex – Image Navigator Example

Image Navigator

Here is a small example of creating an Image Navigator for big images in Flex.

The big image is loaded in Canvas and an Image navigator will have a small prototype of this image. A small rectangle in Navigator can be used to scroll image. Click and drag small rectangle to scroll image. This rectangle corresponds to visible area of image in Canvas.

This example demonstrates usage of:

Image control

SWFLoader

Creating Sprite at runtime

Assigning Drag and drop functionality to sprite

Copying image using BitmapData

Controlling Scrollbar using ActionScript

Handling mouse events in Flex

Example: http://tushar.x10hosting.com/ImageNavigator/

Source: http://tushar.x10hosting.com/ImageNavigator/src/Navigator.mxml

Posted in ActionScript3, AS3, components, Flex | Tagged , , | 28 Comments

ActionScript 3: Using URLLoader to send and load server variables

Here is a very simple example of two way communication with database using Flex and PHP. In this example, we are sending username and password to the PHP file from Flex. PHP file then validates the input and returns the appropriate response.

This example also demonstrates the simple PHP script to establish a database (MySQL) connection and validate username and password against the table in database.

In AS3, we can use flash.net.URLLoader, URLRequest and URLVariables class to send and load data. First create a class named SendAndLoadExample.

Class SendAndLoadExample:

package {

import flash.events.*
import flash.net.*;

public class SendAndLoadExample {

public function SendAndLoadExample() {}
public function sendData(url:String, _vars:URLVariables):void {
var request:URLRequest = new URLRequest(url);
var loader:URLLoader = new URLLoader();
loader.dataFormat = URLLoaderDataFormat.VARIABLES;
request.data = _vars;
request.method = URLRequestMethod.POST;
loader.addEventListener(Event.COMPLETE, handleComplete);
loader.addEventListener(IOErrorEvent.IO_ERROR, onIOError);
loader.load(request);
}
private function handleComplete(event:Event):void {
var loader:URLLoader = URLLoader(event.target);
trace("Par: " + loader.data.par);
trace("Message: " + loader.data.msg);
}
private function onIOError(event:IOErrorEvent):void {
trace("Error loading URL.");
}
}
}

Now, create an object of SendAndLoadExample class in Flex.

SendAndLoadExample.mxml

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" 
		layout="vertical">
<mx:Script>
<!&#91;CDATA&#91;
import flash.net.URLVariables;
private var mySendAndLoadExample:SendAndLoadExample;
mySendAndLoadExample = new SendAndLoadExample();
private function sendAndLoad():void {
var url:String = "http://&#91;your server&#93;/login.php";
var variables:URLVariables = new URLVariables();
variables.UserName = "tushar";
variables.Password = "my_password";
mySendAndLoadExample.sendData(url, variables);
}
&#93;&#93;>
</mx:Script>
<mx:Button label="Fetch data" click="sendAndLoad()"/>
</mx:Application> 

PHP Script for login check: login.php

<?   
$clientUserName=$_POST&#91;'UserName'&#93;;   
$clientPassword=$_POST&#91;'Password'&#93;;   
//////////////////////////////////////   
// Host name   
$host="&#91;your server&#93;"; 
// Mysql username
$username="&#91;MySql database username&#93;"; 
// Mysql password     
$password="&#91;MySql database password&#93;"; 
// Database name    
$db_name="&#91;MySql database name&#93;"; 
// Table name  
$tbl_name="&#91;MySql table name having usernames and passwords&#93;";  
function makeConnection() {   
// Connect to server and select databse.   
mysql_connect("$GLOBALS&#91;host&#93;", "$GLOBALS&#91;username&#93;", 
		"$GLOBALS&#91;password&#93;")or die("cannot connect");   
mysql_select_db("$GLOBALS&#91;db_name&#93;")or die("cannot select DB");   
}   
function fireQuery($query) {   
$result=mysql_query($query);   
return $result;   
}   
function printOutput($code, $msg){   
print "par=$code&msg=$msg";   
}   
//////////////////////////////////////   
function checkUserID($id, $password) {   
$sql="SELECT * FROM $GLOBALS&#91;tbl_name&#93; WHERE 
		userName='$id' and password='$password'";   
$result=fireQuery($sql);   
$count=mysql_num_rows($result);   
if($count==1){   
return true;   
}   
return false;   
}   
function init(){   
if(isSet($GLOBALS&#91;"clientUserName"&#93;) 
	&& isSet($GLOBALS&#91;"clientPassword"&#93;)){   
makeConnection();   
if(checkUserID($GLOBALS&#91;"clientUserName"&#93;
	, $GLOBALS&#91;"clientPassword"&#93;)){   
printOutput("1", "Login successful.");   
} else {   
printOutput("0", "Failed to login $GLOBALS&#91;clientUserName&#93;.");   
}   
} else {   
printOutput("0", "Required parameters missing.");   
}   
}   
init();   
?> 

However, you can also use HTTPService to send and load data in Flex. Nitin has posted a simple example of using HTTPService in flex. Check it out here.

Posted in ActionScript3, AS3, Database, Flash CS3, Flex, MySql, PHP | 70 Comments

ActionScript 3: Creating custom event handlers using EventDispatcher

Creating custom event handlers in ActionScript 3 is pretty much simple. Here is a simple example which loads an image and fires a custom event named “onImageLoad” as soon as image is loaded.

Class imageLoader.as

package {
import flash.events.*;
import flash.net.URLRequest;
import flash.display.Loader;
import flash.display.Sprite;
public class imageLoader extends EventDispatcher {
private var _mc:Sprite;
private var url:String;
private var loader:Loader;
public function imageLoader(_mc:Sprite, url:String) {
this._mc = _mc;
this.url = url;
loadImg();
_mc.addChild(loader);
}
private function loadImg():void {
loader = new Loader();
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, onComplete);
loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, onIOError);
var request:URLRequest = new URLRequest(url);
loader.load(request);
}
private function onComplete(event:Event):void {
dispatchEvent(new Event("onImageLoad"));
}
private function onIOError(event:IOErrorEvent):void {
trace("IO Error.");
}
}
}

Now in Flash, create a a object of imageLoader class and add a event listener (for our custom event “onImageLoad”).

var myImageLoader:imageLoader = new imageLoader(this, "images/someImg.jpg");
myImageLoader.addEventListener("onImageLoad", callbackHandler);
function callbackHandler(event:Event) {
trace("Image Loading Complete!");
}

Now test the file. Be sure to have someImg.jpg in images folder. Once image is loaded, you should be able to see “”Image Loading Complete!” message in output window.

Posted in ActionScript3, AS3, Flash, Flash CS3 | 35 Comments

ActionScript 3: Serializing Classes using registerClassAlias

In previous article “Component and SharedObject Example” we’ve seen how to store simple variables in Local Shared Object. But, what if you want to store a custom class objects in Shared Object?

You can use flash.net. registerClassAlias() to do so. This method is similar to old Object.registerClass() (Removed in AS3).

Shared Objects are stored in AMF (Action Message Format) format. When you try to save class object in Shared Object, it will be stored as normal object. It will not have any reference to the class. Thus to save the information about the class, one has to use registerClassAlias class. This is also called as Serializing Classes.

Apart from SharedObject, this class can be used for LocalConnection, ByteArray , NetConnection and NetStream.

Here is a simple example of using registerClassAlias. In this example, object of Person class is stored in Shared Object. This example also demonstrates use of AS3 components (Label, ComboBox, Button, InputText).

AS3 Serializing example image

Below is the code:

Class Person:

package {
public class Person {
private var _name:String;
private var _age:uint;
private var _gender:String;
public function Person() {
this._name = "";
this._age = undefined;
this._gender = "";
}
public function get name():String {
return this._name;
}
public function set name(name:String):void {
this._name = name;
}
public function get age():uint {
return this._age;
}
public function set age(age:uint):void {
this._age = age;
}
public function get gender():String {
return this._gender;
}
public function set gender(gender:String):void {
this._gender = gender;
}
public function getPerson():String {
return "Name: " + this._name + " Age: " + this._age + " Gender: " + this._gender;
}
}
}

Class soExample:

package {
import fl.controls.Button;
import fl.controls.Label;
import fl.controls.TextInput;
import fl.controls.NumericStepper;
import fl.controls.ComboBox;
import fl.data.DataProvider;
import flash.display.Sprite;
import flash.events.MouseEvent;
import flash.net.SharedObject;
import flash.net.registerClassAlias;
public class soExample extends Sprite {
private var getData_btn:Button;
private var setData_btn:Button;
private var delData_btn:Button;
private var titleLbl:Label;
private var statLbl:Label;
private var nameLbl:Label;
private var ageLbl:Label;
private var genderLbl:Label;
private var name_txt:TextInput;
private var ageNS:NumericStepper;
private var genderCB:ComboBox;
private var _mc:Sprite;
private var mySO:SharedObject;
private var tushar:Person;
public function soExample(_mc:Sprite) {
registerClassAlias(”PersonAlias”, Person);
this._mc = _mc;
updateUI();
updateDisplay();
getSO();
}
private function updateUI():void {
getData_btn = createButton("Get Shared Object", 150, 10, 160, "get_btn");
setData_btn = createButton("Store Shared Object", 150, 10, 190, "set_btn");
delData_btn = createButton("Delete Shared Object", 150, 10, 220, "del_btn");
titleLbl = createLabel("<b>AS3 - Shared Object Example</b>", 200, 10, 10);
statLbl = createLabel("", 400, 10, 250);
nameLbl = createLabel("Name: ", 100, 10, 50);
ageLbl = createLabel("Age: ", 100, 10, 80);
genderLbl = createLabel("Gender: ", 100, 10, 110);
name_txt = createTextInput(200, 60, 50);
ageNS = createNumericStepper(25, 50, 22, 60, 80);
genderCB = createComboBox(100, 22, 60, 110, new DataProvider(["Male", "Female"]));
}
private function updateDisplay():void {
_mc.addChild(titleLbl);
_mc.addChild(nameLbl);
_mc.addChild(ageLbl);
_mc.addChild(genderLbl);
_mc.addChild(statLbl);
_mc.addChild(getData_btn);
_mc.addChild(setData_btn);
_mc.addChild(delData_btn);
_mc.addChild(ageNS);
_mc.addChild(name_txt);
_mc.addChild(genderCB);
}
private function createButton(lbl:String, w:uint, x:uint, y:uint, nme:String):Button {
var BTN:Button = new Button();
BTN.label = lbl;
BTN.width = w;
BTN.move(x, y);
BTN.name = nme;
BTN.addEventListener(MouseEvent.CLICK, clickHandler);
return BTN;
}
private function createLabel(lbl:String, w:uint, x:uint, y:uint):Label {
var LBL:Label = new Label();
LBL.htmlText = lbl;
LBL.width = w;
LBL.move(x, y);
return LBL;
}
private function createTextInput(w:uint, x:uint, y:uint):TextInput {
var TI:TextInput = new TextInput();
TI.htmlText = "";
TI.width = w;
TI.move(x, y);
return TI;
}
private function createNumericStepper(defaultVal:uint, w:uint, h:uint, x:uint, y:uint):NumericStepper {
var NS:NumericStepper = new NumericStepper();
NS.move(x, y);
NS.setSize(w, h);
NS.minimum = 1;
NS.maximum = 150;
NS.stepSize = 1;
NS.value = defaultVal;
return NS;
}
private function createComboBox(w:uint, h:uint, x:uint, y:uint, _data:DataProvider):ComboBox {
var CB:ComboBox = new ComboBox();
CB.move(x, y);
CB.setSize(w, h);
CB.dataProvider = _data;
return CB;
}
private function clickHandler(event:MouseEvent):void {
respondToMouseEvent(event.target.name);
}
private function respondToMouseEvent(nme:String):void {
switch (nme) {
case "get_btn":
getSO();
break;
case "set_btn":
setSO();
break;
case "del_btn":
deleteSO();
break;
}
}
private function getSO():void {
name_txt.text = "";
mySO = SharedObject.getLocal(”person”);
if (mySO.size == 0) {
// Shared object doesn’t exist.
statLbl.htmlText = "Status: SharedObject not found.";
name_txt.text = "";
ageNS.value = 25;
genderCB.selectedIndex = 0;
} else {
name_txt.text = mySO.data.person.name;
ageNS.value = mySO.data.person.age;
if(mySO.data.person.gender == "Female"){
genderCB.selectedIndex = 1;
}
statLbl.htmlText = "Status: SharedObject value is - <b>"+mySO.data.person.getPerson()+"</b>";
}
}
private function setSO():void {
if (name_txt.text != "") {
tushar = createPerson(name_txt.text, ageNS.value, genderCB.selectedItem.data);
mySO.data.person = tushar;
mySO.flush();
getSO();
} else {
statLbl.htmlText = "Status: <b>Name</b> missing.";
}
}
private function deleteSO():void {
mySO.clear();
getSO();
}
private function createPerson(name:String, age:uint, gender:String):Person {
var tmpPerson = new Person();
tmpPerson.name = name;
tmpPerson.age = age;
tmpPerson.gender = gender;
return tmpPerson;
}
}
}

Now, create object of soExample and pass movieclip reference (in which all the components will be added at runtime) as parameter:

var mySoExample:soExample = new soExample(this);

Note: Be sure to add “Button”, “Label”, “ComboBox”, “NumericStepper” & “TextInput” components to the library of that movie.

Source:  AS3 Serializing Example (Zip file included)

Posted in ActionScript3, AS3, components, Flash | 25 Comments

Action Script 3: Component and SharedObject Example

Here is a simple tutorial on using prebuilt AS3 components and SharedObject.

SharedObject Example

Class soExample:

package {
import fl.controls.Button;
import fl.controls.Label;
import fl.controls.TextInput;

import flash.display.Sprite;
import flash.events.MouseEvent;
import flash.net.SharedObject;

public class soExample extends Sprite {
private var getData_btn:Button;
private var setData_btn:Button;
private var delData_btn:Button;
private var titleLbl:Label;
private var statLbl:Label;
private var soText:TextInput;
private var _mc:Sprite;
private var mySO:SharedObject;

public function soExample(_mc:Sprite) {
this._mc = _mc;
updateUI();
updateDisplay();
getSO();
}
private function updateUI():void {
getData_btn = createButton(getData_btn, "Get Shared Object", 150, 10, 100, "get_btn");
setData_btn = createButton(getData_btn, "Store Shared Object", 150, 10, 130, "set_btn");
delData_btn = createButton(getData_btn, "Delete Shared Object", 150, 10, 160, "del_btn");
titleLbl = createLabel(titleLbl, "<b>AS3 - Shared Object Example</b>", 200, 10, 10);
statLbl = createLabel(statLbl, "", 400, 10, 200);
soText = createTextInput(soText, 200, 10, 50);
}
private function updateDisplay():void {
_mc.addChild(titleLbl);
_mc.addChild(soText);
_mc.addChild(getData_btn);
_mc.addChild(setData_btn);
_mc.addChild(delData_btn);
_mc.addChild(statLbl);
}
private function createButton(btn:Button, lbl:String, w:uint, x:uint, y:uint, nme:String):Button {
btn = new Button();
btn.label = lbl;
btn.width = w;
btn.move(x, y);
btn.name = nme;
btn.addEventListener(MouseEvent.CLICK, clickHandler);
return btn;
}
private function createLabel(lblRef:Label, lbl:String, w:uint, x:uint, y:uint):Label {
lblRef = new Label();
lblRef.htmlText = lbl;
lblRef.width = w;
lblRef.move(x, y);
return lblRef;
}
private function createTextInput(tiRef:TextInput, w:uint, x:uint, y:uint):TextInput {
tiRef = new TextInput();
tiRef.htmlText = “”;
tiRef.width = w;
tiRef.move(x, y);
return tiRef;
}
private function clickHandler(event:MouseEvent):void {
respondToMouseEvent(event.target.name);
}
private function respondToMouseEvent(nme:String):void {
switch (nme) {
case "get_btn":
getSO();
break;
case "set_btn":
setSO();
break;
case "del_btn":
deleteSO();
break;
}
}
private function getSO():void {
soText.text = "";
mySO = SharedObject.getLocal("userData");
if (mySO.size == 0) {
// Shared object doesn’t exist.
statLbl.htmlText = "Status: SharedObject not found.";
} else {
statLbl.htmlText = "Status: SharedObject value is - <b>"+mySO.data.userName+"</b>";
}
}
private function setSO():void {
if (soText.text != "") {
mySO.data.userName = soText.text;
mySO.flush();
}
getSO();
}
private function deleteSO():void {
mySO.clear();
getSO();
}
}
}

Now, create object of soExample and pass movieclip reference (in which all the components will be added at runtime) as parameter:

var mySoExample:soExample = new soExample(this);

Note: Be sure to add “Button”, “Label” & “TextInput” components to the library of that movie.

Publish and test the flash file. Simple isn’t it 🙂

Posted in ActionScript3, AS3, Flash | 15 Comments

Action Script 3: Resize SWF on Browser resize

 

Accessing Stage object was pretty simple in previous versions of Action Script. However, it’s little different in Action Script 3. Sprits (movie clip) have property named stage (notice small “s”). One can use this property to access the Stage Object and respond to the Stage object’s Resize event.

Here is the AS3 code to resize SWF depending on browser size:

Class myStage:

package {

import flash.display.Stage;
import flash.display.Sprite;
import flash.display.StageAlign;
import flash.display.StageScaleMode;
import flash.events.Event;

public class myStage extends Sprite {

private var _mc:Sprite;
private var mcStage:Stage;

public function myStage(_mc:Sprite){
this._mc = _mc;
mcStage = _mc.stage;
addStageListener();
}

public function addStageListener() {
mcStage.scaleMode = StageScaleMode.NO_SCALE;
mcStage.align = StageAlign.TOP_LEFT;
mcStage.addEventListener(Event.RESIZE, resizeHandler);
}

private function resizeHandler(event:Event):void {
trace("stageWidth: "+mcStage.stageWidth);
trace("stageHeight: "+mcStage.stageHeight);
_mc.x = mcStage.stageWidth/2;
_mc.y = mcStage.stageHeight/2;
}
}
}

Now, create object of myStage and pass movieclip reference (which you want to align at center of stage) as parameter:

var mystage:myStage = new myStage(_mc);

Publish the flash file. Be sure to put 100% as value for Height and Width parameters in Object and param tag in HTML.

All set! Now you can test your file. SWF should now respond as you resize the browser window.

Posted in ActionScript3, Flash | 28 Comments

Free ActionScript 3 Videos

Just a quick post. If you are looking for some free Flash ActionScript 3 videos, check out Wikivid.

Direct link for the AS 3 videos: http://wikivid.com/index.php/Flash#Actionscript_3.0

Posted in ActionScript3, Flash | 4 Comments