Как получить уведомление при изменении размера окна приложения на ПК / MAC? - PullRequest
0 голосов
/ 13 февраля 2019

Я пытаюсь найти способ получить любой вид уведомления / обратного вызова, когда пользователь изменяет размер окна приложения на ПК / MAC.

Я пытался искать везде, переполнение стека, форум по единству, reddit, и я еще ничего не нашел, кроме попыток проверить это при обновлении или использования подпрограммы.

моя цель - всякий раз, когда пользователь меняет размер окна приложения, я фиксирую размер окна приложения пользователя.установите максимально возможное разрешение для поддерживаемого соотношения сторон дисплея.

спасибо за любые ответы.

1 Ответ

0 голосов
/ 13 февраля 2019

Вы можете сохранить начальные размеры окна и сравнить их как

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 возвращает максимальное разрешение дисплея, а не текущий размер окна.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...