views:

150

answers:

1

I'm aware of textAlign property of the Text component. But it doesn't do what I'm trying to achieve:

I have a Text component which is 500x100 (the size does not change). The default font size is 80 px. The text, however, keeps changing. What I want is to resize the text to "fit" inside the textfield.

Let's say the text is changed to: "A quick brown fox jumped over the lazy dog". That would not fit inside the textfield, because the font size is too big. So how can the textsize be shrinked so that everything fits and nothing goes to the next line?

+1  A: 

Here you go (directly from Adobe):

Given a width in pixels and a maximum number of lines to display, the HeadlineTextField alters the font size to make the text fit the field. If the text is short the font size will be very large, creating a tabloid-style headline. If the text is long the font size will of course be smaller.

The HeadlineTextField.fitText() method shown below does the font sizing work:

public function fitText(msg:String, maxLines:uint = 1, toUpper:Boolean = false, targetWidth:Number = -1):uint
{
    this.text = toUpper ? msg.toUpperCase() : msg;

    if (targetWidth == -1)
    {
        targetWidth = this.width;
    }

    var pixelsPerChar:Number = targetWidth / msg.length;

    var pointSize:Number = Math.min(MAX_POINT_SIZE, Math.round(pixelsPerChar * 1.8 * maxLines));

    if (pointSize < 6)
    {
        // the point size is too small
        return pointSize;
    }

    this.changeSize(pointSize);

    if (this.numLines > maxLines)
    {
        return shrinkText(--pointSize, maxLines);
    }
    else
    {
        return growText(pointSize, maxLines);
    }
}

public function growText(pointSize:Number, maxLines:uint = 1):Number
{
    if (pointSize >= MAX_POINT_SIZE)
    {
        return pointSize;
    }

    this.changeSize(pointSize + 1);

    if (this.numLines > maxLines)
    {
        // set it back to the last size
        this.changeSize(pointSize);
        return pointSize;
    }
    else
    {
        return growText(pointSize + 1, maxLines);
    }
}

public function shrinkText(pointSize:Number, maxLines:uint=1):Number
{
    if (pointSize <= MIN_POINT_SIZE)
    {
        return pointSize;
    }

    this.changeSize(pointSize);

    if (this.numLines > maxLines)
    {
        return shrinkText(pointSize - 1, maxLines);
    }
    else
    {
        return pointSize;
    }
}
Todd Moses
Nice hidden treasure. Thanks! :)
Yeti