Also known as:
- finding the position of a character in a dynamic textfield with embedded fonts using actionscript 2
One of current projects involves some texteffects and I am loath to do anything on the timeline that can be done quicker by code. So my basic idea was (keeping the designer in me happy):
Doing the design stuff at design time on stage:
- put a dynamic textfield on stage
- apply a font, fontsize, color, anti-aliasing
- apply effects such as dropshadow, glow etc to make it look good
Doing the animate stuff at runtime through code:
- break apart the stage textfield into little textfields that I could animate
At this point I was already thinking about converting the stage textfields to bitmaps but found I was thinking about optimising things too early, so back to KISS, basic principles first.
Silly me, I thought it would be easy in actionscript 2 to get the position of a character in a dynamic textfield. As in:
but apparently no such thing exists. Ofcourse if you have a monospaced font, there are other ways to accomplish this, but this solution works for both monospaced and other fonts.
Although in actionscript 3 there is something like getCharIndexAtPoint, that is not quite what I needed.
Using a trick I managed to implement it in actionscript 2. Note that this is still under development, being researched etc, so it’s not a general I-will-work-everytime-approach. Anyway the basic principle is this:
- create a bitmap as large as your textfield
- create two textformats derivatives of your textfield’s textformat and set the textcolor of one to white, the other to black
- now loop over the characters in your textfield (i = 0 to textfield.length), and:
- apply first the white textformat to everything, then applying the black textformat to the range (i, i+1)
(basically in every iteration of the loop you set everything to white except the character whose position you are looking for)
- copy the textfield to the bitmap
- perform a getColorBoundsRect on the bitmap and voila an approximation of the character position
And I say approximation since it’s seems to be off by a couple of pixels, but close enough to be usuable. In addition large amounts of text will slow down the process considerably and small font sizes wreak havoc, but it’s good enough:
Download the prototype here Texteffect 1 (608 downloads) , it includes the Greensock Tween classes, but you can use anything you like.