Add safe area.
This commit is contained in:
38
Assets/Cryville/Common/Unity/UI/SafeArea.cs
Normal file
38
Assets/Cryville/Common/Unity/UI/SafeArea.cs
Normal file
@@ -0,0 +1,38 @@
|
|||||||
|
using UnityEngine;
|
||||||
|
using UnityEngine.EventSystems;
|
||||||
|
|
||||||
|
namespace Cryville.Common.Unity.UI {
|
||||||
|
[ExecuteAlways]
|
||||||
|
[RequireComponent(typeof(RectTransform))]
|
||||||
|
public class SafeArea : UIBehaviour {
|
||||||
|
bool _delayedUpdate;
|
||||||
|
protected override void OnValidate() {
|
||||||
|
_delayedUpdate = true;
|
||||||
|
}
|
||||||
|
void Update() {
|
||||||
|
if (_delayedUpdate) {
|
||||||
|
_delayedUpdate = false;
|
||||||
|
UpdateRect();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
protected override void OnRectTransformDimensionsChange() {
|
||||||
|
base.OnRectTransformDimensionsChange();
|
||||||
|
UpdateRect();
|
||||||
|
}
|
||||||
|
protected override void OnTransformParentChanged() {
|
||||||
|
base.OnTransformParentChanged();
|
||||||
|
UpdateRect();
|
||||||
|
}
|
||||||
|
void UpdateRect() {
|
||||||
|
var safeArea = Screen.safeArea;
|
||||||
|
var rectTransform = transform as RectTransform;
|
||||||
|
var canvas = GetComponentInParent<Canvas>(true).transform as RectTransform;
|
||||||
|
RectTransformUtility.ScreenPointToLocalPointInRectangle(canvas, new Vector2(safeArea.xMin, safeArea.yMin), Camera.main, out var pt1);
|
||||||
|
RectTransformUtility.ScreenPointToLocalPointInRectangle(canvas, new Vector2(safeArea.xMax, safeArea.yMax), Camera.main, out var pt2);
|
||||||
|
var result = Rect.MinMaxRect(pt1.x, pt1.y, pt2.x, pt2.y);
|
||||||
|
rectTransform.anchoredPosition = result.center;
|
||||||
|
rectTransform.sizeDelta = result.size;
|
||||||
|
rectTransform.anchorMin = rectTransform.anchorMax = rectTransform.pivot = new Vector2(0.5f, 0.5f);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
11
Assets/Cryville/Common/Unity/UI/SafeArea.cs.meta
Normal file
11
Assets/Cryville/Common/Unity/UI/SafeArea.cs.meta
Normal file
@@ -0,0 +1,11 @@
|
|||||||
|
fileFormatVersion: 2
|
||||||
|
guid: 112824c0b55202c4f9c779de7574b5fd
|
||||||
|
MonoImporter:
|
||||||
|
externalObjects: {}
|
||||||
|
serializedVersion: 2
|
||||||
|
defaultReferences: []
|
||||||
|
executionOrder: 0
|
||||||
|
icon: {instanceID: 0}
|
||||||
|
userData:
|
||||||
|
assetBundleName:
|
||||||
|
assetBundleVariant:
|
Reference in New Issue
Block a user