Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

JetpackCompose Android – Rotate Image by an angle when clicked on it

I have scenario where I want to rotate image by an angle when clicked on it in Jetpack Compose. Please find my code below of what I tried till now:

`@Composable

fun RotateImage() {

Image(painter = painterResource(id = R.drawable.ic_expand_more),

modifier = Modifier.padding(end=5.dp)

.clickable {

Modifier.rotate(angle)

},

contentDescription = “Expandable Image”
)`

Please help me regarding this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You need to change angle inside Modifier.clickable instead of putting Modifier.rotate inside it.

@Composable
private fun RotateImage() {
    var angle by remember {
        mutableStateOf(0f)
    }

    Image(
        modifier = Modifier
            .rotate(angle)
            .clickable {
               // Change this angle as required, i set it to rotate by 90 degrees
                angle = (angle + 90) % 360f
            },
        painter = painterResource(id = R.drawable.landscape1),
        contentDescription = null
    )
}

Also, side note order of rotate and clickable determines whether clickable region also rotated. If you set rotate after clickable only content is rotated.

@Composable
private fun RotateImage2() {
    var angle by remember {
        mutableStateOf(0f)
    }

    Image(
        modifier = Modifier
            .clickable {
                angle = (angle + 90) % 360f
            }
            .rotate(angle),
        painter = painterResource(id = R.drawable.landscape1),
        contentDescription = null
    )
}

will have different outcome from the first one

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading