Sunday, 25 April 2010

Video smoothing in AS3

This is an issue I found that has made serious difficulties to developers  about video playback. If you have a video file in flv format, and it has a size that is smaller than the stage where you want to show it in, Flash pixelizes the video. This is the default behaviour of Flash when playing video. 

There's a workaround but it's a direct one, as it was in AS2.

In AS2 you would do like this:

myVideoObject.smoothing = true | false

In AS3 you have to get to the "smoothing" in other way. Like this:
 
videoLoader.getVideoPlayer(videoLoader.activeVideoPlayerIndex).smoothing = true; 
 
 Where videoLoader is the FLVPlayback component that you insert with ActionScript.

Monday, 12 April 2010

How to load an external SWF

This is how you can load an external SWF, using the progress event to make some sort of preloader.



import flash.net.URLRequest;
import flash.display.Loader;
import flash.events.Event;
import flash.events.ProgressEvent;


function startLoad() {
   var mLoader:Loader = new Loader();
   var mRequest:URLRequest = new URLRequest(“MouseActions.swf”);
   mLoader.contentLoaderInfo.addEventListener(Event.COMPLETE,onCompleteHandler);
   mLoader.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS,onProgressHandler);
   mLoader.load(mRequest);
}


function onCompleteHandler(loadEvent:Event) {
   addChild(loadEvent.currentTarget.content);
}


function onProgressHandler(mProgress:ProgressEvent) {
   var percent:Number = mProgress.bytesLoaded/mProgress.bytesTotal;
   trace(percent);
}

startLoad();

Tuesday, 19 January 2010

XML loading class

This article is about loading xml data, on files or webservices. Sometimes, some projects require that you must read lots of information that are scattered throught many xml files or webservice. This class will help you not to recode every time you must read such type of information. Instead you only have to read the data acording to the response you receive.

So if you use this class, you just need to instatiate an object and call the file/webservice. Instantiate a new object for each file/webservice.

This code was copied from the website: http://www.mediareason.com/blog/?p=20

package com.func
{
import flash.net.URLLoader
import flash.net.URLRequest
import flash.xml.XMLDocument;
import flash.errors.*
import flash.events.*
public class LoadXML
{
private var loader : URLLoader;
private var mainXML : XML;
public function LoadXML() {
loader = new URLLoader();
loader.addEventListener(Event.COMPLETE, onComplete);
loader.load(new URLRequest("http://.../test.xml"));
}
private function onComplete(evt:Event)
{
try
{
mainXML = new XML(loader.data)
trace(mainXML);
} catch(e:Error)
{
trace("Error: " + e.message)
return;
}
}
}
} 

Thursday, 5 November 2009

Decimal to Fraction

This class will be very handy to transform a decimal number to a fraccion. This was taken from forum entry in Actionscript.org and the user "rondog" converted a AS2 class to AS3. This is one more place where you can get it.

package com.lookmum.util
{
    public class Fraction
    {
        private static var it         :Number = 0;
        public static var iterationLimit:Number = 10000;
        public static var accuracy    :Number = 0.00001;
        
        public function Fraction()
        {
            
        }
        
        private static  function resetIt():void
        {
            it = 0;
        }
        
        private static  function addIt():Boolean
        {
            it++;
            if (it == iterationLimit)
            {
                trace('error : too many iterations');
                return true;
            }
            else
            {
                return false;
            }
        }

        public function getFractionString(num:Number):String
        {
            var fracString:String;
            var fracArray:Array = getFraction(num);
            switch (fracArray.length)
            {
                case 1 :
                    fracString = num.toString();
                    break;
                case 2 :
                    fracString = fracArray[0].toString() + '/' + fracArray[1].toString();
                    break;
                case 3 :
                    fracString = fracArray[0].toString() + ' ' + fracArray[1].toString() + '/' + fracArray[2].toString();
                    break;
            }
            return fracString;
        }
        
        public function getFraction(num:Number):Array
        {
            var fracArray:Array = new Array();
            var hasWhole:Boolean = false;
            if (num >= 1)
            {
                hasWhole = true;
                fracArray.push(Math.floor(num));
            }
            if (num - Math.floor(num) == 0)
            {
                return fracArray;
            }
            if (hasWhole)
            {
                num = num - Math.floor(num);
            }
            var a:Number = num - int(num);
            var p:Number = 0;
            var q:Number = a;
            
            resetIt();
            
            while (Math.abs(q - Math.round(q)) > accuracy)
            {
                addIt();
                p++;
                q = p / a;
            }
            fracArray.push(Math.round(q * num));
            fracArray.push(Math.round(q));
            return fracArray;
        }
    }
}

