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)f
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);
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.
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.
Note: This actually works for any subclass of the View object, not just ImageView.
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.
Can also be done this way:-
imageView.animate().rotation(180).start();
got from here.
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);
For Kotlin,
mImageView.rotation = 90f //angle in float
This will rotate the imageView rather than rotating the image
Also, though its a method in View
class. So you can pretty much rotate any view using it.