MatrixTransform
In recent articles we've seen the standard transforms provided by WPF, which allow you to change the shape of controls and other user interface elements. Each transforms a shape in two-dimensional space. Behind the scenes, the transforms work by multiplying a transformation matrix and the co-ordinates of the item. You can obtain the details of the matrix by reading the transform's Value property.
If you wish, instead of allowing the matrix to be determined for you, you can create one yourself using the Matrix structure and the MatrixTransform class. This can simplify the process of transforming an object.
Matrix Calculation
The Matrix class defines six properties, each of which corresponds to one of six values in a 3 × 3 matrix. This matrix is multiplied by a 1 × 3 matrix representing the co-ordinates of every point in the item being manipulated. The calculation performed is shown below:
![MatrixTransform equation](images/MatrixTransform1.png)
The M11 and M22 properties both default to 1. They act as multipliers for the x and y co-ordinates of elements of the control, scaling the item. M12 and M21 can be used to skew a control. These default to zero, as do OffsetX and OffsetY, which translate the shape.
As an example, consider the formula below. Here M11 has been changed from its default value. As it is set to 2, the width of the shape is doubled. The height is not modified.
![MatrixTransform scale transform](images/MatrixTransform2.png)
Changing M12 and M21 means that the multiplication results combine products of x and y in both resultant co-ordinates. This skews the transformed item.
![MatrixTransform skew transform](images/MatrixTransform3.png)
As you have access to all six of the key matrix values, you can combine them to scale, skew and translate the target element in a single operation.
![MatrixTransform custom transform](images/MatrixTransform4.png)
MatrixTransform in XAML
When you are working with a Matrix you can set the six properties individually, either using code, in a language such as C#, or XAML, with property element syntax. However, if you are using XAML, you can set all of the properties in a single string. To do so, combine the values in the order M11, M12, M21, M22, OffsetX, OffsetY.
The following XAML creates a window containing a TextBox. The TextBox is transformed with a MatrixTransform using the matrix shown in the final equation above.
<Window x:Class="MatrixTransformDemo.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Transform Demo" Height="230" Width="250">
<Grid>
<TextBox Height="40" Width="200" Text="Transform" FontSize="30" Background="Plum">
<TextBox.RenderTransform>
<MatrixTransform Matrix="1 0.3 0 2 10 -50" />
</TextBox.RenderTransform>
</TextBox>
</Grid>
</Window>
When rendered, the text box is scaled, skewed and translated.
![MatrixTransform in XAML](images/MatrixTransform5.png)
24 March 2015