Created
February 12, 2021 02:15
-
-
Save ScottPierce/2bd2624305c89cd8d3da3deb845044c3 to your computer and use it in GitHub Desktop.
Jetpack Compose Screen Rotation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@Composable | |
fun RotateScreen( | |
rotation: ScreenRotation, | |
modifier: Modifier = Modifier, | |
contentAlignment: Alignment = Alignment.TopStart, | |
content: @Composable () -> Unit | |
) { | |
BoxWithConstraints { | |
val width: Dp | |
val height: Dp | |
when (rotation) { | |
ScreenRotation.LEFT_90_DEGREES, ScreenRotation.RIGHT_90_DEGREES -> { | |
width = maxHeight | |
height = maxWidth | |
} | |
else -> { | |
width = maxWidth | |
height = maxHeight | |
} | |
} | |
Box( | |
modifier = modifier | |
.rotate(rotation.degrees) | |
.width(width) | |
.height(height), | |
contentAlignment = contentAlignment | |
) { | |
content() | |
} | |
} | |
} | |
enum class ScreenRotation(val degrees: Float) { | |
LEFT_90_DEGREES(-90f), RIGHT_90_DEGREES(90f), NORMAL(0f) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks, this works fine. I just had to move the modifier to the
BoxWithConstraints
in order to make the modifiers applied on theRotateScreen
to work correctly, for example:weight(1f)
.Also, I needed to use
requiredSize
(see here why), so the width and height is correctly set, and align it to the center before rotating it.Sample: