Search Unity

Width of Label

Discussion in 'UI Toolkit' started by cecarlsen, Aug 22, 2019.

  1. cecarlsen

    cecarlsen

    Joined:
    Jun 30, 2006
    Posts:
    864
    When I change the text of a Label the layout is not immediately updated and so resolvedStyle will still contain the previous size. One could subscribe to GeometryChanged and wait for the layout to update but this complicates the code. How can I pre-calculate how big the label will become?

    This is not precise. Perhaps because characterinfo works in integers.

    Code (CSharp):
    1. CharacterInfo info;
    2. IResolvedStyle style = label.resolvedStyle;
    3. Font font = style.unityFont;
    4. float labelWidth = style.paddingLeft + style.paddingRight;
    5. for( int i = 0; i < text.Length; i++ ) {
    6.     font.GetCharacterInfo( text[i], out info, (int) style.fontSize, style.unityFontStyleAndWeight );
    7.     labelWidth += info.advance;
    8. }
     
  2. jonathanma_unity

    jonathanma_unity

    Unity Technologies

    Joined:
    Jan 7, 2019
    Posts:
    229
  3. cecarlsen

    cecarlsen

    Joined:
    Jun 30, 2006
    Posts:
    864
    Perfect, thank you. I missed that one.
     
  4. dyamanoha_

    dyamanoha_

    Joined:
    Mar 17, 2013
    Posts:
    87
    Sorry to resurrect this, but what if you have a container containing a label among other things and you need the width of the entire container after a label change (or after making other size-related uss changes within the container)?
     
  5. cpalma-unity

    cpalma-unity

    Unity Technologies

    Joined:
    Nov 30, 2020
    Posts:
    110
    In that case I would recommend to register to GeometryChanged in the container and then get resolvedStyle.width
     
  6. dyamanoha_

    dyamanoha_

    Joined:
    Mar 17, 2013
    Posts:
    87
    Gotcha that makes sense
     
    Last edited: May 30, 2023