Search code examples
androidmatrixrotationimageviewscale

Using setRotate rescales the imageview


I'm using the following code in order to rotate an imageview :

Matrix matrix=new Matrix();
matrix.setRotate((float) angle,main_needle.getWidth()/2, (float)(main_needle.getHeight()/1.1787));
main_needle.setImageMatrix(matrix);

The problem is that this code also rescales the imageview . I tried adding the setScale to my code but it didn't help.

Matrix matrix=new Matrix();
matrix.setRotate((float) angle,main_needle.getWidth()/2, (float)(main_needle.getHeight()/1.1787));     
matrix.setScale(main_needle.getWidth(), main_needle.getHeight());
main_needle.setImageMatrix(matrix); 

I updated the code based on the comment to this :

Matrix matrix=new Matrix();
matrix.setRotate((float) angle,main_needle.getWidth()/2, (float)(main_needle.getHeight()/1.1787));
matrix.setScale((int)(main_needle.getWidth()/Math.cos((double)angle)),(int)( main_needle.getHeight()/Math.sin((double)angle)));
main_needle.setScaleType(ScaleType.MATRIX);  
main_needle.setImageMatrix(matrix);

But this code just makes the imageview disapear

The easiest fix I used is to scale down the image in photoshop so that the pixels match the dp for example an image set in xml at 70dp by 100dp should use a drawable 70 by 100 pixel .Thanks everyone for your responces.


Solution

  • You need to use matrix.postRotate(); And this one is must

    Matrix matrix=new Matrix(); 
    main_needle.setScaleType(ScaleType.MATRIX);
    matrix.postRotate((float) i,main_needle.getWidth()/2, (float)(main_needle.getHeight()/1.1787)); 
    main_needle.setImageMatrix(matrix);
    

    Actually thats because you try to rotate a view in a linear layout. And this will cause its dedicated space to expand or shrink.

    Idea 1: try using a frame layout have and your view rotate inside there Idea 2: try a custom view subclass and draw your turntable in the onDraw. In the internet look for a compass drawing example for start.