The rotation of the captured image depends on the target rotation of the ImageCapture
use case. By default, when it isn’t set by the application, it is equal to Display.getRotation()
, where Display
is the default display at the time the ImageCapture
use case is created.
This means that you need to updated the ImageCapture
‘s target rotation every time the display’s orientation changes, e.g. when the device is physically rotated from portrait to landscape.
I’m assuming your activity has a locked orientation (?). In this case, you can use an OrientationEventListener
to continuously get updates on the device’s rotation, and then update the use case’s target rotation accordingly.
val orientationEventListener = object : OrientationEventListener(this) {
override fun onOrientationChanged(orientation: Int) {
if (orientation == OrientationEventListener.UNKNOWN_ORIENTATION) {
return
}
val rotation = when (orientation) {
in 45 until 135 -> Surface.ROTATION_270
in 135 until 225 -> Surface.ROTATION_180
in 225 until 315 -> Surface.ROTATION_90
else -> Surface.ROTATION_0
}
imageCapture.targetRotation = rotation
}
}
You should start/stop the orientationEventListener
when the Activity’s lifecycle is started/stopped, this also matches when the camera’s started/stopped. You can see an example of this here.
You can also learn more about CameraX’s use cases and rotation in the official documentation.
CLICK HERE to find out more related problems solutions.