#753 – Scale vs. Expansion in ManipulationDelta Events

When handling a ManipulationDelta event during touch manipulation, you often care about the ManipulationDelta.Scale property, which indicates the updated scale of an element, relative to its previous size (e.g. 0.5 = 1/2 size).

You can also access a ManipulationDelta.Expansion property, which tells you the actual number of device independent units (1/96th in) that the element is changing, relative to its last known size.

The example below dumps out both scale and expansion values as we scale with touch.

```        private Vector totalScale = new Vector(1.0, 1.0);
private Vector totalExpansion = new Vector(0.0, 0.0);

private void Image_ManipulationDelta(object sender, ManipulationDeltaEventArgs e)
{
ManipulationDelta md = e.DeltaManipulation;

totalScale.X *= md.Scale.X;
totalScale.Y *= md.Scale.Y;

totalExpansion.X += md.Expansion.X;
totalExpansion.Y += md.Expansion.Y;

Console.WriteLine(string.Format(
"Scale: {0},{1}.  Expansion: {2},{3}",
md.Scale.X, md.Scale.Y, md.Expansion.X, md.Expansion.Y));
Console.WriteLine(string.Format(
"  Total Scale: {0},{1}.  Total Expansion: {2},{3}",
totalScale.X, totalScale.Y, totalExpansion.X, totalExpansion.Y));
}
``` #752 – Tracking Total Scale when Scaling by Touch Manipulation

When you use touch manipulation events to scale an element, you typically read the Scale property of the ManipulationDelta object passed in to the ManipulationDelta event handler.   This property reports a delta scaling value to apply to the element, derived from the user’s touch manipulation (e.g. pinch/expand).

For example, a scale value of 1.05 says “scale the object 5% larger than it was the last time that this event was fired”.

In the code example below, we also track total scale, relative to the original size of the element.  (Note that we don’t actually scale the element here).

```        private Vector totalScale = new Vector(1.0, 1.0);

private void Image_ManipulationDelta(object sender, ManipulationDeltaEventArgs e)
{
ManipulationDelta md = e.DeltaManipulation;
Vector scale = md.Scale;

totalScale.X *= scale.X;
totalScale.Y *= scale.Y;

Console.WriteLine(string.Format(
"Scale: X={0}, Y={1}, TotalScale: X={2}, Y={3}",
scale.X, scale.Y, totalScale.X, totalScale.Y));

e.Handled = true;
}
``` #744 – Keeping an Element within Window During Touch Manipulation

You can use the ManipulationDelta event handler to translate a user interface element in response to the user touching and dragging it.  In the previous code, there was nothing preventing the user from sliding the element off of the screen.

We can make the element stop when it hits a window boundary by checking its bounds against the bounds of its parent.  Below is the update code for the ManipulationDelta event handler that does the checking.  (See earlier example for the full code sample).

```        private void Image_ManipulationDelta(object sender, ManipulationDeltaEventArgs e)
{
ManipulationDelta md = e.DeltaManipulation;
Vector trans = md.Translation;

Matrix m = imageTransform.Matrix;

// Find center of element and then transform to get current location of center
FrameworkElement fe = e.Source as FrameworkElement;
Point center = new Point(fe.ActualWidth / 2, fe.ActualHeight / 2);
center = m.Transform(center);

// Check to see if element is at one of the edges of the window
FrameworkElement feParent = fe.Parent as FrameworkElement;
bool atEdge = false;
if (feParent != null)
{
Rect feRect = fe.TransformToAncestor(feParent).TransformBounds(
new Rect(0.0, 0.0, fe.ActualWidth, fe.ActualHeight));
atEdge = (feRect.Right + trans.X) > feParent.ActualWidth ||
(feRect.Bottom + trans.Y) > feParent.ActualHeight ||
(feRect.Left + trans.X) < 0 ||
(feRect.Top + trans.Y) < 0;
}

// Update matrix to reflect translation
if (!atEdge)
m.Translate(trans.X, trans.Y);

imageTransform.Matrix = m;
RaisePropertyChanged("ImageTransform");

e.Handled = true;
}
```

#743 – Using Touch Manipulation Events to Scale an Element

In the previous post, we used a ManipulationDelta object in the ManipulationDelta event handler to both translate and rotate a user interface element.  The user’s touch gestures for translation (sliding finger) and rotation (rotating two fingers) were automatically captured and available in the Translation and Rotation properties of the ManipulationDelta object.

We can also support scaling of an element using the ManipulationDelta event.  The ManipulationDelta object also contains a Scale property, which stores a Vector that indicates the target scale for the object (e.g. scale of 0.5 indicates 1/2 size).  This property is automatically set when a user uses two fingers on an element in a pinch or spread gesture, indicating that they want to zoom in or out of the element.

The sample code below supports all translation, rotation and scaling of an Image element.

```    <Canvas Name="canvMain" Background="Transparent">
<Image Source="JamesII.jpg" Width="100"
IsManipulationEnabled="True"
RenderTransform="{Binding ImageTransform}"
ManipulationStarting="Image_ManipulationStarting" ManipulationDelta="Image_ManipulationDelta"/>
</Canvas>
```

Below is the code-behind for this sample.  Note that we now apply translation, rotation and scaling to the underlying matrix.

