How to Rotate Image in ImageView by an Angle in Android

In this android programming code example, we will explore how to rotate image in ImageView by an angle in android.

Before we start I want to emphasize that there are many ways to achieve this in android but we are going to learn how to do this in a simple way using Picasso Android library.

Using Default ImageView Rotation Attribute

For applications that supports android API 11 and above, we can use the android rotation attribute and assign it angle of rotation value.

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:orientation="vertical">

    <ImageView
        android:id="@+id/imageView2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:src="@drawable/camera"
        android:rotation="120"
        android:scaleType="fitCenter" />

</LinearLayout>

As you can seen above, the rotation attribute rotates the ImageView with the image attached to it.

What if we want to rotate only the attached image?

Let see the difference in results.

Using Picasso Library

  1. Get an instance of an ImageView in the Activity class.
  2. Get the resource id or path to an image
  3. Use Picasso to rotate and add the to an ImageView.

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:orientation="vertical">

    <ImageView
        android:id="@+id/imageView2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:scaleType="fitCenter" />
    
</LinearLayout>

MainActivity.java

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.widget.ImageView;

import com.squareup.picasso.Picasso;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = MainActivity.class.getSimpleName();

    @SuppressLint("WrongThread")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ImageView imageView= findViewById(R.id.imageView2);
        //Image Resource to load
        int imageDrawable = R.drawable.camera;
        //Loading image using Picasso
        Picasso.get().load(imageDrawable).rotate(120.5f).into(imageView);
    }
}

android rotate image

If you have any questions or suggestions kindly use the comment box or you can contact us directly through our contact page below.

 

Add a Comment