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

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

** As accurate as possible. *

Take this image:

enter image description here

Using my current knowledge, I can extract the blue rectangle above:

 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 understand that there will be slight differences, because the characters change with / height, and there should be a common base).

How can I get a red rectangle (dynamically)?


I installed this helper class based on the answer below, Jacob Eggers, however I always get the result (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 the 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); 
+4
source share
2 answers

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

 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 well catch zachzurn about text color. I added a comment to clarify.

+5
source

Try this, although it will not be ideal:

 var textRect:Rectangle = field.getBounds(field.parent); 

Or try this (there is an example there that you can try):

http://blog.stroep.nl/2009/11/getbitmapbounds/

+1
source

Source: https://habr.com/ru/post/1400156/


All Articles