Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AS3: How can I get the top-left and exact width and height of some text in a text field?

We are trying to get a Rectangle that represents the exact* boundary of the text in a TextField.

**Exact as possible.*

Take this image:

enter image description here

Using my current knowledge, I can retrieve the blue rectangle above like so:

var textRect:Rectangle = new Rectangle(
    field.x,
    field.y,
    field.textWidth,
    field.textHeight
);

However, we need to get as close as possible to the red rectangle (I realize there will be minor differences because characters have varied with/height and there will need to be a common ground).

How can I get the red rectangle (dynamically)?


I set up this helper class based on the answer below by Jacob Eggers, however I always get a result of (x=0, y=0, w=0, h=0)..

package
{
    import flash.display.BitmapData;
    import flash.text.TextField;
    import flash.geom.Rectangle;

    public class TextBounds
    {

        public static function getTextBounds(textField:TextField):Rectangle
        {
            var curtainColor:uint = 0x00FF00;
            var bmd:BitmapData = new BitmapData(textField.width, textField.height, false, curtainColor);
            bmd.draw(textField);

            return bmd.getColorBoundsRect(curtainColor, textField.textColor, true);
        }

    }
}

Even if I fill a small section with the color I'm looking for I still get a zero-sized rectangle:

bmd.fillRect(new Rectangle(0, 0, 30, 30), textField.textColor);
like image 202
Marty Avatar asked Mar 07 '12 05:03

Marty


1 Answers

Use BitmapData.draw, and then use getColorBoundsRect to get the bounds of the black text. Something like this:

import flash.display.Bitmap;
import flash.display.BitmapData;

var bmd:BitmapData = new BitmapData(80, 40, false, 0xFFFFFF);
bmd.draw(tf)

var maskColor:uint = 0xFFFFFF; 
var color:uint = 0x000000;  //the color of the text
var tfBounds:Rectangle = bmd.getColorBoundsRect(maskColor, color, true);
trace(tfBounds);

edit good catch zachzurn about the text color. I added a comment to clarify.

like image 164
Jacob Eggers Avatar answered Sep 28 '22 01:09

Jacob Eggers