Tuesday 8 June 2010

2D Matrix transforms in Silverlight

“A 3x3 matrix is used for transformations in a two-dimensional x-y plane. Affine transformation matrices can be multiplied to form any number of linear transformations, such as rotation and skew (shear), followed by translation. An affine transformation matrix has its final column equal to (0, 0, 1), so only the members in the first two columns need to be specified. Note that vectors are expressed as row-vectors, not column vectors.” *

Affine transformations preserve collinearity and relative distancing in a transformed coordinate space:

  • Points on a line will remain in a line after an affine transformation
  • Parallel lines remain parallel
  • Relative spacing or distancing will always maintain at a consistent ratio.

Affine transformations allow for repositioning, scaling, skewing and rotation. Things they cannot do include tapering or distorting with perspective.

The transformation matrix looks like this (default values in brackets):

M11 (1.0) M12 (0.0) 0
M21 (0.0) M22 (1.0) 0
OffX (0.0) OffY (0.0) 1

The elements ion the matrix map as follows:

  • M11 = X Scale
  • M12 = Y Skew
  • M21 = X Skew
  • M22 = Y Scale
  • OffX = translation on X axis
  • OffY = translation on Y axis

Or:

X Scale Y Skew 0
X Skew Y Scale 0
X translation Y translation 1

Note you cannot change the values of the 3rd column in the Matrix class (i.e. 0, 0, 1).

For example, to create a matrix that scales but changes no other parameters:

double scaleX = 0.5;
double scaleY = 0.5;
Matrix mx = new Matrix(scaleX, 0.0, 0.0, scaleY, 0.0, 0.0);

A quick bit of revision; the following is an identity matrix:

1 0 0
0 1 0
0 0 1

This applies no transformation whatsoever:

x' = x*1 + y*0 + 0
y' = x*0 + y*1 + 0

which reduces to

x' = x
y' = y

Note that the the matrix for the point will be [x, y, 1].

* Matrix Structure - http://msdn.microsoft.com/en-us/library/system.windows.media.matrix%28v=VS.95%29.aspx

See also: