Skip to content

Instantly share code, notes, and snippets.

@ScottPierce
Created February 12, 2021 02:15
Show Gist options
  • Save ScottPierce/2bd2624305c89cd8d3da3deb845044c3 to your computer and use it in GitHub Desktop.
Save ScottPierce/2bd2624305c89cd8d3da3deb845044c3 to your computer and use it in GitHub Desktop.
Jetpack Compose Screen Rotation
@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)
}
@JBou
Copy link

JBou commented Jul 29, 2025

Thanks, this works fine. I just had to move the modifier to the BoxWithConstraints in order to make the modifiers applied on the RotateScreen 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:

RotateScreen(
    rotation = ScreenRotation.RIGHT_90_DEGREES,
    modifier = Modifier.weight(1f)
) {
  //CONTENT
}
@Composable
fun RotateScreen(
    rotation: ScreenRotation,
    modifier: Modifier = Modifier,
    contentAlignment: Alignment = Alignment.TopStart,
    content: @Composable () -> Unit
) {
    BoxWithConstraints(modifier = modifier) {
        val width: Dp
        val height: Dp

        when (rotation) {
            ScreenRotation.LEFT_90_DEGREES, ScreenRotation.RIGHT_90_DEGREES -> {
                width = this.maxHeight
                height = this.maxWidth
            }

            else -> {
                width = this.maxWidth
                height = this.maxHeight
            }
        }

        Box(
            modifier = Modifier
                .align(Alignment.Center)
                .requiredSize(width = width, height = height)
                .rotate(rotation.degrees),
            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