개발관련/Unity

해상도 고정

Diademata 2023. 9. 2. 02:46
반응형

유니티 API를 Screen.SetResolution 호출하는 경우
이 해상도를 맞추기 위해 인게임의 화면 비율을 강제로 늘리거나 줄이거나 해버린다.

세로일때는 정상이나 가로로 돌렸을 경우 타일들이 늘어난 것을 볼 수 있다.

 

그래서 해상도의 비율을 고정하기 위해서 최대 공약수로 타겟 해상도의 비율을 구한다.

 

이후에 그 비율만큼 디바이스의 높이와 넓이를 설정한다.

public void SetResolutionBasedOnRatio()
{
    DeviceWidth = Screen.width;
    DeviceHeight = Screen.height;

    int gcdValue = GCD(TargetWidth, TargetHeight);

    float targetWidthRatio = (float)TargetWidth / gcdValue;
    float targetHeightRatio = (float)TargetHeight / gcdValue;

    int proposedHeight = (int)(DeviceWidth * targetHeightRatio / targetWidthRatio);
    int proposedWidth = (int)(DeviceHeight * targetWidthRatio / targetHeightRatio);

    if (proposedHeight <= DeviceHeight)
    {
        Screen.SetResolution(DeviceWidth, proposedHeight, true);
    }
    else
    {
        Screen.SetResolution(proposedWidth, DeviceHeight, true);
    }
}

private int GCD(int a, int b)
{
    return b == 0 ? a : GCD(b, a % b);
}

 

위의 방법 말고 레터박스를 깔기 위해선 다른 방법을 사용해야한다.

public IEnumerator AdjustCameraViewportToAspectRatio(Camera camera)
{
    yield return null;
    var rect = camera.rect;
    var scaleheight = (float)DeviceWidth / DeviceHeight / ((float)TargetWidth / TargetHeight);
    var scalewidth = 1F / scaleheight;
    if (scaleheight < 1F)
    {
        rect.height = scaleheight;
        rect.y = (1f - scaleheight) / 2F;
    }
    else
    {
        rect.width = scalewidth;
        rect.x = (1f - scalewidth) / 2F;
    }
    camera.rect = rect;
}

 

반응형