Monday, 26 October 2009

Instantiate from library by class name

This maybe is one of the best hints for any as3 developer.

You have several objects in the Library, and some of them have sequenciall names, like "obj1", "obj2", "obj3"... and so on.

Normally if you want to instanciate an object from the library you would do like this:

var obj1:obj1=new obj1();
var obj2:obj2=new obj2();
...

What do you think... tedious, right? and not eficient, at all.

One of the solutions is to use the flash.util class that as a method called getDefinitionByName, wich can help a lot on this sort of thing.

By the upper example you just need a FOR cycle to instantiate all the objects. Imagine that I have from obj1 to obj5, this is how I would do it:

import flash.util.*;

private function instObj():void{
  for(var i:Number=1; i<6; i++){
    var name:String="obj"+i;
    var object = new (getDefinitionByName(name) as Class)();
    addChild(object);
  }
}

Sunday, 25 October 2009

Generalize Methods

This one I saw in the "Actionscript 3 Cookbook" by Joey Lott, Darron Schall, Keith Peters and published by O'Reilly. Although it's on the first chapter of the book, it may come handy most of the times.


This recipe applies when you have a method and you want to use it several times, but with slightly different numbers of arguments, like calculating the average number. You can calculate the average between 2 numbers, or maybe, 7.


Lets  make a example:

public function average (num1:Number, num2:Number):void{
   trace("The average number is: "+(num1+num2)/2;
}

You call this method like this:

average(3,6);

The answer will be:

The average number is: 4.5

So how can I call the average method with a different number of arguments?


In the first place, you don't specify the number of arguments you put in the method, when you define it.
 Then, you must have a cycle inside the method, that will read all the arguments when you call it. 
Do it like this:

public function average():Number{
  var sum:Number=0;


  for(var i:Number=0; i
     sum+=arguments[i];
  }
  
  return sum/arguments.length;
}

The keyword arguments will retrieve the number and the value of the arguments that you place when you call a method.


then call the function like this:


var value:Number=average(2,3,4);


or


var value:Number=average(5,6,7,8,9,10);




This is a nice feature

Friday, 16 October 2009

How to Format Text in Actionscript

This time I will post a snippet about how to format text in a textfield that is placed dynamicaly in the Stage.


Firstly you must insert the TextField on the stage. For that you need to place these two line in order to import the class that controls the TextField object in AS3. The second import, will import the class that control the appearence of TextFields:



import flash.text.TextField;
import flash.text.TextFormat;

Next you need to create the TextField and place it in the DisplayObject list:

var myText:TextField = new TextField();
addChild(myText);

Next you can tell Flash if the user can select the text, and if you want some border around the TextField:



myText.selectable = false;
myText.border = false;


Next you can tell if the TextField is autosizable, that is, if the text inside is to be dynamic, maybe you need the TextField to stretch or shrink, according to the text value. You can even tell if the autosize is to the right, center or left:


myText.autoSize = "center";


Now we're ready to format the contents of the TextField. For that you need to create a TextFormat object that will be associated to the TextField later on.


Create the TextFormat object:


var myFormat:TextFormat = new TextFormat();


Define the font face you want to use. Then you can define if the text is to bold, underline or italic:


myFormat.font = "Myriad Pro";
myFormat.bold = true;


Give it some colour:


myFormat.color = 0xFF0000;


Change the size:


myFormat.size = 12;


Finally associate the TextFormat to the TextField:


myText.setTextFormat(myFormat);


Happy Texting...