2

Actually I programming a app that use image rotation. But when I rotate image, it doesn't show anything.

This is my code:

XML file:

<?xml version="1.0" encoding="utf-8" ?>

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/rotate_test_layout"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <ImageView
        android:id="@+id/android"
        android:src="@drawable/android"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_gravity="center"
        android:scaleType="matrix"
        android:adjustViewBounds="true"
        android:contentDescription="@string/android_description" >
    </ImageView>

</LinearLayout>

Activity file:

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.rotate_test_layout);
    ImageView imageView = (ImageView)findViewById(R.id.android);
    imageView.setScaleType(ScaleType.MATRIX);
    Matrix matrix = new Matrix();
    matrix.postRotate(90);
    imageView.setImageMatrix(matrix);
}
Vahid Javaherifar
  • 155
  • 1
  • 2
  • 8

2 Answers2

1

You are making a mistake here:

imageView.setImageMatrix(matrix);

Instead of doing that you have to apply that matrix to the existing Bitmap to get a new bitmap which you can then assign to the ImageView.

Drawable drawable = getResources().getDrawables(R.drawable.android);
Bitmap existingBitmap = ((BitmapDrawable) drawable).getBitmap();
Bitmap rotated = Bitmap.createBitmap(existingBitmap, 0, 0, existingBitmap.getWidth(), existingBitmap.getHeight(), matrix, true);
imageView.setImageBitmap(rotated);
A Random Android Dev
  • 2,691
  • 1
  • 18
  • 17
  • This method will cause OOM on big bitmaps. There is a post talking about this issue with this solution. http://stackoverflow.com/a/10104318/2123400 But for me this solution doesn't work as your answer tells why. I'm confused why lot's of people could rotate ImageView's image without creating new bitmap. – Eftekhari May 30 '16 at 15:22
-1

You can rotate ImageView without using matrix. test it.

imageView.setRotation(90.0f); 
daniula
  • 6,898
  • 4
  • 32
  • 49