vxh.viet

5/10/2017 - 2:55 AM

Android image transformation matrix stuff.

**Useful image transformation matrix **

*Source:* Math StackExchange

- Calculate the difference between 2 matrices. This difference matrix can then be postconcated to another matrix to make that matrix have the same transformation. In the image below, A after some translation, scaling, rotation turns into A'. In order for B to have those same transformation, we calculate the diff matrix between A and A', then we post concat it with B's current matrix.

```
/**
* <pre>
* Calculate the difference between the old transformation matrix and the new matrix, based on the following formula:
* Difference = (O) * (N^-1)
* O: old transformation matrix.
* N: new matrix.
* Source: https://math.stackexchange.com/q/1399401
* Position is very important in matrix operation.
*
* This one has been tested with rotate, scale, translation.
* </pre>
*
* @param oldMatrix the matrix to calculate the difference from
* @param newMatrix the new input matrix.
* @return a matrix that represent the difference from the old matrix.
*/
public static Matrix getDifferenceMatrix(Matrix oldMatrix, Matrix newMatrix){
Matrix diffMatrix = new Matrix();
newMatrix.invert(diffMatrix);
diffMatrix.postConcat(oldMatrix);
diffMatrix.invert(diffMatrix);
return diffMatrix;
}
```

*Source:* StackOverFlow

- Convenient method to have a matrix that have a set of scaling and translate value to scale and center one rect to another rect. One note,
`Rect`

in android doesn't rotate. After we rotate an image it will only result in a new`Rect`

that can fit all those new corners.

```
Matrix m = new Matrix();
RectF drawableRect = new RectF(0, 0, imageWidth, imageHeight);
RectF viewRect = new RectF(0, 0, imageView.getWidth(), imageView.getHeight());
m.setRectToRect(drawableRect, viewRect, Matrix.ScaleToFit.CENTER);
imageView.setImageMatrix(m);
```