-
유니티 화면 비율 고정 처리...22일지 2021. 12. 9. 18:15
기존 처리에 크기 제한 추가
WinProc 코드에서 최대 크기, 최소 크기에 대한 제한이 상당히 괜찮아 보여서 추가하려고 한다.
단, 가로 세로 크기를 동일하게 둘 생각인데 가로 크기 제한과 세로 크기 제한이 달라서 가로로 줄일 때와 세로로 줄일 때 사이즈가 서로 다르다는 것을 발견했기 때문이다.
이게 굉장히 이상하게 느껴졌기에 가로, 세로의 크기 제한을 같은 값을 사용할 생각이다.
먼저, 크기 조절을 위한 변수를 추가했다.
// 화면 최소 크기 public int MinSize { get; set; } = 512; // 화면 최대 크기 public int MaxSize { get; set; } = 1024;
이후 기존 크기 변경 코드를 함수로 분리한 뒤, 사이즈 조절 후에도 크기가 지정된 크기를 벗어나지 않도록 추가 함수로 크기를 조절하도록 했다.
/// <summary> /// 주어진 크기를 지정된 비율에 맞게 수정하여 반환한다. /// </summary> /// <param name="width">너비</param> /// <param name="height">높이</param> private void GetAdjustedSize(ref int width, ref int height) { // 대각선으로 비율을 바꾼 경우 적절한 방향을 선택해 비율을 맞춘다. if (width != m_screenSizeX && height != m_screenSizeY) { GetAdjustedSize(ref width, ref height, ResizeOption.Diagonal); } else if (width != m_screenSizeX) { GetAdjustedSize(ref width, ref height, ResizeOption.Vertical); } else { GetAdjustedSize(ref width, ref height, ResizeOption.Horizontal); } // 바꾼 값이 최소, 최대 크기를 벗어나는 경우 다시 조정한다. if (width < MinSize || MaxSize < width) { width = width < MinSize ? MinSize : MaxSize; GetAdjustedSize(ref width, ref height, ResizeOption.Vertical); } if (height < MinSize || MaxSize < height) { height = height < MinSize ? MinSize : MaxSize; GetAdjustedSize(ref width, ref height, ResizeOption.Horizontal); } } /// <summary> /// 적절한 방향을 선택해 크기 조절하기 위한 함수 /// </summary> /// <param name="width">너비</param> /// <param name="height">높이</param> /// <param name="resizeOption">크기 변경 옵션</param> private void GetAdjustedSize(ref int width, ref int height, ResizeOption resizeOption) { // 대각선으로 비율을 바꾼 경우 적절한 방향을 선택해 비율을 맞춘다. if (resizeOption == ResizeOption.Diagonal) { if (Mathf.Abs(width - m_screenSizeX) > Mathf.Abs(height - m_screenSizeY)) { height = Mathf.FloorToInt(width / m_aspectRatio); } else { width = Mathf.FloorToInt(height * m_aspectRatio); } } else if (resizeOption == ResizeOption.Vertical) { height = Mathf.FloorToInt(width / m_aspectRatio); } else { width = Mathf.FloorToInt(height * m_aspectRatio); } }
실행 결과는 다음과 같다.
크기 조절 시 최대, 최소 크기를 벗어나지 않는다.