```    public partial class MainWindow : Window, INotifyPropertyChanged
{
public MainWindow()
{
InitializeComponent();
this.DataContext = this;

ImageTransform = new MatrixTransform();
}

private MatrixTransform imageTransform;
public MatrixTransform ImageTransform
{
get { return imageTransform; }
set
{
if (value != imageTransform)
{
imageTransform = value;
RaisePropertyChanged("ImageTransform");
}
}
}

private void Image_ManipulationStarting(object sender, ManipulationStartingEventArgs e)
{
// Ask for manipulations to be reported relative to the canvas
e.ManipulationContainer = canvMain;
}

private void Image_ManipulationDelta(object sender, ManipulationDeltaEventArgs e)
{
ManipulationDelta md = e.DeltaManipulation;
Vector trans = md.Translation;
double rotate = md.Rotation;
Vector scale = md.Scale;

Matrix m = imageTransform.Matrix;

// Find center of element and then transform to get current location of center
FrameworkElement fe = e.Source as FrameworkElement;
Point center = new Point(fe.ActualWidth / 2, fe.ActualHeight / 2);
center = m.Transform(center);

// Update matrix to reflect translation/rotation
m.Translate(trans.X, trans.Y);
m.RotateAt(rotate, center.X, center.Y);
m.ScaleAt(scale.X, scale.Y, center.X, center.Y);

imageTransform.Matrix = m;
RaisePropertyChanged("ImageTransform");

e.Handled = true;
}

public event PropertyChangedEventHandler PropertyChanged;

private void RaisePropertyChanged(string prop)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(prop));
}
}
```

#742 – Using Touch Manipulation Events to Rotate an Element

In addition to using the touch manipulation events to handle translation of an element, we can use the same mechanisms to allow a user to rotate an element using touch.

We can do both translation and rotation in the same event handler.  The ManipulationDelta object gives us both a translation (vector) and a rotation (angle).  Both are automatically incorporated into the ManipulationDelta object, based on how the user is touching the screen.  The user can translate by sliding one finger around and can rotate by placing two fingers on the object and rotating it.

We transform the element by calling two different functions of the underlying Matrix, for both translation and rotation.

Here’s the XAML, containing a single Image control that we’ll interact with.

```    <Canvas Name="canvMain" Background="Transparent">
<Image Source="JamesII.jpg" Width="100"
IsManipulationEnabled="True"
RenderTransform="{Binding ImageTransform}"
ManipulationStarting="Image_ManipulationStarting" ManipulationDelta="Image_ManipulationDelta"/>
</Canvas>
```

Here is the source code, with the updated ManipulationDelta event handler.

```    public partial class MainWindow : Window, INotifyPropertyChanged
{
public MainWindow()
{
InitializeComponent();
this.DataContext = this;

ImageTransform = new MatrixTransform();
}

private MatrixTransform imageTransform;
public MatrixTransform ImageTransform
{
get { return imageTransform; }
set
{
if (value != imageTransform)
{
imageTransform = value;
RaisePropertyChanged("ImageTransform");
}
}
}

private void Image_ManipulationStarting(object sender, ManipulationStartingEventArgs e)
{
// Ask for manipulations to be reported relative to the canvas
e.ManipulationContainer = canvMain;
}

private void Image_ManipulationDelta(object sender, ManipulationDeltaEventArgs e)
{
ManipulationDelta md = e.DeltaManipulation;
Vector trans = md.Translation;
double rotate = md.Rotation;

Matrix m = imageTransform.Matrix;

// Find center of element and then transform to get current location of center
FrameworkElement fe = e.Source as FrameworkElement;
Point center = new Point(fe.ActualWidth / 2, fe.ActualHeight / 2);
center = m.Transform(center);

// Update matrix to reflect translation/rotation
m.Translate(trans.X, trans.Y);
m.RotateAt(rotate, center.X, center.Y);

imageTransform.Matrix = m;
RaisePropertyChanged("ImageTransform");

e.Handled = true;
}

public event PropertyChangedEventHandler PropertyChanged;

private void RaisePropertyChanged(string prop)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(prop));
}
}
``` #741 – Using Touch Manipulation Events to Translate an Element

You can use the touch manipulation events to translate an element, that is, to move it around on the screen.

To start with, you set the IsManipulationEnabled property of the element to true.  This allows the manipulation events to be fired.  You also handle both the ManipulationStarting and ManipulationDelta events.

```    <Canvas Name="canvMain" Background="Transparent">
<Image Source="JamesII.jpg" Width="100"
IsManipulationEnabled="True"
RenderTransform="{Binding ImageTransform}"
ManipulationStarting="Image_ManipulationStarting" ManipulationDelta="Image_ManipulationDelta"/>
</Canvas>
```

Below is the code that allows the image to be moved around (translated) as the user moves their finger.  We bind the image’s render transform to a MatrixTransform object, which contains a matrix that allows us to scale, rotate or translate the image.  In our case, we modify the translation part of the matrix with the translation vector returned in the ManipulationDelta event.

```    public partial class MainWindow : Window, INotifyPropertyChanged
{
public MainWindow()
{
InitializeComponent();
this.DataContext = this;

ImageTransform = new MatrixTransform();
}

private MatrixTransform imageTransform;
public MatrixTransform ImageTransform
{
get { return imageTransform; }
set
{
if (value != imageTransform)
{
imageTransform = value;
RaisePropertyChanged("ImageTransform");
}
}
}

private void Image_ManipulationStarting(object sender, ManipulationStartingEventArgs e)
{
// Ask for manipulations to be reported relative to the canvas
e.ManipulationContainer = canvMain;
}

private void Image_ManipulationDelta(object sender, ManipulationDeltaEventArgs e)
{
ManipulationDelta md = e.DeltaManipulation;
Vector trans = md.Translation;

// Update matrix to reflect translation
Matrix m = imageTransform.Matrix;
m.Translate(trans.X, trans.Y);
imageTransform.Matrix = m;
RaisePropertyChanged("ImageTransform");

e.Handled = true;
}

public event PropertyChangedEventHandler PropertyChanged;

private void RaisePropertyChanged(string prop)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(prop));
}
}
``` 