본문 바로가기
안드로이드 코틀린

[Kotlin][Android] 디바이스 전체 화면 길이 구하기

by teamnova 2022. 6. 18.

안녕하세요. 오늘은 상태바(status bar, navigation bar 등)를 포함한 디바이스 전체 화면의 가로, 세로 길이는 구하는 방법을 알아보겠습니다.

 

//   top & bottom navigation bar 를 포함한 디바이스 화면의 가로,세로 길이 얻기
private fun getScreenSize(context: Context): IntArray {
    val screenDimensions = IntArray(2) // width[0], height[1]
    val orientation = context.resources.configuration.orientation //세로모드인지 가로모드인지 판별
    val wm = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager
    val display = wm.defaultDisplay
    val screenSize = Point()
    display.getRealSize(screenSize)
    screenDimensions[0] = screenSize.x
    screenDimensions[1] = screenSize.y
    
    return screenDimensions
}

-> 현재 디바이스 방향에 따라 가로길이와 세로길이를 얻을 수 있습니다. 

 

    //   top & bottom navigation bar 를 포함한 디바이스 화면의 가로,세로 길이 얻기
    private fun getScreenSize(context: Context): IntArray {
        val screenDimensions = IntArray(2) // width[0], height[1]
        val orientation = context.resources.configuration.orientation //세로모드인지 가로모드인지 판별
        val wm = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager
        val display = wm.defaultDisplay
        val screenSize = Point()
        display.getRealSize(screenSize)
//        screenDimensions[0] = screenSize.x
//        screenDimensions[1] = screenSize.y

        //디바이스 방향에 영향 받지 않고 화면 길이를 불러오고 싶다면
        if (orientation == Configuration.ORIENTATION_PORTRAIT){ //현재 세로모드
            screenDimensions[0] = screenSize.x
            screenDimensions[1] = screenSize.y
        }else{ //가로모드
            screenDimensions[0] = screenSize.y
            screenDimensions[1] = screenSize.x
        }

        return screenDimensions
    }

-> 디바이스의 방향과 무관하게 길이를 얻고 싶다면 위와 같이 현재 디바이스 방향을 받아와서 

    값을 사용하면 됩니다.