问题
We are trying to get a Rectangle
that represents the exact* boundary of the text in a TextField
.
**Exact as possible.*
Take this image:

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);
回答1:
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.
回答2:
Try this, although is not going to be perfect:
var textRect:Rectangle = field.getBounds(field.parent);
Or try this (there's an example there you can try out):
http://blog.stroep.nl/2009/11/getbitmapbounds/
来源:https://stackoverflow.com/questions/9596529/as3-how-can-i-get-the-top-left-and-exact-width-and-height-of-some-text-in-a-tex