Android: Rotate image in imageview by an angle

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP



Android: Rotate image in imageview by an angle



I am using the following code to rotate a image in ImageView by an angle. Is there any simpler and less complex method available.


ImageView iv = (ImageView)findViewById(imageviewid);
TextView tv = (TextView)findViewById(txtViewsid);
Matrix mat = new Matrix();
Bitmap bMap = BitmapFactory.decodeResource(getResources(),imageid);
mat.postRotate(Integer.parseInt(degree));===>angle to be rotated
Bitmap bMapRotate = Bitmap.createBitmap(bMap, 0, 0,bMap.getWidth(),bMap.getHeight(), mat, true);
iv.setImageBitmap(bMapRotate);





PS for 2014, it looks like you can simply set "rotation" in the XML in Android Studio. (You can even just click the "expert properties" button on the right, if you can't be bothered using the 'Text' layout!)
– Fattie
May 25 '14 at 17:14




18 Answers
18



Another simple way to rotate an ImageView:
UPDATE:

Required imports:


ImageView


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



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


imageView


angle


pivotX


pivotY


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.


ImageView


ImageView





For completeness here is the line based on the ImageView's values: matrix.postRotate( 180f, imageView.getDrawable().getBounds().width()/2, imageView.getDrawable().getBounds().height()/2);
– Stefan Hoth
Sep 12 '12 at 22:14


ImageView


matrix.postRotate( 180f, imageView.getDrawable().getBounds().width()/2, imageView.getDrawable().getBounds().height()/2);





how to rotate imageview on every touch event?
– Saurabh
Jan 23 '13 at 13:05





for me, if rotated in a relativeLayout the imageView grows to the size of the image contained, not fitting into the layout anymore. Does anybody have experience how to solve this?
– Makibo
Apr 25 '13 at 3:42





Note: for this to work, you have to set your ImageView's src attribute. getDrawable() was returning null for me until I realized that I had set the ImageView's background attribute instead of src. facepalm
– Gary S.
Jan 2 '14 at 15:32


ImageView


src


getDrawable()


ImageView


background


src





It rotates the image in imageview only. What should I do to rotate the image itself too?
– Ege
May 6 '14 at 21:49



mImageView.setRotation(angle) with API>=11


mImageView.setRotation(angle)





would it also change the width and height of the view to the correct size ? or does it change only how it looks?
– android developer
Jan 27 '14 at 8:28





Is there a way to have a "rotation animation" while rotating?
– Ivan Morgillo
Oct 16 '14 at 12:25





@IvanMorgillo You can have a look at ViewPropertyAnimator, which is used like aView.animate().rotation(20).start()
– Jokester
Jul 10 '15 at 4:36


ViewPropertyAnimator


aView.animate().rotation(20).start()





@IvanMorgillo: Use rotationBy(). For example, view.animate().rotationBy(180f).start(). But it becomes problematic if the view is clicked successively.
– Mangesh
Aug 29 '15 at 10:32


rotationBy()


view.animate().rotationBy(180f).start()





I'm using this code in a button. The first click is ok, But the next clicks doesn't rotate anymore. Should I put some other line to fix this?
– Eggakin Baconwalker
Aug 25 '16 at 20:00



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.





The hint regarding the xml preview helped me a lot
– ngu
Dec 10 '15 at 18:58





The XML preview is displaying for me properly after rotation is applied.
– Dick Lucas
Jul 24 at 16:50



There are two ways to do that:



1 Using Matrix to create a new bitmap:


Matrix


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


RotateAnimation


View


fillAfter=true


duration=0


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);





danx.. But is dere ny way to do RotateAnimation on the View dynamically..i mean to set d angle dynamically..
– rijinrv
Jan 26 '12 at 7:00





this works better than the accepted answer if the image you need to rotate is in a ListView
– Daren
Mar 7 '14 at 0:03



I know this is insanely late, but it was helpful for me so it may help others.



As of API 11, you can set the absolute rotation of an ImageView programmatically by using the imageView.setRotation(angleInDegrees); method.


imageView.setRotation(angleInDegrees);



