-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathUIImageScaler.cs
76 lines (64 loc) · 2.14 KB
/
UIImageScaler.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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
// **************************************************************** //
//
// Copyright (c) RimuruDev. All rights reserved.
// Contact me:
// - Gmail: [email protected]
// - GitHub: https://github.com/RimuruDev
// - LinkedIn: https://www.linkedin.com/in/rimuru/
//
// **************************************************************** //
using UnityEngine;
using UnityEngine.UI;
namespace AbyssMoth.Internal.Codebase.Runtime.Gameplay.UI
{
[RequireComponent(typeof(Image))]
[RequireComponent(typeof(RectTransform))]
[RequireComponent(typeof(AspectRatioFitter))]
public sealed class UIImageScaler : MonoBehaviour
{
[SerializeField] private ScaleImageMode scaleImageMode;
private Image image;
private RectTransform rectTransform;
private AspectRatioFitter aspectRatioFitter;
private void OnEnable()
{
if (scaleImageMode == ScaleImageMode.OnEnable)
ScaleImage();
}
private void Awake()
{
image = GetComponent<Image>();
rectTransform = GetComponent<RectTransform>();
aspectRatioFitter = GetComponent<AspectRatioFitter>();
}
private void Start() =>
ScaleImage();
private void LateUpdate()
{
if (scaleImageMode == ScaleImageMode.LateUpdate)
ScaleImage();
}
private void ScaleImage()
{
SetAspectRatioMode();
SetAnchorState();
}
private void SetAspectRatioMode()
{
aspectRatioFitter.aspectMode = AspectRatioFitter.AspectMode.EnvelopeParent;
aspectRatioFitter.aspectRatio = image.sprite.bounds.size.x / image.sprite.bounds.size.y;
}
private void SetAnchorState()
{
rectTransform.anchorMin = Vector2.zero;
rectTransform.anchorMax = Vector2.one;
rectTransform.offsetMin = Vector2.zero;
rectTransform.offsetMax = Vector2.zero;
}
private enum ScaleImageMode
{
LateUpdate = 0,
OnEnable = 1,
}
}
}