Archive for the ‘Flash’ Category

Flash focus border in Firefox

Monday, March 22nd, 2010

I’ve noticed recently that Firefox has started showing a 1px dotted border around flash objects when I click on them. It didn’t bother me enough to look for a solution, but today the solution found me.
In my rss reader a blog post from FlashComGuru pops up, showing how to get rid of this annoyance, pasted here for your convenience:

Simply add this to your page’s stylesheet:

a:focus, object:focus { outline: none; -moz-outline-style: none; }

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.

WordPress replaces — with –

Thursday, November 5th, 2009

I just recently upgraded my wordpress system, and now it does not show my embedded flash at all. I would be surprised, but this isn’t the first time this happens.
The last time I upgraded I found a blog post on how to fix it, but it’s been a while and I just can’t find that post any more, so I’m writing my own.

So this is the deal: I always embed my flash using the html code that SWFobject recommends:

<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="780" height="420">
  <param name="movie" value="myContent.swf" />
  <!--[if !IE]>-->
  <object type="application/x-shockwave-flash" data="myContent.swf" width="780" height="420">
  <!--<![endif]-->
    <p>Alternative content</p>
  <!--[if !IE]>-->
  </object>
  <!--<![endif]-->
</object>

After the upgrade, instead of my pretty flash objects I get this funky arrow in my posts:

–>

And if I look at the source, it now looks like this:

<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="780" height="420">
  <param name="movie" value="myContent.swf" />
  <!--[if !IE]>&#8211;>
  <object type="application/x-shockwave-flash" data="myContent.swf" width="780" height="420">
  <!--<![endif]-->
    <p>Alternative content</p>
  <!--[if !IE]>&#8211;>
  </object>
  <!--<![endif]-->
</object>

Apparently wordpress replaces
<!–[if !IE]>>
with
<!–[if !IE]>&#8211;>, but when I look into my post to edit it, it still looks fine there.

The reason is that wordpress is trying to make your writing prettier, even if you don’t use the wysiwyg editor. To stop wordpress from doing that, go into your wordpress directory and edit the file wp-includes/formatting.php. On lines 55 and 56 (for version 2.8.5) you should see this text:

$static_characters = array_merge(array('---', ' -- ', '--', ' - ', 'xn&#8211;', '...', '``', ''s', '''', ' (tm)'), $cockney);
$static_replacements = array_merge(array('&#8212;', ' &#8212; ', '&#8211;', ' &#8211; ', 'xn--', '&#8230;', $opening_quote, '&#8217;s', $closing_quote, ' &#8482;'), 

If not, just look for it, it should be in the top page or two.
Now all you have to do is comment out the array elements you don’t want wordpress to replace. My lines look like this:

$static_characters = array_merge(array(/*'---', ' -- ', '--', ' - ', */'xn&#8211;', '...', '``', ''s', '''', ' (tm)'), $cockney);
$static_replacements = array_merge(array(/*'&#8212;', ' &#8212; ', '&#8211;', ' &#8211; ', */'xn--', '&#8230;', $opening_quote, '&#8217;s', $closing_quote, ' &#8482;'), 

Hope this helps.

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;
}

Line-Line Intersection in AS3

Tuesday, April 28th, 2009

Line line intersection function explanation

I found a bug in my old Line-Line Intersection in C++ post, and after I fixed it I thought it would be a good idea to port it to AS3:

function intersection(p1:Point, p2:Point, p3:Point, p4:Point):Point {
    var x1:Number = p1.x, x2:Number = p2.x, x3:Number = p3.x, x4:Number = p4.x;
    var y1:Number = p1.y, y2:Number = p2.y, y3:Number = p3.y, y4:Number = p4.y;
	var z1:Number= (x1 -x2), z2:Number = (x3 - x4), z3:Number = (y1 - y2), z4:Number = (y3 - y4);
    var d:Number = z1 * z4 - z3 * z2;
	
    // If d is zero, there is no intersection
    if (d == 0) return null;

	// Get the x and y
    var pre:Number = (x1*y2 - y1*x2), post:Number = (x3*y4 - y3*x4);
    var x:Number = ( pre * z2 - z1 * post ) / d;
    var y:Number = ( pre * z4 - z3 * post ) / d;
    
    // Check if the x and y coordinates are within both lines
    if ( x < Math.min(x1, x2) || x > Math.max(x1, x2) ||
        x < Math.min(x3, x4) || x > Math.max(x3, x4) ) return null;
    if ( y < Math.min(y1, y2) || y > Math.max(y1, y2) ||
        y < Math.min(y3, y4) || y > Math.max(y3, y4) ) return null;
 
    // Return the point of intersection
    return new Point(x, y);
}

You can try it here:

Get Adobe Flash player

Flash Player 10 penetration at 75.3%

Monday, April 27th, 2009

Adobe has just updated their flash penetration statistics, and flash player 10 has reached 75.3% in Europe.

Soon it will be time to make 10 the default version in my publish settings =)

AS3 Array Shuffle

Friday, April 17th, 2009

There are a lot of ways to shuffle an array in AS3, ranging from swapping repeatedly the elements to using the sort function with a random sorter, but the most convenient way I’ve found was to simply splice a random element from the former array to the new shuffled array while the former array has elements.

DaveOnCode has a nice implementation of this method, pasted here:

var arr2:Array = [];

while (arr.length > 0) {
    arr2.push(arr.splice(Math.round(Math.random() * (arr.length - 1)), 1)[0]);
}

Edit: Although small and convenient, this method is not the fastest way of shuffling an array, check out the comments for more info.