使用 RectTransform 进行ui的整体缩放
问题: 背景图或者需要两边拉伸的图片需单独抽离节点 或者 特殊处理
public abstract class BaseUI : MonoBehaviour
{
RectTransform Panel;
public int nOffSetX;
public int nOffSetScreanX;
public bool isSalfAreaAdapt = false;
public void Awake()
{
isSalfAreaAdapt = false;
//isSafeAreaAdapt = PlayerPrefs.GetInt("isSafeAreaAdapt", 1);
nOffSetX = PlayerPrefs.GetInt("SafeAreaOffSetX", 80);
nOffSetScreanX = (int)((float)nOffSetX * (float)Screen.width / (float)1920);
Panel = transform.GetComponent<RectTransform>();
}
void ApplySafeArea(Rect r, RectTransform tr)
{
if (tr == null)
return;
// Convert safe area rectangle from absolute pixels to normalised anchor coordinates
Vector2 anchorMin = r.position;
Vector2 anchorMax = r.position + r.size;
anchorMin.x /= Screen.width;
anchorMin.y /= Screen.height;
anchorMax.x /= Screen.width;
anchorMax.y /= Screen.height;
tr.anchorMin = anchorMin;
tr.anchorMax = anchorMax;
Debug.LogFormat("New safe area applied to {0}: x={1}, y={2}, w={3}, h={4} on full extents w={5}, h={6}",
name, r.x, r.y, r.width, r.height, Screen.width, Screen.height);
}
public void OnAdaptSafeArea()
{
if ((float)Screen.width / (float)Screen.height < 1.8f)
return;
if (isSalfAreaAdapt == false)
return;
Debug.LogError("nOffSetX:" + nOffSetX);
Debug.LogError("nOffSetScreanX:" + nOffSetScreanX);
var newRect = new Rect(nOffSetScreanX, 0, Screen.width - 2*nOffSetScreanX, Screen.height);
ApplySafeArea(newRect, Panel);
return;
}
private void Start()
{
OnAdaptSafeArea();
}
}