Android: Rotate image in imageview by an angle

If you're supporting API 11 or higher, you can just use the following XML attribute:

android:rotation="90"

It might not display correctly in Android Studio xml preview, but it works as expected.


Another simple way to rotate an ImageView:
UPDATE:
Required imports:

import android.graphics.Matrix;
import android.widget.ImageView;

Code: (Assuming imageView, angle, pivotX & pivotY are already defined)

Matrix matrix = new Matrix();
imageView.setScaleType(ImageView.ScaleType.MATRIX);   //required
matrix.postRotate((float) angle, pivotX, pivotY);
imageView.setImageMatrix(matrix);

This method does not require creating a new bitmap each time.

NOTE: To rotate an ImageView on ontouch at runtime you can set onTouchListener on ImageView & rotate it by adding last two lines(i.e. postRotate matrix & set it on imageView) in above code section in your touch listener ACTION_MOVE part.


There are two ways to do that:

1 Using Matrix to create a new bitmap:

imageView = (ImageView) findViewById(R.id.imageView);
Bitmap myImg = BitmapFactory.decodeResource(getResources(), R.drawable.image);

Matrix matrix = new Matrix();
matrix.postRotate(30);

Bitmap rotated = Bitmap.createBitmap(myImg, 0, 0, myImg.getWidth(), myImg.getHeight(),
        matrix, true);

imageView.setImageBitmap(rotated);

2 use RotateAnimation on the View you want to Rotate, and make sure the Animation set to fillAfter=true, duration=0, and fromDegrees=toDgrees

 <?xml version="1.0" encoding="utf-8"?>
<rotate
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:fromDegrees="45"
  android:toDegrees="45"
  android:pivotX="50%"
  android:pivotY="50%"
  android:duration="0"
  android:startOffset="0"
/>

and Inflate the Animation in code:

Animation rotation = AnimationUtils.loadAnimation(this, R.anim.rotation);
myView.startAnimation(rotation);

mImageView.setRotation(angle) with API>=11