By absolute, I mean you can repeatedly call this function without having to keep track of the current rotation. Meaning, if I rotate by passing 15F to the setRotation() method, and then call setRotation() again with 30F, the image's rotation with be 30 degrees, not 45 degrees.


15F


setRotation()


setRotation()


30F



Note: This actually works for any subclass of the View object, not just ImageView.





My image at rotating gets naturally a little bit higher on the page. How can I set it down?
– I Wanna Know
Feb 13 at 14:41





Is your image centered properly? If you have an uneven amount of transparency in your image, rotation can cause it to appear to change position when rotating
– thomaspsk
Feb 13 at 18:09





No man, when image rotates it uses the axis. Imagine your cellphone in vertical position on your hand, now rotate it to horizontal. It doesn't touch your hand any more. So there's a space... But I solved it by using setPivotX()
– I Wanna Know
Feb 13 at 23:17



This is my implementation of RotatableImageView. Usage is very easy: just copy attrs.xml and RotatableImageView.java into your project and add RotatableImageView to your layout. Set desired rotation angle using example:angle parameter.


<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:example="http://schemas.android.com/apk/res/com.example"
android:layout_width="match_parent"
android:layout_height="wrap_content">

<com.example.views.RotatableImageView
android:id="@+id/layout_example_image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:adjustViewBounds="true"
android:scaleType="fitCenter"
android:src="@drawable/ic_layout_arrow"
example:angle="180" />
</FrameLayout>



If you have some problems with displaying image, try change code in RotatableImageView.onDraw() method or use draw() method instead.





Very helpful. Thanks for sharing!
– Stefan Hoth
Sep 12 '12 at 22:15





I got a NullPointerException while using RotatableImageView. protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) int w=getDrawable().getIntrinsicWidth(); ... BTW, I was use it in code(and have a given default image), not in xml.
– RRTW
Dec 21 '12 at 3:17






this imageView has weird issues when being used in a gridView. it keeps getting invisible till you scroll.
– android developer
Jan 27 '14 at 8:07



try this on a custom view


public class DrawView extends View


public DrawView(Context context,AttributeSet attributeSet)
super(context, attributeSet);


@Override
public void onDraw(Canvas canvas)
/*Canvas c=new Canvas(BitmapFactory.decodeResource(getResources(), R.drawable.new_minute1) );

c.rotate(45);*/

canvas.drawBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.new_minute1), 0, 0, null);
canvas.rotate(45);








Thank you very much it works for me...
– shripal
Nov 29 '13 at 4:10



here's a nice solution for putting a rotated drawable for an imageView:


Drawable getRotateDrawable(final Bitmap b, final float angle)
final BitmapDrawable drawable = new BitmapDrawable(getResources(), b)
@Override
public void draw(final Canvas canvas)
canvas.save();
canvas.rotate(angle, b.getWidth() / 2, b.getHeight() / 2);
super.draw(canvas);
canvas.restore();

;
return drawable;



usage:


Bitmap b=...
float angle=...
final Drawable rotatedDrawable = getRotateDrawable(b,angle);
root.setImageDrawable(rotatedDrawable);



another alternative:


private Drawable getRotateDrawable(final Drawable d, final float angle)
final Drawable arD = d ;
return new LayerDrawable(arD)
@Override
public void draw(final Canvas canvas)
canvas.save();
canvas.rotate(angle, d.getBounds().width() / 2, d.getBounds().height() / 2);
super.draw(canvas);
canvas.restore();

;



also, if you wish to rotate the bitmap, but afraid of OOM, you can use an NDK solution i've made here



just write this in your onactivityResult


Bitmap yourSelectedImage= BitmapFactory.decodeFile(filePath);
Matrix mat = new Matrix();
mat.postRotate((270)); //degree how much you rotate i rotate 270
Bitmap bMapRotate=Bitmap.createBitmap(yourSelectedImage, 0,0,yourSelectedImage.getWidth(),yourSelectedImage.getHeight(), mat, true);
image.setImageBitmap(bMapRotate);
Drawable d=new BitmapDrawable(yourSelectedImage);
image.setBackground(d);



