-
Notifications
You must be signed in to change notification settings - Fork 0
/
AspectRatio.cs
55 lines (42 loc) · 1.21 KB
/
AspectRatio.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
using UnityEngine;
using UnityEngine.UI;
[RequireComponent(typeof(Camera))]
public class AspectRatio : MonoBehaviour
{
public float targetAspectRatio = 16f / 9f; // The desired aspect ratio, e.g., 16:9
private Camera _camera;
void Start()
{
_camera = GetComponent<Camera>();
}
void SetCameraAspect()
{
float windowAspect = (float)Screen.width / Screen.height;
float scaleHeight = windowAspect / targetAspectRatio;
if (scaleHeight < 1.0f)
{
// Letterboxing
Rect rect = _camera.rect;
rect.width = 1.0f;
rect.height = scaleHeight;
rect.x = 0;
rect.y = (1.0f - scaleHeight) / 2.0f;
_camera.rect = rect;
}
else
{
// Pillarboxing
float scaleWidth = 1.0f / scaleHeight;
Rect rect = _camera.rect;
rect.width = scaleWidth;
rect.height = 1.0f;
rect.x = (1.0f - scaleWidth) / 2.0f;
rect.y = 0;
_camera.rect = rect;
}
}
private void Update()
{
SetCameraAspect();
}
}