在开头,先首说一下TextField中单行文字空间是怎样的。图如下

wKioL1Wl9GWAd2KnAADxyU5Q_4E808.jpg

从图中可以看到,当为文字设定像素大小时,我们都可以从TextField中的文字空间信息取得两个信息Ascent与Descent,文字空间与边距的2px一般是固定的。所以如果我们想在TextField中单行文字垂直居中的话,可以这样设定TextField的高度为Ascent+Descent+4px。具体在as3.0中的个人实现代码实例如下:

package
{
	import fl.controls.Label;
	import fl.controls.TextInput;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.text.TextField;
	import flash.text.TextFormat;
	import flash.text.TextFieldType;
	import flash.text.StyleSheet;
	import flash.text.TextLineMetrics;
	
	[SWF(backgroundColor='0xFFFFFF',width='400',height='300',frameRate='29')]
	public class Main extends Sprite 
	{
		
		private var userNameInfo:TextField;
		
		public function Main() 
		{
			this.init();
			this.doDrawInit();
		}
		
		private function init():void {
			this.userNameInfo = new TextField();
			this.userNameInfo.width = 300;
			
			this.userNameInfo.type = TextFieldType.INPUT;
			
			this.userNameInfo.background = true;
			this.userNameInfo.backgroundColor = 0xeeeeee;
			this.userNameInfo.x = 10;
			this.userNameInfo.y = 10;
			
			var newStyle:StyleSheet = new StyleSheet();
			var styleObj:Object = new Object();
            styleObj.fontWeight = "bold";
            styleObj.color = "#660066";
			styleObj.fontSize  = 30;
			styleObj.fontStyle = "normal"; //可识别的值为 normal 和 italic。
			styleObj.display = "block";//受支持的值为 inline、block 和 none。
			styleObj.textAlign = "center";//可识别的值为 left、center、right 和 justify。
            newStyle.setStyle(".defStyle", styleObj);

			this.userNameInfo.styleSheet=newStyle;
			this.userNameInfo.htmlText = '<span class="defStyle">用户名</span>';
			this.doDrawInit();
			
			
			var textinfo :TextLineMetrics = this.userNameInfo.getLineMetrics(0);
			
			this.userNameInfo.height = textinfo.ascent + textinfo.descent + 4;
			
		}
		
		private function doDrawInit():void {
			this.addChild(this.userNameInfo);
		}
		
	}
	
}

大家可以看到this.userNameInfo.height = textinfo.ascent + textinfo.descent + 4行,这行是重点,正是采取之前的方式来设定TextField对象的高度。在执行这行之前,我们首先要使用TextField中的getLineMetrics方法来获得TextField实例的度量空间,这样才能得到单行文字的Ascent及Descent。所以主要作用的两行为如下:

	var textinfo :TextLineMetrics = this.userNameInfo.getLineMetrics(0);
			
	this.userNameInfo.height = textinfo.ascent + textinfo.descent + 4;



上面程序的执行结果如下:

wKioL1Wl-t3ycwIoAACXD1GwCNg624.jpg



扩展思路:

  如果我们想做一个文字垂直居中的Label,一般我们只要把TextField添加到一个Sprite中,然后把TextField的高度按上面的方法进行设定,根据TextField高度再在Sprite把TextField的位置居中调整。这样一个文字可垂直居中的Label就做成了。