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

标签 actionscript-3 textfield

我们试图获得一个 Rectangle ,它表示 TextField 中文本的精确*边界。

**尽可能准确。*

拍下这张图片:

使用我目前的知识,我可以像这样检索上面的 蓝色 矩形:

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

但是,我们需要尽可能接近 红色 矩形(我意识到会有细微的差异,因为字符随高度/高度而变化,并且需要有一个共同点)。

如何获得红色矩形(动态)?

我根据 Jacob Eggers 的以下答案设置了这个助手类,但是我总是得到 (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);
        }

    }
}

即使我用我正在寻找的颜色填充一小部分,我仍然会得到一个零大小的矩形:
bmd.fillRect(new Rectangle(0, 0, 30, 30), textField.textColor);

最佳答案

使用 BitmapData.draw,然后使用 getColorBoundsRect 获取黑色文本的边界。
像这样的东西:

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);

编辑 很好地捕获了有关文本颜色的 zachzurn。我添加了一条评论来澄清。

关于actionscript-3 - AS3 : How can I get the top-left and exact width and height of some text in a text field?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9596529/

相关文章:

actionscript-3 - 为 actionscript-3 中的 2d Flash 游戏优化我的动态背景引擎

ios - StageWebViewBridge 加载包含的资源

flash - Flash:是否可以录制用户语音并对其进行操作?

flutter - onChange TextField 移动光标以开始 flutter

java - 如何使用 JButton 删除 textField 中某个字符的所有实例?

textfield - 在 TextField Jetpack Compose 中用户输入文本后显示尾随图标

actionscript-3 - Actionscript从字符串数组加载/调用声音

flash - 检查值是否为数字

swift - 元组 Void (aka ()) 的值没有成员 "isSuperset"

jasper-reports - Jasper Reports - 水平对齐动态文本字段及其标签