首页 > 解决方案 > 检测手机的方向

问题描述

我想检测手机的方向以从相机旋转框架,然后我的姿势估计可以正确推断出这个旋转的图像。

例如:有人站在我的手机前,我将手机水平放置,然后我想在推理之前将此图像旋转为垂直。因为模型正好可以垂直捕捉人。

我试过这个: varorientation = resources.configuration.orientation

但这仅在屏幕的自动旋转打开并且我不想要这个时才有效。我不旋转我的应用程序。

标签: androidkotlinsensors

解决方案


         val orientationEventListener = object : OrientationEventListener(activity) {
            override fun onOrientationChanged(orientation: Int) {
                val defaultPortrait = 0
                val upsideDownPortrait = 180
                val rightLandscape = 90
            val leftLandscape = 270
                when {
                    isWithinOrientationRange(orientation, defaultPortrait) -> {} 
                    isWithinOrientationRange(orientation, leftLandscape) -> {} 
                    isWithinOrientationRange(orientation, upsideDownPortrait) -> {} 
                    isWithinOrientationRange(orientation, rightLandscape) -> {} 
                }
            }

           private fun isWithinOrientationRange(
               currentOrientation: Int, targetOrientation: Int, epsilon: Int = 10
           ): Boolean {
               return currentOrientation > targetOrientation - epsilon
                    && currentOrientation < targetOrientation + epsilon
           }
        }
        orientationEventListener.enable()

推荐阅读