how to rotate image in android programmatically
Android

How To Rotate Image In Android Programmatically?

2.4/5 - (8 votes)

Intro

How to rotate image in android programmatically. To rotate an image in android is pretty much easier than anything. You just open an image and tap the edit button, and tap on the rotate. Well, but is it that easy when you want to do it programmatically?

What is programming?

Programming is the process of creating a set of instructions that tell a device how to perform a task. It is a process that professionals use to write code that instructs them to perform a program or an application. Basically, programming is a set of instructions to facilitate specific actions.

How To Rotate Image In Android Programmatically Using Imageview

In android, Imageview is the best app to display images. Images from any source or any type can be fetched. In the Imageview, Images can be displayed without any operations. Also, images can be rotated to a certain angle and displayed in it. So I will try to explain how you could rotate an image programmatically and display it in Imageview.

Step by step implementation

Step 1: Create a New Project in Android Studio

To create a new project, please open the Imageview and start a new project. This application is shown in Kotlin, so make sure you select Kotlin as the primary language.

Step 2: Adding an image in res > drawable folder

Copy the image to the drawable folder in the resources folder.

Step 3: Working with the activity_main.xml file.

Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. Add an ImageView to display the image, an EditText to input degrees (integer) to rotate and a Button to execute the rotation.

XML

<?xml version=”1.0″ encoding=”utf-8″?>

<RelativeLayout

            xmlns:android=”http://schemas.android.com/apk/res/android”

            xmlns:app=”http://schemas.android.com/apk/res-auto”

            xmlns:tools=”http://schemas.android.com/tools”

            android:layout_width=”match_parent”

            android:layout_height=”match_parent”

            tools:context=”.MainActivity”>

            <ImageView

                        android:id=”@+id/image_view_1″

                        android:layout_width=”300sp”

                        android:layout_height=”300sp”

                        android:layout_centerHorizontal=”true”

                        android:layout_marginTop=”50sp”

                        android:src=”@drawable/img”/>

            <EditText

                        android:id=”@+id/edit_text_1″

                        android:layout_width=”50sp”

                        android:layout_height=”60sp”

                        android:inputType=”number”

                        android:layout_centerHorizontal=”true”

                        android:layout_below=”@id/image_view_1″

                        android:layout_marginTop=”100sp”/>

            <Button

                        android:id=”@+id/button_1″

                        android:layout_width=”wrap_content”

                        android:layout_height=”wrap_content”

                        android:layout_centerHorizontal=”true”

                        android:layout_below=”@id/edit_text_1″

                        android:layout_marginTop=”20sp”

                        android:text=”rotate”/>

</RelativeLayout>

Step 4: Working with the MainActivity.kt file

Go to the MainActivity.kt file and refer to the following code. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail.

Kotlin

package org.geeksforgeeks.programmaticallyrotateiv

import androidx.appcompat.app.AppCompatActivity

import android.os.Bundle

import android.widget.Button

import android.widget.EditText

import android.widget.ImageView

import android.widget.Toast

class MainActivity : AppCompatActivity() {

            override fun onCreate(savedInstanceState: Bundle?) {

                        super.onCreate(savedInstanceState)

                        setContentView(R.layout.activity_main)

                        // Declaring and Initializing the ImageView,

                        // EditText and Button from the layout file

                        val mImageView = findViewById<ImageView>(R.id.image_view_1)

                        val mEditText = findViewById<EditText>(R.id.edit_text_1)

                        val mButton = findViewById<Button>(R.id.button_1)

                        // When button is clicked

                        mButton.setOnClickListener {

                                    // EditText value is converted to

                                    // float and rotation is applied

                                    if(mEditText.text.isNotEmpty()){

                                                val mAngleRotate = (mEditText.text.toString() + “f”).toFloat()

                                                mImageView.rotation = mAngleRotate

                                    } else {

                                                Toast.makeText(applicationContext, “Field cannot be empty”, Toast.LENGTH_SHORT).show()

                                    }

                        }

            }

}

 

Rotating image in an image view by an angle using Android studio

Step 1: Create a new project.

