AkiraPixelWind/Assets/Scripts/Main/UI/UIMgr/UIAutoAdjustWidth.cs
2022-12-29 18:20:40 +08:00

69 lines
1.8 KiB
C#

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class UIAutoAdjustWidth : MonoBehaviour
{
private RectTransform m_rtfSelf;
private Vector2 m_targetSize;
private void OnEnable()
{
m_rtfSelf = transform.GetComponent<RectTransform>();
m_targetSize = new Vector2(GetFullUIWidth(), m_rtfSelf.rect.height);
RefreshSize();
}
public void SetRectTransformSize(RectTransform trans, Vector2 newSize)
{
Vector2 oldSize = trans.rect.size;
Vector2 deltaSize = newSize - oldSize;
trans.offsetMin = trans.offsetMin - new Vector2(deltaSize.x * trans.pivot.x, deltaSize.y * trans.pivot.y);
trans.offsetMax = trans.offsetMax + new Vector2(deltaSize.x * (1f - trans.pivot.x), deltaSize.y * (1f - trans.pivot.y));
}
private float GetFullUIWidth()
{
int devWidth = ScreenAutoAdjust.DevWidth;
// 屏幕比 > 2:1的用 2:1, 小于2:1的用16:9
float screenRate = (float)Screen.width / (float)Screen.height;
if (screenRate < 1.98f)
devWidth = ScreenAutoAdjust.DevHeight * 16 / 9;
return Mathf.Max(screenRate * ScreenAutoAdjust.DevHeight, devWidth);
}
//private float GetFullUIHeight()
//{
// //float devHeight = 900;
// //屏幕比 < 16:9的用
// //local screenRate = (float)Screen.width / (float)Screen.height
// //if (screenRate < 1.77f)
// // devWidth = 1600;
//}
//#if UNITY_EDITOR
// private void Update()
// {
// m_targetSize = new Vector2(GetFullUIWidth(), m_rtfSelf.rect.height);
// RefreshSize();
// }
//#endif
private void RefreshSize()
{
SetRectTransformSize(m_rtfSelf, m_targetSize);
}
}