有個很方便的方法:
UIComponent#measureText( text:String ):TextLineMetrics
先看看官方說的:
Measures the specified text, assuming that it is displayed in a single-line UITextField using a UITextFormat determined by the styles of this UIComponent.
簡單來說,這個方法會根據你當下使用的文字樣式,測量一段文字的長寬高。舉例來說, “Taiwan” 這幾個字,在各種字體、字型大小設定下,顯示出來的結果當然不同(比如字體大小11pt時高度為21px; 14pt時高度為34px…) ,為了要得到正確的文字框數據,就可以運用該方法。
那麼,到底什麼時候會用到呢? 很多時候,在開發與TextField相關的自訂元件時,會大量地運用到,譬如 Button,裡頭的Label和icon要對齊,label的位置就利用了此方法測量出來,然後位移之。
看看原始碼,應該會常常看到這種寫法:
因為大寫W是最高的字, 小寫j是最低的字, 如此可以算出最大的文字框高度
measureText("Wj");
算出現有的文字框高度
measureText(textField.text);
UIComponent#measureText(text:String):TextLineMetrics
It is a very handy method for determining the bounds of a specific text. To illustrate, with different text format, the appearance of text must be different. In other words, the height, width and other values will be changed as well. Therefore, to make sure we get the correct and precise values of it, we can call this method to get a TextLineMetrics object, which provides all the properties. Given that object, we could update positions of components precisely.
For example, while the label of a button changes, we could measure it by
measureText(label)
or
to get a safe size of it, use following code:
measureText("Wj")
Here is a thing, the capital w and lowercase j are the latter with highest baseline and the lowest. That’s why Adobe developer often writes up code in this way.
FYI