由於文本測量在創建和配置文本字段時沒有將其添加到顯示列表中,因此文本測量值工作正常,因此您缺少以下信息。
訣竅是確保在完全配置TextField後設置「text」屬性LAST。給定所有先前配置的設置,設置「文本」屬性似乎最終確定了佈局。
您遇到的問題可能是您正在設置「文本」屬性,然後更改其他設置,如多行或embedFonts。當你這樣做時,getLineMetrics將不會返回正確的值。如果您然後設置「text」屬性並再次檢查getLineMetrics,則值將是正確的。請參閱此示例以及跟蹤語句後的註釋。
var tf:TextField = new TextField();
tf.defaultTextFormat = new TextFormat("Arial Black", 16, 0, false);
tf.embedFonts = true;
tf.text = "Hello"; //set text last
trace(tf.getLineMetrics(0).height); //Traces 22.55 (correct)
var tf2:TextField = new TextField();
tf2.defaultTextFormat = new TextFormat("Arial Black", 16, 0, false);
tf2.text = "Hello"; //set text first
tf2.embedFonts = true; //modify a property after setting text seems to make the TextField "dirty"
trace(tf2.getLineMetrics(0).height); //Traces 1.15 (incorrect)
var tf3:TextField = new TextField();
tf3.defaultTextFormat = new TextFormat("Arial Black", 16, 0, false);
tf3.text = "Hello";
tf3.embedFonts = true; //modifying a property after setting the text seems to make the TextField "dirty"
tf3.text = "Hello"; //setting the text again seems to fix the problem
trace(tf3.getLineMetrics(0).height); //Traces 22.15 (correct)
這裏的教訓是,您配置TextField的順序非常重要。例如,使用defaultTextFormat屬性記錄了這一點,您必須在設置文本之前設置該屬性,否則設置的新文本將不會選取defaultTextFormat。在這種情況下,如果您打開了embedFonts並且它使用了其他未嵌入的默認字體,則文本可能根本不顯示。因此,請確保先設置defaultTextFormat,配置其他屬性,並在調用getLineMetrics之前設置最後的「文本」。
這裏使用我創建的這個函數。它迫使你首先配置TextField的重要屬性(文本,類型,多行,可選,嵌入字體),然後後面的參數與TextFormat構造函數完全相同,順序相同。它確保您的屬性按正確的順序設置,文本最後分配的,它會向下降低文本字段創建一個說法:
public static function CreateTextField(text:String = "", type:String = null, multiline:Boolean = false, selectable:Boolean = true, embedFonts:Boolean = false, font:String=null, size:Object=null, color:Object=null, bold:Object=null, italic:Object=null, underline:Object=null, url:String=null, target:String=null, align:String=null, leftMargin:Object=null, rightMargin:Object=null, indent:Object=null, leading:Object=null):TextField
{
var tf:TextField = new TextField();
tf.defaultTextFormat = new TextFormat(font, size, color, bold, italic, underline, url, target, align, leftMargin, rightMargin, indent, leading);
tf.embedFonts = embedFonts;
tf.multiline = multiline;
tf.selectable = selectable;
tf.type = type;
tf.text = text; //setting text last ensures the text line metrics returns correct values
return tf;
}
當我在主時間軸中將代碼複製並粘貼到Flash CS4中時,我得不到相同的數字。我得到0,1.15,0 .. – MrB
然後你的字體沒有嵌入。你必須在圖書館中嵌入Arial Black。如果使用count爲零,那麼你必須檢查「export for actionscript」以確保字體實際上是嵌入的。沒有嵌入字體,你會看到0而不是22.55。 – Triynko