Create a new project in Android Studio, go to File ⇒ New Project, and fill in all required details to create a new project.

Step 2: Add the Code

Add the following code to res/layout/activity_main.xml.

<?xml version=”1.0″ encoding=”utf-8″?>

<LinearLayout xmlns:android=”http://schemas.android.com/apk/res/android”

   android:id=”@+id/parent”

   xmlns:tools=”http://schemas.android.com/tools”

   android:layout_width=”match_parent”

   android:layout_height=”match_parent”

   tools:context=”.MainActivity”

   android:gravity=”center”

   android:orientation=”vertical”>

   <ImageView

      android:id=”@+id/imageView”

      android:src=”@mipmap/ic_launcher”

      android:layout_width=” wrap_content”

      android:layout_height=” wrap_content” />

   <TextView

      android:id=”@+id/textChanger”

      android:layout_margin=”20dp”

      android:textAlignment=”center”

      android:text=”Initial text”

      android:layout_width=”match_parent”

      android:layout_height=”wrap_content” />

</LinearLayout>

In the above code, image view and text view are used. When a user clicks on the Text view, the Image will rotate to a 20-degree angle.

Step 3: Add the Code

Add the following code to src/MainActivity.java

package com.example.andy.myapplication;

import android.graphics.Bitmap;

import android.graphics.Matrix;

import android.os.Build;

import android.os.Bundle;

import android.os.Handler;

import android.support.annotation.RequiresApi;

import android.support.v7.app.AppCompatActivity;

import android.view.View;

import android.widget.ImageView;

import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

   int view = R.layout.activity_main;

   TextView textChanger;

   ImageView imageView;

   @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)

   @Override

   protected void onCreate(Bundle savedInstanceState) {

      super.onCreate(savedInstanceState);

      setContentView(view);

      textChanger = findViewById(R.id.textChanger);

      imageView=findViewById(R.id.imageView);

      textChanger.setOnClickListener(new View.OnClickListener() {

         @Override

         public void onClick(View v) {

            roateImage(imageView);

         }

      });

   }

   private void roateImage(ImageView imageView) {

      Matrix matrix = new Matrix();

      imageView.setScaleType(ImageView.ScaleType.MATRIX); //required

      matrix.postRotate((float) 20, imageView.getDrawable().getBounds().width()/2,    imageView.getDrawable().getBounds().height()/2);

      imageView.setImageMatrix(matrix);

   }

}

In the above code, roateImage() is used and passed imageview as shown below –

Matrix matrix = new Matrix();

imageView.setScaleType(ImageView.ScaleType.MATRIX); //required

matrix.postRotate((float) 20, imageView.getDrawable().getBounds().width()/2, imageView.getDrawable().getBounds().height()/2);

imageView.setImageMatrix(matrix);

Let’s run the application. I think you are connected to an actual Android device with your computer. Open your project’s activity files and click the Run icon from the toolbar. Choose your mobile device as an option and check your android device which will display the default screen −

how to rotate image in android programmatically

In the above code, it is a default screen. When the user clicks on the “initial text” text view, it will rotate 20 degrees as shown below –

how to rotate image in android programmatically

Scaling and Rotating Image using XML

Step 1: Create an XML file and write this

Use an Image View and button in an XML file to do both rotation and scaling on button click.

  • <?xml version=”1.0″ encoding=”utf-8″?> 
  • <RelativeLayout xmlns:android=”http://schemas.android.com/apk/res/android” 
  •     android:layout_width=”fill_parent” 
  •     android:layout_height=”fill_parent”> 
  •      
  •     <ImageView android:id=”@+id/imageview” 
  •         android:layout_width=”wrap_content” 
  •         android:layout_height=”wrap_content” 
  •         android:src=”@drawable/ic_launcher” 
  •         android:layout_centerInParent=”true”/> 
  •      
  •     <Button android:id=”@+id/btnStart” 
  •         android:layout_width=”150dp” 
  •         android:layout_height=”wrap_content” 
  •         android:text=”RotateScale” 
  •         android:layout_alignParentBottom=”true” 
  •         android:layout_centerHorizontal=”true” 
  •         android:layout_marginBottom=”20dp”/> 
  • </RelativeLayout>

