Total Pageviews

Saturday 6 August 2011

Create XML in AS3

ActionScript 3.0 now treats XML as a native data type meaning its no longer parsed as a String. That does bring with it that the old methods of inserting variable values (e.g. “”+myValue+””) no longer apply.
Just take a look at the following snippet of code:
var myVar:Number = 3;

var xml:XML =<myXML>
    <valueOfMyVar>{myVar}</valueOfMyVar>
</myXML>
That’s right, the curly braces notation from MXML. One difference though, this is not an active reference to the variable. If you change the value of the variable this will not update your XML (no, not even in Flex — this is pure AS3 code but you can of course define the XML structure in MXML and take advantage of its data binding features).
Also worth noting is that you don’t put quotes around the curly braces when you use it for an XML attribute, if you do that it’ll treat it as a String rather than eval’ing it. The XML object takes care of generating valid XML from it.

Wednesday 13 July 2011

Uploading image file in Flex

The file upload is initiated when the user clicks on the Upload button on the Stage, which invokes the FileUpload.startUpload() method. This method calls the browse() method of the FileReference class which causes the operating system to display a system dialog box prompting the user to select a file to upload to the remote server. The following excerpt shows the code for the startUpload() method:

public function startUpload():void
{
   fr.browse();  
}

Once the user selects a file to upload, the select event (Event.SELECT) is dispatched, causing the selectHandler() method to be invoked. The selectHandler() method creates a new URLRequest object and sets the URLRequest.url property to the value of the UPLOAD_URL constant defined earlier in the code. Finally, the FileReference object uploads the selected file to the specified server-side script. The code for the selectHandler() method is as follows:

private function selectHandler(event:Event):void
{
    var request:URLRequest = new URLRequest();  
    request.url = UPLOAD_URL;  
    fr.upload(request);  
}

The remaining code in the FileUpload class is the same as the code defined in the FileDownload class. If a user wishes to terminate the upload at any point, they can click the Cancel button, which sets the label on the progress bar and stops the file transfer immediately. The progress bar gets updated whenever the progress event (ProgressEvent.PROGRESS) is dispatched. Similarly, once the upload has completed, the progress bar is updated to notify the user that the file has uploaded successfully. The Cancel button is then disabled until the user begins a new file transfer.

Saturday 2 July 2011

Convert an Image to Base64 string and vice versa

import flash.utils.ByteArray;
import flash.display.Loader;
import flash.display.Bitmap;
import flash.display.BitmapData;
import flash.events.Event; 
import mx.utils.Base64Decoder; //Transform String in a ByteArray.
import mx.utils.Base64Encoder; //Transform ByteArray in a readable string.
import mx.graphics.codec.PNGEncoder; //Encode a BitmapData in a PNG;

//In this case I had a BitmapData in the library
so I took it from there.
var myBMD:BitmapData=new myBitmapData(0,0); 

//Create the ByteArray of myBMD usinf the PNGEncoder.
var myBMDByteArray:ByteArray=(new PNGEncoder).encode(myBMD);

var compStr:String=compress(myBMDByteArray); //Creates String
trace(compStr);

// The loader acts exactly as we were loading an external 
PNG except the fact that we write the ByteArray.
var loader:Loader = new Loader(); 
// In the loadBytes we write the Base64 String of the image.
loader.loadBytes(uncompress(compStr));
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, loadComplete);

function loadComplete(e:Event):void
{
    var bmp:BitmapData=new BitmapData(loader.width,loader.height,true,0x0);
    bmp.draw(loader);
    addChild(new Bitmap(bmp));
}

// Compress a ByteArray into a Base64 String.
function compress(bytes:ByteArray):String
{
    var enc:Base64Encoder = new Base64Encoder();   
    enc.encodeBytes(bytes);
    return enc.drain().split("\n").join("");
}

// Uncompress a Base64 String into a ByteArray.
function uncompress(str:String):ByteArray
{
    var dec:Base64Decoder = new Base64Decoder();
    dec.decode(str);
    var newByteArr:ByteArray=dec.toByteArray();       
    return newByteArr;
}


