Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Question Scaling an VisualElement to preserve background aspect ratio

Discussion in 'UI Toolkit' started by www4, May 26, 2023.

  1. www4

    www4

    Joined:
    May 17, 2014
    Posts:
    2
    Hi,
    I'm struggling a bit with what I thought would be a simple task. I want to scale this VisualElement in a container so that it takes up 100% height and just as much width as needed to preserve aspect ratio.

    upload_2023-5-26_2-21-23.png

    This is the intended result that I accomplished by hardcoding the pixel size, but as I want the image to be resizable this isn't satisfactory. Here is my UXML code:

    Code (CSharp):
    1. <ui:VisualElement name="top-group" style="flex-grow: 1; padding-left: 40px; padding-right: 40px; padding-top: 40px; padding-bottom: 20px; flex-direction: row; justify-content: flex-start; align-items: stretch;">
    2.         <ui:VisualElement name="profile-picture" style="background-image: url(<link>); flex-shrink: 0; height: 100%; width: auto; -unity-background-scale-mode: scale-to-fit; flex-grow: 0;" />
    3.  </ui:VisualElement>
    Any help comes highly appreciated :)
     
  2. spiney199

    spiney199

    Joined:
    Feb 11, 2021
    Posts:
    5,769
    You should only need to set
    flex-grow: 1
    and so long as the parent container is organising its children via
    flex-direction: column
    it should grow to fill out as much vertical space as it can.

    Otherwise setting its height to 100% as you've done will make sure it grows to fill out all vertical space too.
     
  3. www4

    www4

    Joined:
    May 17, 2014
    Posts:
    2
    The thing is I don't want it to take all space that it can in all directions. This element's container is
    flex-direction: row
    , so I want it to take 100% vertical space, but only as much horizontal space as it needs to maintain aspect ratio. If I set grow to 1, it will take up as much space as it can horizontally, which is undesirable for me.
     
  4. jwinn

    jwinn

    Joined:
    Sep 1, 2012
    Posts:
    88
    I want to scale this VisualElement in a container so that it takes up 100% height and just as much width as needed to preserve aspect ratio.

    This is almost exactly the same problem I was trying to solve yesterday. Unity needs to add support for the Yoga layout engine's aspect-ratio. There's some more discussion in this thread. Right now it looks like code is needed when you want a VisualElement to be 100% height and a dynamic width that keeps the aspect ratio (there are at least two GitHub links to scripts there that should work as a stop-gap solution).
     
    Last edited: May 27, 2023
    www4 likes this.