In this tutorial, you'll learn how to dynamically rotate images both clockwise and counterclockwise in an Android app using Kotlin. This involves programmatically manipulating the ImageView using the Matrix class to achieve smooth and responsive image rotation based on user interactions or other application logic.
Submitted on July 07, 2024
To create an Android app that allows users to rotate an image both clockwise and counterclockwise, we'll build a simple application using Kotlin. Here's a step-by-step guide:
Modify the layout XML (activity_main.xml):
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="16dp">
<ImageView
android:id="@+id/imageView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="centerInside"
android:src="@drawable/your_image" />
<Button
android:id="@+id/btnRotateClockwise"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_marginEnd="16dp"
android:layout_marginBottom="16dp"
android:text="Rotate Clockwise" />
<Button
android:id="@+id/btnRotateCounterclockwise"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_marginStart="16dp"
android:layout_marginBottom="16dp"
android:text="Rotate Counterclockwise" />
</RelativeLayout>
Open MainActivity.kt:
Rotate image clockwise and counterclockwise:
import android.graphics.Matrix
import android.os.Bundle
import android.view.View
import android.widget.Button
import android.widget.ImageView
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
private lateinit var imageView: ImageView
private lateinit var btnRotateClockwise: Button
private lateinit var btnRotateCounterclockwise: Button
private var currentRotation = 0f
@Override
fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
imageView = findViewById(R.id.imageView)
btnRotateClockwise = findViewById(R.id.btnRotateClockwise)
btnRotateCounterclockwise = findViewById(R.id.btnRotateCounterclockwise)
// Set initial rotation
imageView.rotation = currentRotation
btnRotateClockwise.setOnClickListener {
rotateImage(90f)
}
btnRotateCounterclockwise.setOnClickListener {
rotateImage(-90f)
}
}
private fun rotateImage(degrees: Float) {
currentRotation += degrees
val matrix = Matrix()
matrix.postRotate(currentRotation)
imageView.imageMatrix = matrix
imageView.invalidate()
}
}
Connect your Android device or start an emulator:
Run the application:
Test the rotation functionality:
This example provides a basic implementation of rotating an image in both clockwise and counterclockwise directions using matrix transformations.