Skip to content

Using Anchors for positioning

rubenmueller edited this page Sep 13, 2010 · 7 revisions

Problem:

  • To postion things right now you have to override updateDisplaylist on the UIControl.
  • The only way to position things in the center of a UIControl is by doing math (like: (control.width-child.width)/2 ).

Proposed solution:

Introduce a new core object called Anchor. Similar to backgroundPainters, anchors would be triggered at the updateDisplaylist() call. Could look something like:

var anchor1:Anchor = Anchor.target(sprite).toHorizontalCenter();
var anchor2:Anchor = Anchor.target(sprite).toLeft(10).toTop(10);
Control.addAnchors(anchor1, anchor2); // this uses the varargs to allow addition of as many anchors as needed.

Additionally, anchors can also be used to anchor child components to each other. And since the methods return reference to the Anchor itself, they can be chained like so:

Anchor.target(sprite).toLeftOf(sprite2, 10).toBottomOf(sprite2, 10);

Note the target is just a static function on the Anchor class that returns a reference to a newly constructed anchor.

Anchor public methods:

public static function target(object:Object):Anchor
(used to create a new Anchor, assign it to either a Group or a single component)
// For positioning regarding some reference displayObject
public function toLeftOf(ref:DisplayObject, distance:Number ):Anchor
public function toRightOf(ref:DisplayObject, distance:Number):Anchor
public function above(ref:DisplayObject, distance:Number=0):Anchor
public function below(ref:DisplayObject, distance:Number=0):Anchor
// For positioning regarding the parent
public function toHorizontalCenter(offset:Number=0):Anchor
public function toVerticalCenter(offset:Number):Anchor
public function toLeft(offset:Number):Anchor
public function toRight(offset:Number):Anchor
public function toTop(offset:Number):Anchor
public function toBottom(offset:Number):Anchor

Additionally Anchors can be used with Groups. So you can layout your children in a group and then anchor the entire group to a point within the container’s bounds.

var g:Group = new Group();
g.addChidren(child1, child2, child3);
g.layout =  new HLayout();
Anchor.target(g).toHorizontalCenter().toVerticalCenter();

This gives us the best possible way of centering a bunch of controls on the center of the parent