Code Snippet: Centering Arbitrary DisplayObjects

The math for centering a DisplayObject whose registration point is not at 0,0 can be a little tricky. I’ve recalculated this algorithm too many times, so I thought I’d share it here.

Assume you want to center the DisplayObject “sprite” in the DisplayObjectContainer “container.” Assume container has a 0,0 registration point, but sprite may not.

container.addChild(sprite); //Important to do this first!
sprite.x = container.x + container.width * 0.5;
sprite.y = container.y + container.height * 0.5;
var bounds:Rectangle = sprite.getBounds(container);
sprite.x += sprite.x - (bounds.left + 0.5 * bounds.width);
sprite.y += sprite.y - (bounds.top + 0.5 * bounds.height);

Or, more generally, to place the center of a display object at (desiredX, desiredY):


var bounds:Rectangle = sprite.getBounds(desiredCoordinateSpaceDisplayObject);
sprite.x = desiredX -  (bounds.left + 0.5 * bounds.width);
sprite.y = desiredY -  (bounds.top + 0.5 * bounds.height);

I hope this helps someone!