Skip to main content
Inspiring
April 22, 2023
Answered

Position the center of a TextField

  • April 22, 2023
  • 2 replies
  • 703 views

Is there a way to position a TextField based on the vertical and horizontal center of its string? I gather the .myText.width and myText.height can be read, but the native origin seems to be in the upper left, as shown here:

so it will take trig todecide the offset to the center. Is there a native function to position at the actual center?

    This topic has been closed for replies.
    Correct answer hclmed0

    Very kind. That works. I had tried substracting half the width and height before, but it seems:

    txt.autoSize = TextFieldAutoSize.CENTER;

    makes the difference.

    Thank you.

    2 replies

    JoãoCésar17023019
    Community Expert
    Community Expert
    April 22, 2023

    Hi.

     

    You can also use the textWidth and textHeight properties to get the actual size of the text. Then you can add or remove half of these values to position the TextField in the center.

     

    Regards,

    JC

    hclmed0Author
    Inspiring
    April 22, 2023

    That also seems to work since textWidth and textHeight are smaller and, I assume, more exact than width and height. Thanks.

    Vladin M. Mitov
    Inspiring
    April 22, 2023
    // AS3 code
    var calculatedLocation:Object = {x:100, y:100}; // ***
    var txt:TextField = new TextField();
    	txt.type = TextFieldType.DYNAMIC;
    	txt.autoSize = TextFieldAutoSize.CENTER;
    	txt.border = true; // ***
    	txt.text = "TEST"; // ***
    txt.x = calculatedLocation.x - txt.width / 2;
    txt.y = calculatedLocation.y - txt.height / 2;
    addChild( txt );

     

    - Vlad: UX and graphic design, Flash user since 1998Member of Flanimate Power Tools team - extensions for character animation
    hclmed0AuthorCorrect answer
    Inspiring
    April 22, 2023

    Very kind. That works. I had tried substracting half the width and height before, but it seems:

    txt.autoSize = TextFieldAutoSize.CENTER;

    makes the difference.

    Thank you.