Version: 2023.2
Create a drag-and-drop list and tree views between windows
Style UI

Create an aspect ratio custom control

Version: 2023.2+

The aspect ratio is the ratio between the width and height of the display. The aspect ratio is used to maintain the proportions of the display. For example, if you have a 4:3 aspect ratio, then the display is 4 pixels wide for every 3 pixels in height. If you have a 16:9 aspect ratio, then the display is 16 pixels wide for every 9 pixels in height.

Example overview

This example creates a custom control that maintains a specified aspect ratio of its child elements. For demonstration purposes, the custom control adds paddings to the left and right if the display ratio is wider, pushing the “central” items to fit into the aspect ratio.

Aspect ratio example
Aspect ratio example

You can find the completed files that this example creates in this GitHub repository.

先决条件

This guide is for developers familiar with the Unity Editor, UI Toolkit, and C# scripting. Before you start, get familiar with the following:

Create the custom control class

Create a C# class that inherits from VisualElement with two attributes: width and height. The width and height attributes are used to calculate the aspect ratio.

  1. Create a Unity project with any template.
  2. Create a C# script named AspectRatio.cs with the following content:

[!code-cs]

Use the custom control

Add the custom control in UI Builder. Set the width and height attributes to the desired aspect ratio. Add a child element to the custom control. The child element is the element that you want to maintain the aspect ratio.

  1. Create a UXML file named AspectRatio.uxml.
  2. Double-click the AspectRatio.uxml file to open it in UI Builder.
  3. In the Library panel, select the Project tab.
  4. Drag AspectRatio from the Project tab to the Hierarchy panel.
  5. In the Inspector panel, set a value for the width. For example, set the value to 4.
  6. Set a value for the height. For example, set the value to 3.
  7. Set the background color to Yellow.
  8. In the Hierarchy panel, add a VisualElment as the child element to the AspectRatio element.
  9. Set the background color of the child element to Green.
  10. Set the flow-grow of the child element to 1.
  11. Save the UXML file. The finished UXML file looks like this:

[!code-xml]

Test the custom control

Test the custom control in a scene, and see how it behaves when you change the aspect ratio.

  1. From the menu, select GameObject > UI Toolkit > UIDocument.
  2. In the Hierarchy window, select UIDocument.
  3. In the Inspector window, set the UI Document > Source Asset to AspectRatio.uxml.
  4. Enter Play mode.
  5. Change the aspect ratios to a wider display ratio, such as 16:9. The custom control adds padding to the left and right.

其他资源

Create a drag-and-drop list and tree views between windows
Style UI