当PC / MAC上的应用程序窗口大小更改时,如何获得通知?

时间:2019-02-13 09:32:47

标签: c# unity3d

当用户在PC / MAC上更改应用程序窗口大小时,我正在尝试寻找一种获得任何通知/回调的方法。

我尝试到处寻找,stackoverflow,统一论坛,reddit,除了尝试在Update或使用协同例程进行检查之外,我什么都找不到。

我的目标是在用户更改应用程序窗口大小时固定用户设置的应用程序窗口大小,使其尽可能接近显示器支持的宽高比。

感谢您的答复。

1 个答案:

答案 0 :(得分:0)

您可以存储初始窗口大小,然后进行比较

public float targetAspetctRatio;

private int lastWidth;
private int lastHeight;

private void Start()
{
    lastWidth = Screen.width;
    lastHeight = Screen.height;

    // You could get the targetAspetctRatio also from the device like
    targetAspetctRatio = (float)Screen.currentResolution.with / Screen.currentResolution.height;
}

private void LateUpdate()
{
    if(lastWidth != Screen.width || lastHeight != Screen.height || !Mathf.Approximately((float)Screen.width/Screen.height, targetAspetctRatio))
    {
        ScreenSizeChanged();
    }
}

或带有用于不检查每一帧的计时器

private float timer=0;
public float Interval = 0.5f;

private void LateUpdate()
{
    timer-= Time.deltaTime;
    if(timer > 0) return;

    timer = Interval;

    if(lastWidth != Screen.width || lastHeight != Screen.height || !Mathf.Approximately((float)Screen.width/Screen.height, targetAspetctRatio))
    {
        ScreenSizeChanged();
    }
}

或带有协程

public float Interval = 0.5f;

private void Start()
{
    lastWidth = Screen.width;
    lastHeight = Screen.height;

    // You could get the targetAspetctRatio also from the device like
    targetAspetctRatio = (float)Screen.currentResolution.with / Screen.currentResolution.height;

    StartCoroutine(CheckSize);
}

private IEnumertor CheckSize()
{
    while(true)
    {
        if(lastWidth != Screen.width || lastHeight != Screen.height || !Mathf.Approximately((float)Screen.width/Screen.height, targetAspetctRatio))
        {
            ScreenSizeChanged();
        }
        yield return new WaitForSeconds(Offset);
    }
}

要设置长宽比,请根据高度进行设置

Screen.SetResolution(Screen.height * targetAspetctRatio, Screen.height, false);

或基于宽度

Screen.SetResolution(Screen.width,  Screen.width / targetAspetctRatio, false);

您必须确定要走的路..毫无疑问,至少有一种方法适合屏幕。像

private void ScreenSizeChanged ()
{
    // Try to go by width first
    // Check if new height would fit
    if(Screen.width <= screen.currentResolution.width && Screen.width / targetAspetctRatio <= Screen.currentResolution.height)
    {
        Screen.SetResolution(Screen.width,  Screen.width / targetAspetctRatio, false);
    }

    // By height as fallback
    // Check if new width would fit display
    else if(Screen.height <= Screen.currentResolution.height && Screen.height * targetAspetctRatio <= Screen.currentResolution.width)
    {
        Screen.SetResolution(Screen.height * targetAspetctRatio, Screen.height, false);
    }
    else
    {
        // Do nothing or maybe reset?
        Screen.SetResolution(lastWidth, lastHeight, false);
    }

    // Don't fortget to store the changed values 
    lastWidth = Screen.width;
    lastHeight = Screen.height;
}

Screen.currentResolution返回显示器的最大分辨率,而不是当前窗口大小。

相关问题