I have a solution to this.
Actually it is a solution to a problem that arises after rotation(Rectangular image doesn't fit ImagView)
but it covers your problem too..
Although this Solution has Animation for better or for worse


int h,w;
Boolean safe=true;



Getting the parameters of imageView is not possible at initialisation of activity
To do so please refer to this solution
OR set the dimensions at onClick of a Button Like this


rotateButton.setOnClickListener(new View.OnClickListener()
@Override
public void onClick(View view)
if(imageView.getRotation()/90%2==0)
h=imageView.getHeight();
w=imageView.getWidth();


.
.//Insert the code Snippet below here



And the code to be run when we want to rotate ImageView


if(safe)
imageView.animate().rotationBy(90).scaleX(imageView.getRotation()/90%2==0?(w*1.0f/h):1).scaleY(imageView.getRotation()/90%2==0?(w*1.0f/h):1).setDuration(2000).setInterpolator(new LinearInterpolator()).setListener(new Animator.AnimatorListener()
@Override
public void onAnimationStart(Animator animation)
safe=false;


@Override
public void onAnimationEnd(Animator animation)
safe=true;



@Override
public void onAnimationCancel(Animator animation)



@Override
public void onAnimationRepeat(Animator animation)


).start();

});



This solution is sufficient for the Problem above.Although it will shrink the imageView even if it is not necessary(when height is smaller than Width).If it bothers you,you can add another ternary operator inside scaleX/scaleY.



Sadly, I don't think there is. The Matrix class is responsible for all image manipulations, whether it's rotating, shrinking/growing, skewing, etc.


Matrix



http://developer.android.com/reference/android/graphics/Matrix.html



My apologies, but I can't think of an alternative. Maybe someone else might be able to, but the times I've had to manipulate an image I've used a Matrix.



Best of luck!



Another possible solution is to create your own custom Image view(say RotateableImageView extends ImageView )...and override the onDraw() to rotate either the canvas/bitmaps before redering on to the canvas.Don't forget to restore the canvas back.


RotateableImageView extends ImageView



But if you are going to rotate only a single instance of image view,your solution should be good enough.



without matrix and animated:



img_view = (ImageView) findViewById(R.id.imageView);
rotate = new RotateAnimation(0 ,300);
rotate.setDuration(500);
img_view.startAnimation(rotate);



Try this code 100% working;



On rotate button click write this code:


@Override
public void onClick(View view)
if(bitmap==null)
Toast.makeText(getApplicationContext(), "Image photo is not yet set", Toast.LENGTH_LONG).show();

else
Matrix matrix = new Matrix();
ivImageProduct.setScaleType(ImageView.ScaleType.MATRIX); //required
matrix.postRotate(90,ivImageProduct.getDrawable().getBounds().width()/2,ivImageProduct.getDrawable().getBounds().height()/2);
Bitmap bmp=Bitmap.createBitmap(bitmap, 0, 0,bitmap.getWidth(), bitmap.getHeight(), matrix, true);
bitmap.recycle();
bitmap=bmp;
ivImageProduct.setImageBitmap(bitmap);




If you only want to rotate the view visually you can use:


iv.setRotation(float)



Rather than convert image to bitmap and then rotate it try to rotate direct image view like below code.


ImageView myImageView = (ImageView)findViewById(R.id.my_imageview);

AnimationSet animSet = new AnimationSet(true);
animSet.setInterpolator(new DecelerateInterpolator());
animSet.setFillAfter(true);
animSet.setFillEnabled(true);

final RotateAnimation animRotate = new RotateAnimation(0.0f, -90.0f,
RotateAnimation.RELATIVE_TO_SELF, 0.5f,
RotateAnimation.RELATIVE_TO_SELF, 0.5f);

animRotate.setDuration(1500);
animRotate.setFillAfter(true);
animSet.addAnimation(animRotate);

myImageView.startAnimation(animSet);



Follow the below answer for continuous rotation of an imageview


int i=0;



If rotate button clicked


imageView.setRotation(i+90);
i=i+90;



I think the best method :)


int angle = 0;
imageView.setOnClickListener(new View.OnClickListener()
@Override
public void onClick(View v)
angle = angle + 90;
imageView.setRotation(angle);

);






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

Firebase Auth - with Email and Password - Check user already registered

Dynamically update html content plain JS

Creating a leaderboard in HTML/JS