Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the rotate value from matrix in android?

How to the rotate value from a translated/scaled/rotated matrix?

Matrix matrix = new Matrix();
matrix.postScale(...);
matrix.postTranslate(...);
matrix.postRotate(...);
...

Now I don't know what the rotate it was, but I need to get it. How to do this?

like image 918
Freewind Avatar asked Sep 04 '12 04:09

Freewind


3 Answers

float[] v = new float[9];
matrix.getValues(v);
// translation is simple
float tx = v[Matrix.MTRANS_X];
float ty = v[Matrix.MTRANS_Y];

// calculate real scale
float scalex = v[Matrix.MSCALE_X];
float skewy = v[Matrix.MSKEW_Y];
float rScale = (float) Math.sqrt(scalex * scalex + skewy * skewy);

// calculate the degree of rotation
float rAngle = Math.round(Math.atan2(v[Matrix.MSKEW_X], v[Matrix.MSCALE_X]) * (180 / Math.PI));

from here http://judepereira.com/blog/calculate-the-real-scale-factor-and-the-angle-of-rotation-from-an-android-matrix/

like image 59
Sergei S Avatar answered Nov 17 '22 11:11

Sergei S


I can't enter equation here, so I make a picture of how to solve your problem. Here it is:

enter image description here

like image 34
Robust Avatar answered Nov 17 '22 09:11

Robust


In addition to previous answers, here is the Kotlin extension you need. It returns the rotation angle value of this matrix

fun Matrix.getRotationAngle() = FloatArray(9)
    .apply { getValues(this) }
    .let { -round(atan2(it[MSKEW_X], it[MSCALE_X]) * (180 / PI)).toFloat() }

Just need to call it on your matrix. Note that your matrix values won't be changed.

val angleInDegree = yourMatrix.getRotationAngle()
like image 3
Nicolas Duponchel Avatar answered Nov 17 '22 09:11

Nicolas Duponchel