更改文本大小并保持文本垂直居中

Change Text Size and Keep Text Vertically Centered

如何更改动态文本字段的文本大小并使文本保持在基线上?当我调用此函数并影响文本大小时,随着文本大小的减小,文本在文本字段中逐渐向上上升。

function autoFormatSize(myTextField)
{
    if (! textFormat && ! textSize)
    {
        var textFormat:TextFormat = new TextFormat();
        var textSize:int = new int();
    }
    textFormat.size = 50;
    textSize = 50;
    for (var i=0; myTextField.textWidth>myTextField.width-10; i++)
    {
        textSize--;
        textFormat.size = textSize;
        myTextField.setTextFormat(textFormat);
    }
}

更新

这是我正在尝试做的事情的直观说明:

考虑到您的评论,您是否考虑过改用 autoSize?类似于:

var tf:TextField = yourTextField; //on timeline

tf.autoSize = TextFieldAutoSize.LEFT;
var textFormat:TextFormat = new TextFormat();
textFormat.size = 14;
var oldY:Number = tf.y + tf.height;

tf.setTextFormat(textFormat);
tf.y = oldY - tf.height;

使用textHeight获取文本的高度。以下是将文本字段放置在一行 mc 上的方法:

var tfMain: TextFormat = new TextFormat();
tfMain.size = 100;
tMain.setTextFormat(tfMain);
trace(tMain.textHeight);            
tMain.y = Math.ceil(mcUnderline.y - tMain.textHeight);

使用 ceil 确保它在 x 上。

创建一个 Sprite 并将其添加到舞台上,然后根据 Sprite 对齐您的 TexField。如下编码

with(bg.graphics) {
        clear();
        beginFill(0xeeeeee, 1);
        lineStyle(1, 0x999999);
        drawRect(0, 0, 200, 30);
        endFill();
    }
    txt.x = bg.x + bg.width/2 - txt.width/2;
    txt.y = bg.y + bg.height/2 - txt.height/2;

要将文本调整到文本字段,您必须为文本的每一侧考虑一个 2px gutter,因此您的函数可以是这样的:

function autoFormatSize(myTextField)
{
    var gutter:int = 2 * 2;  // 4px

    var textSize:int = 50;
    var textFormat:TextFormat = new TextFormat();
        textFormat.size = textSize;

    for (var i:int = 0; myTextField.textWidth > myTextField.width - gutter; i++)
    {
        textSize --;
        textFormat.size = textSize;
        myTextField.setTextFormat(textFormat);
    }

    myTextField.height = myTextField.textHeight + gutter;

}

希望能帮到你。