I'm building a small Flex UI component that displays a colored square next to a label of text. I want to be able to specify a size for the square and internally adjust the label's properties such that the line height matches the square and the text is vertically centered w开发者_开发知识库ith respect to the square.
At the moment, I'm using mx.controls.Label
for the text. Setting the fontSize
style to the square's size does not work, the label then becomes too big. After tracing a couple of values in the debugger, I found that
- the line height of the internal text field (sum of the
ascent
anddescent
properties of theTextFieldMetrics
object obtained throughgetTextFieldMetircs()
) seems to end up about 120% of what I specify a s font size. - there's a default "leading" of 2 pixels that I can not change directly at the
Label
level, this adds to the overall height of the internal text field (getTextFieldMetrics().height
) - the height of the
Label
component then is an additional 5 pixels larger than that, I don't know where those come from.
My current solution is to set the font size to Math.round((iconSize - 2) / 1.2)
but while this works out OK-ish, it seems unsatisfactory. Is there a more reliable and more straightforward approach to this?
Meanwhile, I have experimented a little with using a UITextField
instead of a Label
and that lead me to an interesting observation: Both components seem to do some internal scaling and resizing based on the font size, so that the rendered text will always have some padding around it. The numbers returned from getTextLineMetrics()
are different for the same font size when using either component.
The UITextField
renders the text such that the total pixel height of the component fits the number specified as fontSize
, which in turn makes the actual text slightly smaller (about 2-4 pixels). Also, it seems to ignore when you set leading
to zero.
The Label
fits the resulting line height to what was specified as fontSize
, making the component larger than that (by approximately 5 pixels).
While this is certainly confusing to me, I'm satisfied with using the Label
component and positioning it such that the excess whitespace on top and bottom is clipped by the parent component and doesn't matter anymore. The text then has the right size. I'm centering vertically, which is easy, but it would also work to use the numbers from getTextLineMetrics()
for more sophisticated positioning.
精彩评论