Step 2: In the together.xml file inside the animk folder, you will write the following.

Create a folder inside the res folder and write this:

●   <?xml version=”1.0″ encoding=”utf-8″?> 

●   <set xmlns:android=”http://schemas.android.com/apk/res/android” 

●       android:fillAfter=”true” 

●       android:interpolator=”@android:anim/linear_interpolator” > 

●      

●       <scale 

●           xmlns:android=”http://schemas.android.com/apk/res/android” 

●           android:duration=”4000″ 

●           android:fromXScale=”1″ 

●           android:fromYScale=”1″ 

●           android:pivotX=”50%” 

●           android:pivotY=”50%” 

●           android:toXScale=”4″ 

●           android:toYScale=”4″ > 

●       </scale> 

●      

●       <rotate 

●           android:duration=”500″ 

●           android:fromDegrees=”0″ 

●           android:toDegrees=”360″ 

●           android:pivotX=”50%” 

●           android:pivotY=”50%” 

●           android:repeatCount=”infinite” 

●      

●           /> 

●      

●   </set>

Step 3: Create a java file and write the following

In your Java file, you need to load this XML file by ing the path of this file. First, you will create an Animation reference variable and this animation object will hold the animation object returned by the loadAniamtion() method. Then call the setAnimationListener() method to set the animation, because you need to perform all operations on a button click so set the button on its clickListener and start the animation on the image.

  • import android.app.Activity; 
  • import android.os.Bundle; 
  • import android.view.View; 
  • import android.view.animation.Animation; 
  • import android.view.animation.AnimationUtils; 
  • import android.view.animation.Animation.AnimationListener; 
  • import android.widget.Button; 
  • import android.widget.ImageView; 
  • public class TogetherActivity extends Activity implements AnimationListener { 
  •    
  •        ImageView imageview; 
  •        Button rotatescale; 
  •    
  •        // Animation 
  •        Animation Togetheraniamtion; 
  •    
  •        @Override 
  •        protected void onCreate(Bundle savedInstanceState) { 
  •               // TODO Auto-generated method stub 
  •               super.onCreate(savedInstanceState); 
  •               setContentView(R.layout.activity_together); 
  •    
  •               imageview = (ImageView) findViewById(R.id.imgLogo); 
  •               rotatescale = (Button) findViewById(R.id.btnStart); 
  •    
  •               // load the animation 
  •         Togetheraniamtion = AnimationUtils.loadAnimation(getApplicationContext(), 
  •                            R.anim.together); 
  •    
  •               // set animation listener 
  •         Togetheraniamtion.setAnimationListener(this); 
  •    
  •               // button click event 
  •               rotatescale.setOnClickListener(new View.OnClickListener() { 
  •                      @Override 
  •                      public void onClick(View v) { 
  •                            // start the animation 
  •                            imageview.startAnimation(Togetheraniamtion); 
  •                      } 
  •               }); 
  •    
  •        } 
  •    
  •        @Override 
  •        public void onAnimationEnd(Animation animation) { 
  •               // Take any action after completing the animation 
  •    
  •               // check for zoom in animation 
  •               if (animation ==Togetheraniamtion) { 
  •               } 
  •    
  •        } 
  •    
  •        @Override 
  •        public void onAnimationRepeat(Animation animation) { 
  •               // TODO Auto-generated method stub 
  •    
  •        } 
  •    
  •        @Override 
  •        public void onAnimationStart(Animation animation) { 
  •               // TODO Auto-generated method stub 
  •    
  •        }

It will rotate continuously unless you do not change the android:repeatcount to infinite.

You may also have interested to know:

How to fix Google Talk authentication failed?

How to cast to vizio tv from Android

Frequently Asked Questions

1.   What is ImageView?

Imageview is used to display all kinds of images in the android application.

2.   What is TextInputLayout?

It’s a layout to wrap a TextInputEditText, EditText, or descendant to show a floating label.

Leave a Reply

Your email address will not be published.