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);
Solution 1:
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 onImageView
& 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.
Solution 2:
mImageView.setRotation(angle)
with API>=11
Solution 3:
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.