asdg>> technotes>> how do i measure the width of on-screen text?

Version: Flash 5, Flash MX
Date Added: October 1, 2001
Last Updated: December 31, 2002

In Flash MX, you can measure the width or height of a string of text via the TextFormat.getTextExtent() method, which is described in the Language Reference of ASDG2.

In Flash 5 ActionScript and older, there is no built-in tool to measure the width of a string displayed on screen. This means we have to take matters into our own hands. Determining the width of a string displayed in a fixed-width font is easy. The characters in a fixed-width font (e.g., courier, lucida console) are all the same width. To determine the width of a character we draw a line under it in the authoring tool and check the line's width in the Info panel. We then multiply that width by the number of characters in our string. For example:

var charWidth = 8;
var theString = "hello world";
var strWidth = theString.length * charWidth;

Determining the width of a string displayed in a proportional-width font is slightly trickier because the characters in a proportional-width font vary in width. However, we can use the same basic approach: find the width of certain representative characters in the font, and use them to total the approximate width of the whole string. For lowercase letters, I use the following character groupings (mostly to save the hassle of measuring all the characters in a font):

  1. i, l, j
  2. f, t, r, space
  3. m, w
  4. all other chars

If you were anal or had more time, you could alternatively store each individual character's width in an array and total any string's width by mapping charCodeAt() return values to the array's elements. I'll leave that for you to try.

Here's a sample function that measures the width of a lowercase string based on the above character width groupings: