Search Unity

  1. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Question Shrink UI text background image to fit text

Discussion in 'UGUI & TextMesh Pro' started by hamstar, Aug 9, 2022.

  1. hamstar


    Sep 25, 2013
    I've asked this on Unity answers but not sure which place gets more traffic.

    I want to create UI text elements with backgrounds that resize to fit around the text. I've tried to follow guides which use vertical layout groups to achieve this. What I have at the moment partially works. The image and text resize as more text is added. But the height of the background image won't shrink below 110 (see top text).

    I can see that the preferred height of the background image is 110, but I'm not sure what determines this. When I try using a LayoutElement to change the Preferred Height, this breaks the auto-resizing behaviour that I want.

    If I use a LayoutElement on the image with Preferred Height set:

    The UI hierarchy is:

    Contents Container
    and Heading Background have a VerticalLayoutGroup components with settings:

    Does anyone know how I can change the preferred height of the background image while still having the background+text autosize to fit the text? Thanks!
  2. hamstar


    Sep 25, 2013
    Couldn't find any solutions for this, so used a workaround. I created a custom Image implementation that uses the layout group's (VerticalLayoutGroup) preferred height as the preferred height, rather than the image height.

    So the Image components on Heading Background and Detail Background are using this script:

    Code (CSharp):
    1.  public class ContentFitImage : Image
    2. {
    3.      public override float preferredHeight
    4.      {
    5.          get
    6.          {
    7.              if (TryGetComponent<LayoutGroup>(out var layoutGroup))
    8.              {
    9.                  return layoutGroup.preferredHeight;
    10.              }
    11.              return base.preferredHeight;
    12.          }
    13.      }
    14. }