Version: 2023.2
언어: 한국어
여러 창 사이에 드래그 앤 드롭 목록과 트리 뷰 생성
UI 스타일링

Create an aspect ratio custom control

버전: 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.

개요 예시

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.

선행 조건

이 가이드는 Unity 에디터, UI 툴킷, C# 스크립팅에 익숙한 개발자용입니다.시작하기 전에 먼저 다음을 숙지하십시오.

커스텀 컨트롤 클래스 만들기

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. 임의의 템플릿을 사용하여 Unity 프로젝트를 생성합니다.
  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. 플레이 모드를 시작합니다.
  5. Change the aspect ratios to a wider display ratio, such as 16:9. The custom control adds padding to the left and right.

추가 리소스

여러 창 사이에 드래그 앤 드롭 목록과 트리 뷰 생성
UI 스타일링