unity UGUI 全面屏适配 笔记

 使用 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();
    }
}

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值