Vertical-alignment for TextFields – ActionScript 3.0

Vertical-alignment for textfields in ActionScript 3.0 is useful for aligning textfields to images, other UI elements in a flash app, and more! As many of you may know, Adobe introduced TLF Text along with Flash Player 10. If you are working with general consumer projects, however, chances are you are targeting Flash Player 9 as a minimum.
Before TLF TextFields, there was no direct way to vertically align TextFields.

That being said, you can easily accomplish this by using the TextLineMetrics object, or more directly, TextField‘s getLineMetrics().

TextLineMetrics allows us to access basic values for any typeface, such as ascent, descent, leading, width and height. Using ascent, we can determine a TextField’s baseline Y position.

Example

Let’s assume that our TextField myText is already on the stage. This is how you would get it’s baseline Y-axis:

var baselineY:Number = myText.y + myText.getLineMetrics(0).ascent;

Now, to align another TextField myOtherText to this myText, you would do this:

myOtherText.y = baselineY - myOtherText.getLineMetrics(0).ascent;
// or
myOtherText.y = myText.y - myOtherText.getLineMetrics(0).ascent;

The second method can be used if you have 1 item that is stationary. Otherwise, store the fixed Y position in a variable, so you can move myText around and move it back in line later.

One thought on “Vertical-alignment for TextFields – ActionScript 3.0”

  1. This is an old topic, but I recently was looking for a simple solution for vertical align text in a TextField and I did it.
    It works great only for the case that the text is in single line.

    First you have to add an initial break line in every text. I did it in a new component extending TextField and overriding the “text” function, adding the initial break line character.

    import flash.text.TextField;

    public class MyTextField extends TextField
    {
    public function MyTextField()
    {
    super();
    }

    public override function set text(value:String):void
    {
    value = “\n” + value;

    super.text = value;
    }
    }

    Then you need to apply format to the text, an use the “leading” property that represents the amount of vertical space between lines.

    myTextFormat = new TextFormat();

    // This is the existent horizontal align
    myTextFormat.align = TextFormatAlign.CENTER;

    // This is my simulated vertical align. Remember that the first character
    // is always a break line. In most cases it will be a negative value…
    myTextFormat.leading = -22;

    var myTextField:MyTextField = new MyTextField();
    myTextField.text = “Hello”;
    myTextField.setTextFormat(myTextFormat);

    I hope this will help to someone who needs vertical align in single line text using TextField.
    :-)

    Regards,
    Angel (from Córdoba-Argentina)

Leave a Reply

Your email address will not be published. Required fields are marked *