Skip to main content

How to rotate an image in ImageView in Kotlin Android

How to rotate an image in ImageView in Kotlin Android.

Here's a detailed step-by-step tutorial on how to rotate an image in an ImageView using Kotlin in Android:

Step 1: Create a new Android project in Android Studio and open the layout file where you want to display the ImageView.

Step 2: Add an ImageView to your layout file. You can do this by adding the following code to your XML layout file:

<ImageView
android:id="@+id/imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/your_image" />

Replace @drawable/your_image with the appropriate image resource.

Step 3: Open the activity file associated with your layout file (e.g., MainActivity.kt).

Step 4: Declare a variable for the ImageView in your activity. Add the following code inside the onCreate method:

val imageView: ImageView = findViewById(R.id.imageView)

Step 5: Define a method to rotate the image. Add the following code outside the onCreate method:

private fun rotateImage() {
val anim = ObjectAnimator.ofFloat(imageView, "rotation", 0f, 360f)
anim.duration = 1000 // Set the duration of the rotation (in milliseconds)
anim.start()
}

This method uses an ObjectAnimator to rotate the ImageView. The rotation is performed from 0 degrees to 360 degrees over a duration of 1000 milliseconds (1 second).

Step 6: Call the rotateImage method whenever you want to rotate the image. For example, you can add a button to your layout and rotate the image when the button is clicked. Add the following code inside the onCreate method:

val button: Button = findViewById(R.id.button)
button.setOnClickListener {
rotateImage()
}

Replace R.id.button with the ID of your button.

Step 7: Run your app and click the button to rotate the image.

That's it! You've successfully rotated an image in an ImageView using Kotlin in Android.