unity刘海屏适配

 public class SafeArea : MonoBehaviour
    {
        private Rect _safeArea;
        public Action ApplySafeArea;

        void Update()
        {
            if (getSafeArea() != _safeArea)
            {
                _safeArea = getSafeArea();
                applySafeArea();
            }
        }

        private void applySafeArea()
        {
            Vector2[] anchors = getAnchor();
            ApplySafeArea?.Invoke(anchors[0], anchors[1]);
        }

        private Vector2[] getAnchor()
        {
            Rect rect = getSafeArea();
            Vector2 anchorMin = rect.position;
            Vector2 anchorMax = rect.position + rect.size;
            anchorMin.x /= Screen.width;
            anchorMax.x /= Screen.width;
            anchorMin.y /= Screen.height;
            anchorMax.y /= Screen.height;
            return new Vector2[] { anchorMin, anchorMax};
        }

        private Rect getSafeArea()
        {
            Rect rect = Screen.safeArea;
    #if UNITY_EDITOR
            rect = PLAGame.Client.LuaHelper.GetSafeArea();
    #endif
            return rect;
        }
class Luahelper{
public static void ApplySafeArea(GameObject go, Action action)
  {//go指的是一个大UI的父对象
            SafeArea safeArea = go.CheckAndAddComponent();
            safeArea.ApplySafeArea = action;
 }

}

function SafeArea.ApplyCustomPanle(go, cb )  go指的是一个大UI的父对象
    LuaHelper.ApplySafeArea(go, function (anchorMin, anchorMax )
        cb(anchorMin, anchorMax)  
    end)
end

//C#示例
ApplySafeArea(go,(Vector2 anchorMin , Vector2 anchorMax )=>{
var t1 = go.transform.GetChild(0).RectTransform
t1 .anchorMin = Vector2(anchorMin.x, 1)
t1 .anchorMin = Vector2(anchorMin.x, 1)
})


//lua示例
 SafeArea.ApplyCustomPanle(self.view.go, function ( anchorMin, anchorMax )
        print(anchorMin)
        print(anchorMax)
        local tran = self.view.go.transform
        tran:GetChild(1).anchorMin = Vector2(anchorMin.x, 1)
        tran:GetChild(2).anchorMin = Vector2(anchorMin.x, 0)
        tran:GetChild(3).anchorMin = Vector2(anchorMax.x, 1)
        tran:GetChild(3).anchorMax = Vector2(anchorMax.x, 1)
        tran:GetChild(4).anchorMin = Vector2(anchorMin.x, 0)
        tran:GetChild(4).anchorMax = Vector2(anchorMax.x, 1)
 end)

 

你可能感兴趣的:(unity刘海屏适配)