21

So, it appears to be fairly easy to do pinch zoom in android - but I would also like to be able to snap back the image when it goes out of bounds, and to do that the most reasonable thing seems to be to do things like when the scale < 1, rescale to 1. However, I can't seem to find a good way to retrieve the scale from the the graphics matrix.

One possible solution might be to map a point using the matrix's mapPoints function and see where it ends up, but in addition to being trickly, that just feels ugly and indirect to me. Are there any better solutions for retrieving the scale from an Android graphics matrix?

Community
  • 1
  • 1
OverclockedTim
  • 1,713
  • 2
  • 12
  • 22
  • Note that scale and zoom are very different in Matrices, see this answer http://stackoverflow.com/questions/12260260/how-to-get-zoom-value-of-arbitrary-matrix – Artur Mar 31 '17 at 01:09

2 Answers2

58
float[] f = new float[9];
matrix.getValues(f);

float scaleX = f[Matrix.MSCALE_X];
float scaleY = f[Matrix.MSCALE_Y];

will probably be what you are looking for. the values given will be as followed:

0 : Scale X

1 : Skew X

2 : Translate X

3 : Scale Y

4 : Skew Y

5 : Translate Y

6 : Perspective 0

7 : Perspective 1

8 : Perspective 2

Evan Leis
  • 494
  • 5
  • 13
Henrik
  • 1,147
  • 2
  • 11
  • 22
  • 4
    Thanks, I had also passed over this part of the documentation. If you use this, though, it's probably best to use the constants provided in the Matrix class. For example, use `Matrix.MSCALE_X` instead of 0 for the 'Scale X' index. – potatoe Apr 04 '11 at 19:27
  • Note that position 3 is Skew-Y, not Scale-Y. Further proof that it's better to use the constants. – scottt Sep 04 '19 at 23:52
0

Here's a simple method to log the matrix contents:

private void logMatrix(String label, Matrix matrix) {
    float[] matrixVals = new float[9];
    matrix.getValues(matrixVals);
    Log.e(TAG, String.format("%s: %s\nscale (x,y) = (%f, %f)\ntranslate (x,y) = (%f, %f)\nskew (x,y) "
                             + "= (%f, %f)\nperspective-0 = %f\nperspective-1 = %f\nperspective-2 = %f",
        label, matrix, matrixVals[Matrix.MSCALE_X], matrixVals[Matrix.MSCALE_Y],
        matrixVals[Matrix.MTRANS_X], matrixVals[Matrix.MTRANS_Y],
        matrixVals[Matrix.MSKEW_X], matrixVals[Matrix.MSKEW_Y],
        matrixVals[Matrix.MPERSP_0], matrixVals[Matrix.MPERSP_1], matrixVals[Matrix.MPERSP_2]));
}
scottt
  • 8,301
  • 1
  • 31
  • 41