Compatibility issue with ios applications developed using flash builder 4.5

Building an app using Flashbuilder 4.5 and just tried to install it on iOS devices it says its not compatible with my ipod touch while iOS devices are running 4.2 and all are the 3rd generation, devices.

Reasonn is Flash Builder 4.5 applications will work only newer version of iOS devices with multitasking hardware capabilities. i.e. your devices (iPhone 4 ,iPod touch and iPad) should be with newer version hardware capabilities.

Saturday 18 June 2011

Load and Display Image in Flash Builder 4

There are 3 methods for loading image in flash builder 4:

1) Load and Display image on Stage:


<?xml version="1.0" encoding="utf-8"?>
<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" minWidth="500" minHeight="500" applicationComplete="loadImage()">

<fx:Declarations>
<!-- Place non-visual elements (e.g., services, value objects) here -->
</fx:Declarations>

<fx:Script>
<![CDATA[
import flash.display.*;
import flash.events.*;
import flash.net.*;
import mx.core.*;

private var loader:Loader = new Loader();
private var ui:UIComponent = new UIComponent();
private var sprite:Sprite = new Sprite();
                        private var mc:MovieClip = new MovieClip();

private function loadImage():void
{
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, imageLoaded);
loader.load(new URLRequest("mypic.jpg"));
trace("started loading");
}

private function imageLoaded(event:Event):void
{
loader.width=50;
loader.height=50;
systemManager.stage.addChild(loader);
}

]]>
</fx:Script>
</s:Application>

if we want to set height width of image then set the loader height and width and than addChild the image in stage. else if we want to load image in actual size than there is no need to set the loader height and width.


2) There is an another way to load image if  you wanted to add a Flash DisplayObject to the main Application canves you would wrap the DisplayObject in a UIComponent then add the UIComponent, then add the UIComponent to the Application as a child, like this:

ui.addChild(loader);
this.addElement(ui);

3) Another way to load and display an image inside a MovieClip: 
                         
ui.addChild(mc);
this.addElement(ui);
mc.addChild(loader);

Friday 17 June 2011

What Is ActionScript?

ActionScript is a programing language. It allows you to the enhance user control of a flash application. If you want anything exciting or interactive to happen within a flash application you have to use ActionScript. With ActionScript you can program your flash application to adapt, or reach to user input, user action, external data or even the time of day. An example of such a change would be igoogle's web header. If you have an igoogle account you can choice your own web header. This header will change based on weather conditions and the time of day.

ActionScript enables the programer to provide both action-oriented instructions(do-this) and logic-oriented instructions(check this then do something) to the flash application.

ActionScript is created with a syntax structure, the same way that all programing language are developed, ActionScript Syntax consists of many different words, phrases, punctuation and structure, must use the
 proper syntax.

Such as:
phrase_txt.text = "ActionScript is Cool!";
phrase_txt.textColor = 0x232e81;
phrase_txt.thickness = 2;

So Basically, ActionScript is a programing language that enables advance control of flash applications.

Thursday 16 June 2011

AS3 Shuffle Array

Shuffling an array is something that is always needed. Whether it is for a card game, creating a random label , or just to randomize part of your data to make your application more interesting. Shuffling in AS3 is like the following: 

package 
{
    import flash.display.*;
   
    public class Shuffling extends MovieClip
    {
        private var my_array:Array=["a","b","c","d","e","f","1","2","3","4","array","Flash"];
       
        public function Shuffling()
        {
            // constructor code
            trace("Before Shuffling: "+my_array);
            arrayShuffle(my_array);
            trace("After Shuffling: "+my_array);
        }
       
        public  function arrayShuffle(array_arr:Array):Array
        {
           for(var i:Number = 0; i < array_arr.length; i++)
           {
              var randomNum_num = Math.floor(Math.random() * array_arr.length)
              var arrayIndex = array_arr[i];
              array_arr[i] = array_arr[randomNum_num];
              array_arr[randomNum_num] = arrayIndex;
           }
           return array_arr;
        }    }   
}
First off it creates a variable of a random number between 0 and one less than the length of the array. The reason it is one less than the length of the array, is because we have Math.floor pushing the number to the "floor". It then creates a variable equal to "i" or the iteration of  loop.It then makes the index of the array to be the value of the array’s index at the random number we created. And then just the opposite, it makes the index of the array at our random number to be the value of the array at our iteration. For instance, the first iteration of the loop is 0, and if our random number is 5, then it would swap those indices, so my_array[0] would now be 5, and my_array[5] would now be 0.It continues to do this throughout the loop. Because it does not exclude indices it has already swapped, it will continue to swap out those it chooses, making the array completely random each time it is ran. After the  loop finishes, it then returns the array. we can display it by tracing an array.

