Runtime pixel snapping

Lets set the scene: your lazy. You got a sweet a design in photoshop and now you need to bring it to life in flash. Now remember your lazy so your going to use flash’s PSD importer to import the layers into flash. What a timer saver. Flash has has made movieclips and text layers from the photoshop layers, nice. You hookup some functions and publish the file. But something is wrong, some the text looks a little fuzzy and some of the lines are little blurred. You jump back to the fla and check through some of the movieclips. Bah, flash has placed some clips in-between pixels. You’ve even got the ‘Snap to Pixels’ feature turned on but flash has ignored when doing the import.
This has happened to me countless times and often on a big flash project it can be real drag digging through movieclips trying to find the elusive off-pixel clip. It would great I thought if I had a little pixel pixie to go through my FLA and fix up all the movieclips and textfields. Well I couldn’t find any pixies or elfs that where willing to work for me so instead I wrote recursive function to do it at runtime.
This script takes in one argument, the base movieclip it then goes through every child of that movieclip and rounds the x and y position to the nearest pixel. So that every stage instance is rendered on a whole pixel. If any of these clips have children if goes through them and rounds their position and so on and so on recursively until it does each movieclip, sprite or textfield in the swf.

roundChildren(this)
function roundChildren(base:DisplayObjectContainer):void {
	for (var i:int=0; i<base.numChildren-1; i++) {
		var m:DisplayObject=base.getChildAt(i) as DisplayObject;
		var p:DisplayObjectContainer=base.getChildAt(i) as DisplayObjectContainer;
		if (m) {
			m.x=Math.round(m.x);
			m.y=Math.round(m.y);
			if(p){
				if (p.numChildren>0) {
					roundChildren(p);
				}
			}
		}

	}
}

Checkout the example below to see the script in action. The pixel snapping does not effect dynamic text because of the way flash anti-aliases it. But you can see a big improvement for the static text and vector lines placed inside a movieclip.

This movie requires Flash Player 10



See more

1 comment so far ↓

#1 Andrew on 03.19.12 at 8:33 am

I made a scale 9 bitmap class and this saved me :) sometimes the edge bitmap would be a pixel off but Math.floor() seemed to help.

Leave a Comment