转自 http://hi.baidu.com/ouyang80/blog/item/777309fd7178661309244da8.html
这是我从一个老外程序里调出来的, 但是有一个缺陷, 当文字个数小于 2 个时, 字体太大, 反而不能自适应了, 请各位看官支招
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute"
creationComplete="init()">
<mx:Script>
<![CDATA[
import mx.core.UIComponent;
private var _textField:TextField;
private function init():void
{
_textField = new TextField;
_textField.text = "匹客"; // 匹客吧 Professi" // 改这里的文字内容, 得到不同适应结果
_textField.width = can.width;
_textField.height = can.height;
_textField.multiline = true;
_textField.wordWrap = true;
setTextSize();
var ui:UIComponent = new UIComponent;
ui.addChild(_textField);
can.addChild(ui);
}
//
private function setTextSize():void
{
//
var mode:String = "none";
var sameHeightTwice:Boolean = false;
var lastHeight:Number = 0;
var currentSize:Number = 12;
var format:TextFormat = this._textField.getTextFormat();
while(this._textField.textHeight < this._textField.height - 4)
{
if(this._textField.textHeight == lastHeight)
{
//sometimes if the font size is increased by one, the textHeight won't change
//but then it will change when it is increased again.
//to combat this problem, we need to check if the height has matched twice!
if(sameHeightTwice) break;
sameHeightTwice = true;
}
else sameHeightTwice = false;
lastHeight = this._textField.textHeight;
format.size = currentSize += 1;
this._textField.setTextFormat(format);
//special case for partial mode
if(mode == "partial" && this._textField.numLines > 1)
{
//minimize words being broken into multiple lines!
for(var i:int = 1; i < this._textField.numLines; i++)
{
var lineOffset:int = this._textField.getLineOffset(i);
//check for a space or dash at the end of the previous line
var beginningOfLine:String = this._textField.text.charAt(lineOffset);
var endOfPreviousLine:String = this._textField.text.charAt(lineOffset - 1);
if(endOfPreviousLine != " " && endOfPreviousLine != "-" && this._textField.numLines > 1 && currentSize > 1)
{
format.size = currentSize -= 1;
this._textField.setTextFormat(format);
return;
}
}
}
}
//decrease to fit. stop at size == 1
while(currentSize > 1 && this._textField.textHeight > this._textField.height - 4)
{
format.size = currentSize -= 1;
this._textField.setTextFormat(format);
}
}
]]>
</mx:Script>
<mx:Canvas id="can" width="30" height="300" backgroundColor="#f0f0f0" x="10" y ="10">
</mx:Canvas>
</mx:Application>