- FLASH AS3多行不换行自动适应宽度的文本框,取得文本实际宽度: [返回文章列表]
发表于: 2009-6-12 626人(次)浏览
AS3 在做多行不换行自动适应宽度的文本框时,可以这样取得文本实际宽度:
_txt.width=_txt.getCharBoundaries(_txt.length-1).width+_txt.getCharBoundaries(_txt.length-1).x+5
关键方法:getCharBoundaries
getCharBoundaries()方法
public function getCharBoundaries(charIndex:int):Rectangle
Rectangle — 一个矩形,具有定义字符边框的 x 和 y 最小值和最大值。
下面是抄的AS3的帮助文档上的例子
示例
在下面的示例中,使用 getCharBoundaries() 方法标记(产生聚光灯照射效果)用户选择的字符。
该类定义了 spotlight Shape 对象,该对象用于在每个所选的字符周围绘制一个矩形。 当用户单击 myTextField 文本字段时,将调用 clickHandler() 方法。
在 clickHandler() 方法中,getCharIndexAtPoint() 方法基于鼠标单击的 localX 和 localY 坐标来获取所单击的字符的索引,此坐标相对于包含它的 Sprite。 如果该点(鼠标单击)不在任何字符上,getCharIndexAtPoint() 方法将返回 -1。 由于文本字段可能比文本大,因此,应检查返回的整数 (index) 以确保用户单击了某个字符。 getCharBoundaries() 还使用 index 整数来获取用于保存字符边界的 Rectangle 对象。 clear() 方法将清除以前显示的所有 spotlight Shape 对象。 将使用返回的 frame 矩形的 x 和 y 坐标,在字符位置生成一个字符宽度和高度边界大小的新矩形,字符位置是相对于 (10, 10) 坐标的偏移。 若要产生用聚光灯照射字符的效果,请使用黄色填充 spotlight Shape 对象,并将不透明度设置为 35%,以便能够看到字符。 请注意,空格也被视为字符。
package {
import flash.display.Sprite;
import flash.events.MouseEvent;
import flash.text.TextField;
import flash.geom.Rectangle;
import flash.events.MouseEvent;
import flash.text.TextFieldAutoSize;
import flash.display.Shape;
public class TextField_getCharBoundariesExample extends Sprite
{
private var myTextField:TextField = new TextField();
private var spotlight:Shape = new Shape();
public function TextField_getCharBoundariesExample() {
myTextField.x = 10;
myTextField.y = 10;
myTextField.border = true;
myTextField.selectable = false;
myTextField.autoSize = TextFieldAutoSize.LEFT;
myTextField.text = "Selected a character from this text by clicking on it."
myTextField.addEventListener(MouseEvent.CLICK, clickHandler);
this.addChild(myTextField);
this.addChild(spotlight);
}
private function clickHandler (e:MouseEvent):void {
var index:int = myTextField.getCharIndexAtPoint(e.localX, e.localY);
if (index != -1) {
var frame:Rectangle = myTextField.getCharBoundaries(index);
spotlight.graphics.clear();
spotlight.graphics.beginFill(0xFFFF00, .35);
spotlight.graphics.drawRect((frame.x + 10), (frame.y + 10), frame.width, frame.height);
spotlight.graphics.endFill();
}
}
}
}
翼 www.ourbrander.com
FLASH AS3多行不换行自动适应宽度的文本框,取得文本实际宽度:
[返回文章列表]