Unity 在编辑器下模拟刘海屏显示

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/akof1314/article/details/86725961

原因

在实现支持刘海屏时,为了可以方便在编辑器下直观查看效果,也方便其他人员进行调整,需要可以在编辑器模拟显示刘海屏。

原理

模拟显示刘海屏黑边,那么就得在左右两侧动态添加两个黑色图片,来模仿刘海屏。

代码

了防止分辨率小于刘海屏的也开启模拟,所以添加分辨率比判断,小于一定比例不是刘海屏。

/// <summary>
/// 开启模拟
/// </summary>
public static void OpenSimulate()
{
    if (UIManager.Instance == null)
    {
        return;
    }

    s_Height = 80;
    var tf = UIManager.Instance.gameObject.GetComponent<RectTransform>();
    if (tf == null)
    {
        return;
    }

    var pixelWidth = UIManager.Instance.uiCamera.pixelWidth;
    var pixelHeight = UIManager.Instance.uiCamera.pixelHeight;
    if (pixelWidth * 1f / pixelHeight < 2.1f)
    {
        // 说明不是刘海屏,强制改变分辨率
#if UNITY_EDITOR
        UnityEditor.EditorUtility.DisplayDialog("刘海屏测试", "Game 视图分辨率不是刘海屏比例比 2.1 至少!", "手动修改");
        return;
#endif
    }
    s_Height = s_Height / (pixelWidth / tf.sizeDelta.x);

    CreateSimulateUI();
}

private static void CreateSimulateUI()
{
    string canvasName = "UISimulateNotch";
    if (GameObject.Find(canvasName))
    {
        return;
    }

    var root = new GameObject(canvasName);
    Object.DontDestroyOnLoad(root);
    Canvas canvas = root.AddComponent<Canvas>();
    canvas.renderMode = RenderMode.ScreenSpaceOverlay;
    var scaler = root.AddComponent<CanvasScaler>();
    scaler.uiScaleMode = CanvasScaler.ScaleMode.ConstantPixelSize;

    GameObject child = new GameObject("Notch");
    Image img = child.AddComponent<Image>();
    img.color = Color.black;
    RectTransform rectTransform = child.transform as RectTransform;
    rectTransform.SetParent(root.transform, false);
    rectTransform.anchoredPosition = Vector2.zero;
    rectTransform.sizeDelta = new Vector2(80f, 324f);
    rectTransform.anchorMin = new Vector2(0, 0.5f);
    rectTransform.anchorMax = rectTransform.anchorMin;
    rectTransform.pivot = rectTransform.anchorMin;

    GameObject child2 = GameObject.Instantiate(child);
    rectTransform = child2.transform as RectTransform;
    rectTransform.SetParent(root.transform, false);
    rectTransform.anchoredPosition = Vector2.zero;
    rectTransform.anchorMin = new Vector2(1, 0.5f);
    rectTransform.anchorMax = rectTransform.anchorMin;
    rectTransform.pivot = rectTransform.anchorMin;
}
展开阅读全文

没有更多推荐了,返回首页