Might seem like an odd thing to start off a blog with, but hey – you’ve got to start somewhere. I’m no Flash rockstar, but this seemed like a pretty common usecase and had been bugging me for a while. I needed to measure the size of some text before rendering it to the stage, in AS2. There’s me thinking that using
would give me a reliable figure.
It seems like a reasonable method of solving the problem: Measure the text, then do whatever you need with the result (fit your text to a box, for example.) Unfortunately, it doesn’t really pan out. The values returned in the Object you get back differ between Flash Player version, platform and browser. Great! Apparently some Mac player versions return the value in twips, and not pixels, too.
The strangest variation I found was that the same platform, browser and player gave different values depending on whether the font was installed or not, even though the font was embedded. I’m guessing it’s possible that Flash could be using the metrics in the installed font if available, which are correct, whereas the embedded ones are somehow wrong. A theory that I have no hope of proving, but a theory nonetheless. (I’ve had similar problems with sIFR before.)
The result wasn’t quite as bad as just using
instead, but it’s getting that way.
// Returns values incorrect by ~10% varying
// between platform and browser
At this point I was considering refactoring the project to use AS3, which has a
method which I hoped would fix everything. But that would require a fair amount of hassle, so I tried autosizing the TextField and measuring that. It didn’t want to know, and soundly ignored any kind of sizing I tried to set. Cheers. However, I finally discovered non-obvious textWidth and textHeight properties of the textField, which seem to give the right values. So the steps are to measure some text are:
- Create an invisible text field (or use an existing one) with the appropriate textFormat
- Set the text in the field to the phrase to measure
- Use textWidth and textHeight to get the dimensions you need
And finally, some (untested) AS2 code:
// Assumes textField with instance name 'field' on the stage
textFormat = new TextFormat("Verdana", 16, 0xffffff);
field.setText("I am the ruler of measuring text");
trace("Width of text is: " + field.textWidth + ", and height is: "
You get the idea. Until next time…