Posts Tagged ‘AS3’

Color.setTint() alternative (AS3)

Monday, February 1st, 2010

I once discovered a really cool feature of the color class that lets you set the tint of an object via its color transform object using the setTint function.
The bad news though is that the Color class is in the fl namespace, so if you’re developing outside of the Flash IDE you have no access to that class natively, so here is how to replicate that functionality without the Color class:

Tinting with the color class:

import fl.motion.Color;
// Tint the movie clip 50% with the color 0xFF9933
var c:Color = new Color();
c.setTint(0xFF9933, 0.5);
myMovieClip.transform.colorTransform = c;

Tinting without the color class:

import flash.geom.ColorTransform;

// Tint the movie clip 50% with the color 0xFF9933
var tintColor:uint = 0xFF9933;
var tintMultiplier:Number = 0.5;
setTint(myMovieClip, tintColor, tintMultiplier);

function setTint(displayObject:DisplayObject, tintColor:uint, tintMultiplier:Number):void {
	var colTransform:ColorTransform = new ColorTransform();
	colTransform.redMultiplier = colTransform.greenMultiplier = colTransform.blueMultiplier = 1-tintMultiplier;
	colTransform.redOffset = Math.round(((tintColor & 0xFF0000) >> 16) * tintMultiplier);
	colTransform.greenOffset = Math.round(((tintColor & 0x00FF00) >> 8) * tintMultiplier);
	colTransform.blueOffset = Math.round(((tintColor & 0x0000FF)) * tintMultiplier);
	displayObject.transform.colorTransform = colTransform;
}

Pie mask in AS3

Friday, November 13th, 2009

Sometimes I have the need for a rotational progress bar that acts like a pie growing bigger (or smaller if that strikes your fancy). As usual, I made my own =)
The function drawPieMask takes first the graphics object of the displayObject instance and draws a part of pie on it, percentage set’s how big the part is.
If you want to offset the rotation of the pie (it starts to the right by default) you can set the rotation parameter. Note that rotation is in radians, not degrees, but you can multiply your degrees by (Math.PI/180) to convert to radians.
Lastly, the sides property determines how many sides the circle drawn in the mask has. You can see an example of different pie masks after the code.

To make the code as customizable as possible, it does not make a call to beginFill in case you want to set your own fill (or gradientfill even?).
If you just want to use it as a basic mask, just call beginFill(0) before and endFill() after the call to drawPieMask.

function drawPieMask(graphics:Graphics, percentage:Number, radius:Number = 50, x:Number = 0, y:Number = 0, rotation:Number = 0, sides:int = 6):void {
	// graphics should have its beginFill function already called by now
	graphics.moveTo(x, y);
	if (sides < 3) sides = 3; // 3 sides minimum
	// Increase the length of the radius to cover the whole target
	radius /= Math.cos(1/sides * Math.PI);
	// Shortcut function
	var lineToRadians:Function = function(rads:Number):void {
		graphics.lineTo(Math.cos(rads) * radius + x, Math.sin(rads) * radius + y);
	};
	// Find how many sides we have to draw
	var sidesToDraw:int = Math.floor(percentage * sides);
	for (var i:int = 0; i <= sidesToDraw; i++)
		lineToRadians((i / sides) * (Math.PI * 2) + rotation);
	// Draw the last fractioned side
	if (percentage * sides != sidesToDraw)
		lineToRadians(percentage * (Math.PI * 2) + rotation);
}

Example of different sides values. The last circle has a pie with 3 sides as a mask.

Get Adobe Flash player

You can get the example fla here.

Profiling AS3/Flex applications

Tuesday, October 6th, 2009

I’m working on a big project and was having some problems with memory leaks. After some google-ing around I found this great video on AdobeTV by Jun Heider where he shows you how to profile both the memory and performance of your AS3 or Flex application.
It’s pretty thorough and it is little over one hour in length.

Number Format – Thousand Separator in AS3

Wednesday, August 12th, 2009

Here’s a short number format function I wrote to easily paste in your code when needed. It’s really handy for currency formatting.
The first parameter (number:*) can be a Number, int, uint or a String class instance.
The last parameter (siStyle:Boolean) specifies whether to use the International System of Units or not. SI units have points between the thousands and a comma for the seperator (123.456.789,01). Putting siStyle as false reverses that behaviour (123,456,789.01).

It’s really ugly by design since I wanted it to be a single, tiny function. There’s loads of prettier/faster code samples out there.

function numberFormat(number:*, maxDecimals:int = 2, forceDecimals:Boolean = false, siStyle:Boolean = false):String {
    var i:int = 0, inc:Number = Math.pow(10, maxDecimals), str:String = String(Math.round(inc * Number(number))/inc);
    var hasSep:Boolean = str.indexOf(".") == -1, sep:int = hasSep ? str.length : str.indexOf(".");
    var ret:String = (hasSep && !forceDecimals ? "" : (siStyle ? "," : ".")) + str.substr(sep+1);
    if (forceDecimals) for (var j:int = 0; j <= maxDecimals - (str.length - (hasSep ? sep-1 : sep)); j++) ret += "0";
    while (i + 3 < (str.substr(0, 1) == "-" ? sep-1 : sep)) ret = (siStyle ? "." : ",") + str.substr(sep - (i += 3), 3) + ret;
    return str.substr(0, sep - i) + ret;
}

Load font dynamically on runtime

Wednesday, May 6th, 2009

Sometimes you want to be able to keep your fonts in a seperate swf file, a “font library” if you will, that you can load dynamically on runtime. Here’s how to do that in AS3:

The first thing you have to do is create a new flash file to store the font(s). Then, right click the library and select “New Font…”.
newfont

Choose the font you want to embed and give it a name. Any name will do here, as this is only the library name and will not affect our code in any way. I prefer to name the font with the same name as the linkage name I plan to give it.
myfont

Click ok, and then right click the font in the library and select “Linkage…”. Check the “Export for ActionScript” and “Export in first frame” options, give your font the linkage name of your own liking and click OK.
linkage

And now you’re ready. Export the file to swf and there’s your font resource file.

If you want to use that font, you first have to load it into the application domain, and then register it on the global font list using the Font.registerFont function. The textfield can’t display it until it has the embedFonts property set to true and the font name in its textformat.
You can see an example in the following code, ready to be pasted into your frame:

var l:Loader = new Loader();
l.contentLoaderInfo.addEventListener(Event.COMPLETE, onLoaded);
l.load(new URLRequest("MyFont.swf"), new LoaderContext(false, ApplicationDomain.currentDomain));

function onLoaded(e:Event):void {
	// Register the font to the global font list
	Font.registerFont( Class( ApplicationDomain.currentDomain.getDefinition("MyFont")));
	
	myTextField.embedFonts = true;
	// instantiate the font just to get the real font name, or if you know the name before hand you can just hard-code it in here
	var fontName:String = new (ApplicationDomain.currentDomain.getDefinition("MyFont"))().fontName;
	var tf:TextFormat = new TextFormat(fontName);
	// Set the text format for the text already in the text field
	myTextField.setTextFormat(tf);
	// and for future changes
	myTextField.defaultTextFormat = tf;
}