MatrixTransform

I’m been working on some WPF/E samples and I needed to do a mirror rotation. Although I could do this with a combination of canned transformations I prefer to use the general MatrixTransform. This is easy to do if you understand the affine transformation formula and know the mini-language for the MatrixTransform Matrix property. Unfortunately, I typically forgot both of these five minutes after using them and when I need to use a MatrixTransform again I am left to hunt for old samples. There are lots of resources on affine transformations, so I’m not going to go into great details but will provide the very basics you need to know to make use of a MatrixTransform in WPF/E (or WPF).

An affine transformation is a linear transformation - meaning if the input is a line, the output will be a line. Affine transformations are used to rotate, skew, scale and translate a set of points and are described using a matrix based mathematical formula. Rather than describing them using matrix notation, I’m going to show the fairly simple translation calculation (using WPF constant names).

A point, X,Y is translated into a new point, X’,Y’ using the following formula:

X1 = X*M11 + Y*M21+ OffsetX
Y1 = X*M12 + Y*M22+ OffsetY

In WPF/E (and WPF), the MatrixTransform Matrix property uses the above constants as follows:

<MatrixTransform Matrix="M11, M12, M21, M22, OffsetX, OffsetY"/>

With these two pieces of information, it’s fairly easy to generate simple transformations. For example, to scale a path 2X in the X direction:

<Path Stroke="Black" StrokeThickness="1" Data="M0,0 L100,100">

<Path.RenderTransform>

<MatrixTransform Matrix="2, 0, 0, 1, 0, 0"/>

</Path.RenderTransform>

</Path>

Or to translate a path 100 pixels in the X and Y direction:

<Path Stroke="Black" StrokeThickness="1" Data="M0,0 L100,100">

<Path.RenderTransform>

<MatrixTransform Matrix="1, 0, 0, 1, 100, 100"/>

</Path.RenderTransform>

</Path>

Or in my case, to do a mirror transform (rotate around the X axis):

<Path Stroke="Black" StrokeThickness="1" Data="M0,0 L100,100">

<Path.RenderTransform>

<MatrixTransform Matrix="1, 0, 0, -1, 0, 0"/>

</Path.RenderTransform>

</Path>