'How do I fill Matrix4 with translation, skew and scale values in flutter?

Suppose, I have these values for a container of height 200 and width 300:

  • scaleX = 0.9198
  • scaleY = 0.9198
  • skewX = -0.3923
  • skewY = 0.3923
  • translateX = 150
  • translateY = 150

Now, how do I fill this values in Matrix4 correctly?

I tried doing this:

Matrix4(
  0.9198, 0, 0, 0, //
  0, 0.9198, 0, 0, //
  0, 0, 1, 0, //
  150, 150, 0, 1,
)

which is,

Matrix4(
  scaleX, 0, 0, 0, //
  0, scaleY, 0, 0, //
  0, 0, 1, 0, //
  translateX, translateY, 0, 1,
)

But I am not sure where to put skewX and skewY values in this matrix. Please help me with this.



Solution 1:[1]

Skew Values

This is a bit of a nuanced topic, as it could be interpreted in a couple of different ways. There are specific cells of a matrix that are associated with specific names, as identified in your question, translate x, translate y, scale x, and scale y. In this context, you most likely mean the values from a matrix that are called skew x and skew y (also sometimes known as shear x and shear y), which refers to indices 4 and 1 (zero-based, column-major order). They're called these names because when put into an identity matrix by themselves, they do that operation (translate, scale, or skew), but it gets more complicated when there are multiple values.

On the other hand, this could also be interpreted as a series of operations (e.g. scale by (0.9198, 0.9198, 1), then skew by (-0.3923, 0.3923), then translate by (150, 150, 0)), and then it's a series of matrix multiplications that would ultimately result in a similar-looking, but numerically different matrix. I'll assume you don't mean this for this question. You can read more about it here though.

You can consult the Flutter Matrix4 documentation, which also provides implementation notes for Matrix4.skewX and Matrix4.skewY. The skews are stored in (zero-based) indices 4, and 1, as the tangent of the skewed angle.

Matrix4(
  scaleX, skewY,   0,   0, // skewY could also be tan(ySkewAngle)
  skewX,  scaleY,  0,   0, // skewX could also be tan(xSkewAngle)
  0,      0,       1,   0, //
  translateX, translateY, 0, 1,
)

Note to those that aren't familiar with Flutter's data structures that values are stored in column-major order which means that each row in the above code is actually a column, so if you were to represent the matrix as a normal transformation matrix, it's transposed.

More information:

Transformation Matrices: https://en.wikipedia.org/wiki/Transformation_matrix

How matrices are used with CSS Transforms: How do I use the matrix transform and other transform CSS properties?

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 G H Prakash