Skip to content

Commit f29c2df

Browse files
committed
Add script to stetch elements to screen size
1 parent 441fb04 commit f29c2df

File tree

2 files changed

+102
-0
lines changed

2 files changed

+102
-0
lines changed

Runtime/StretchToScreenSize.cs

Lines changed: 91 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,91 @@
1+
using UnityEngine;
2+
3+
namespace Zigurous.UI
4+
{
5+
/// <summary>
6+
/// Stretches a UI element to the screen size.
7+
/// </summary>
8+
[RequireComponent(typeof(RectTransform))]
9+
public sealed class StretchToScreenSize : MonoBehaviour
10+
{
11+
/// <summary>
12+
/// The RectTransform component of the object.
13+
/// </summary>
14+
private RectTransform _rectTransform;
15+
16+
/// <summary>
17+
/// Stretches the width of the RectTransform to match the screen width.
18+
/// </summary>
19+
[Tooltip("Stretches the width of the RectTransform to match the screen width.")]
20+
public bool stretchWidth = true;
21+
22+
/// <summary>
23+
/// Stretches the height of the RectTransform to match the screen height.
24+
/// </summary>
25+
[Tooltip("Stretches the height of the RectTransform to match the screen height.")]
26+
public bool stretchHeight = true;
27+
28+
private void Awake()
29+
{
30+
_rectTransform = GetComponent<RectTransform>();
31+
}
32+
33+
private void Start()
34+
{
35+
ScreenSizeListener.Instance.resized += OnScreenResize;
36+
}
37+
38+
private void OnDestroy()
39+
{
40+
if (ScreenSizeListener.HasInstance) {
41+
ScreenSizeListener.Instance.resized -= OnScreenResize;
42+
}
43+
}
44+
45+
private void OnEnable()
46+
{
47+
Stretch();
48+
}
49+
50+
private void OnScreenResize(int width, int height)
51+
{
52+
if (this.enabled) {
53+
Stretch();
54+
}
55+
}
56+
57+
/// <summary>
58+
/// Stretches the RectTransform to match the screen size.
59+
/// </summary>
60+
public void Stretch()
61+
{
62+
Stretch(this.stretchWidth, this.stretchHeight);
63+
}
64+
65+
/// <summary>
66+
/// Stretches the RectTransform to match the screen size.
67+
/// </summary>
68+
/// <param name="stretchWidth">Whether to stretch the width.</param>
69+
/// <param name="stretchHeight">Whether to stretch the height.</param>
70+
public void Stretch(bool stretchWidth, bool stretchHeight)
71+
{
72+
if (stretchWidth)
73+
{
74+
_rectTransform.SetAnchorMinX(0.0f);
75+
_rectTransform.SetAnchorMaxX(1.0f);
76+
_rectTransform.SetLeft(0.0f);
77+
_rectTransform.SetRight(0.0f);
78+
}
79+
80+
if (stretchHeight)
81+
{
82+
_rectTransform.SetAnchorMinY(0.0f);
83+
_rectTransform.SetAnchorMaxY(1.0f);
84+
_rectTransform.SetBottom(0.0f);
85+
_rectTransform.SetTop(0.0f);
86+
}
87+
}
88+
89+
}
90+
91+
}

Runtime/StretchToScreenSize.cs.meta

Lines changed: 11 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

0 commit comments

Comments
 (0)