Timmy
Timmy

Reputation: 12828

Automatically Resized Sprite in Actionscript 3

I'm using AS3 and I created a popup box as such:

        var s:Sprite = new Sprite();

        var shape:Shape = new Shape();
        shape.name = "HitArea";
        s.addChild( shape );

        shape.graphics.lineStyle( 4, 0xFFFFFF, 1 );
        shape.graphics.beginFill( 0xFFFFFF ); 
        shape.graphics.drawRoundRect( 0, 0, 200, 30, 10, 10 );

        var text:TextField = new TextField();
        text.text = "";
        text.autoSize = TextFieldAutoSize.CENTER;
        text.name = "Text";
        text.x = 100;
        text.y = 10;
        s.addChild( text );

        return s;

Which creates a 200 x 30 box that serves as an error box. The text sometimes goes outside the box though, as I use

        ( s.getChildByName( 'Text' ) as TextField ).text = "Text here";

how do I fit the box to the text? Or is there a better alternative?

Upvotes: 1

Views: 1004

Answers (1)

LiraNuna
LiraNuna

Reputation: 67261

How about setting the size after setting the text?

    var s:Sprite = new Sprite();

    var text:TextField = new TextField();
    text.text = "";
    text.autoSize = TextFieldAutoSize.CENTER;
    text.name = "Text";
/*  // Not yet
    text.x = 100;
    text.y = 10;
*/  s.addChild( text );

    // Create the shape based on text's size
    var shape:Shape = new Shape();
    shape.name = "HitArea";
    s.addChild( shape );
    shape.graphics.lineStyle(4, 0xFFFFFF, 1);
    shape.graphics.beginFill(0xFFFFFF);
    shape.graphics.drawRoundRect(0, 0, text.width + 32, text.height + 32, 10, 10); // Plus padding

    // Now adjust the text's position to the box's center
    text.x = (s.width  - text.width ) / 2;
    text.y = (s.height - text.height) / 2;

    return s;

That way the box will scale with the text no matter how big it is.

Upvotes: 1

Related Questions