Load Text File Data Into a TextField

package
{
    import flash.display.*;
    import flash.events.*;
    import flash.net.*;
       
    public class MyClass extends MovieClip
    {
        public function MyClass()
        {
            var loader:URLLoader = new URLLoader(new URLRequest("text.txt"));
            loader.addEventListener(Event.COMPLETE, completeHandler);
           
            function completeHandler(event:Event):void
            {
                var loadedText:URLLoader = URLLoader(event.target);
                myText_txt.text = loadedText.data;
            }
        }
    }
}

JSON and AS3 Communication

JSON is also reffered as JavaScript Object Notation (JSON).

JSON is a lightweight text-based data exchanging standart designed to be easy readable for humans. It came from the Java Script programming language and represents simple associative arrays. Even though it has Javascript in its name, it is very widely used in all programming languages, mainly to transfer data between a server and a web application.

JSON takes 25% space rather than XML file.

To parse JSON using AS3, I will use some classes from the library written by the good Adobe people
called as3corelib.

The example JSON file which i am using have structure like this:

{
"staff":
[
 {
 "firstName":"John",
 "lastName":"Parker",
 "age":"32",
 "country":"Canada",
 "job":"Programmer"
 },

 {
 "firstName":"Peter",
 "lastName":"Anderson",
 "age":"30",
 "country":"USA",
 "job":"System administrator"
 },

 {
 "firstName":"Bob",
 "lastName":"Johnson",
 "age":"35",
 "country":"Canada",
 "job":"Coder"
 }
]
}
 
Now, let's parse it using AS3.
// import the necessary JSON class (I have the com folder in the 
same directory as my flash code):
 
package
{
 import com.adobe.serialization.json.JSON;  
 import flash.display.*;
 import flash.events.*;
 import flash.net.*;
 
 public class MyClass extends MovieClip
 {
  public function MyClass()
  {
   var myRequest:URLRequest = new URLRequest("staff.txt");
   var myLoader = new URLLoader();
   myLoader.addEventListener(Event.COMPLETE, onload);
   myLoader.load(myRequest);
   
/*which will consist of an array of 3 other Objects: myData,
For each member we have a set of properties, such as first and 
last names.use the JSON class we've imported 
to encode this into a string:*/
function onload(evt:Event):void
   {
    var myData:Object = JSON.decode(myLoader.data);
    trace(myData.staff[0].firstName);
    trace(myData.staff[1].job);
    trace(myData.staff[1].age);    
   }
  }
 }
}

Wednesday 15 June 2011

Load a single Image into an Empty MovieClip via XML

package 
{
    import flash.display.*;
    import flash.events.*;
    import flash.net.*;
    import flash.xml.*;
   
    public class MyClass extends MovieClip
    {
        public function MyClass()
        {
            init();
        }
       
        public function  init():void
        {
            var myXML:XML;
            var myLoader:URLLoader = new URLLoader();
            myLoader.load(new URLRequest("Image.xml"));    // Load a XML

            myLoader.addEventListener(Event.COMPLETE, processXML);           
        }

      
        Public function processXML(e:Event):void
        {
            myXML = new XML(e.target.data);
         
            var ldr:Loader = new Loader();
            ldr.load(new URLRequest(myXML.IMAGE[0]));
            mc.addChild(ldr);
        }
    }   
}

Microsoft Logo using flexbox and Reactjs

 <!DOCTYPE html> <html> <head>     <script src="https://unpkg.com/react@18/umd/react.development.js" crossori...