#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;
        }

752-001

Advertisement

#751 – Indicating which Touch Manipulation Modes You Support

When you support touch manipulation events, you can choose which types of touch manipulation to support for an element.  The modes include:

  • Translation (in X, Y, or both)
  • Rotation
  • Scaling

You indicate which modes you want to support within the ManipulationStarting event handler, setting the ManipulationStartingEventArgs.Mode property.  You can set this property to some combination of :

  • ManipulationModes.None
  • ManipulationModes.TranslateX
  • ManipulationModes.TranslateY
  • ManipulationModes.Translate
  • ManipulationModes.Rotate
  • ManipulationModes.Scale
  • ManipulationModes.All

When you enable a mode, the ManipulationDelta event will fire when a user manipulates the element using touch, and will include data for that style of manipulation.  When a manipulation mode isn’t supported, the ManipulationDelta event will not fire for that mode.  It may fire for other manipulation actions, but will not include data for modes that are disabled.

The mode values listed above can be combined using the OR (|) operator.

            // Support translation and scaling
            e.Mode = ManipulationModes.Translate | ManipulationModes.Scale;

#750 – Using Touch Manipulation to Translate in Just One Dimension

You can set the IsManipulationEnabled property and handle the ManipulationDelta event for an element, to support translating (moving) the element using touch.

By default, when you read the ManipulationDelta.Translation property, it will contain translation values for both X and Y.  If you want to allow moving the element only horizontally or vertically, you can handle the ManipulationStarting event and set the ManipulationStartingEventArgs.Mode property to either TranslateX or TranslateY.

The example below shows how we could limit translation to be only horizontal.  You could do the same thing by ignoring the Y component of the Translation property in the ManipulationDelta event handler.

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

            // Allow only horizontal translation
            e.Mode = ManipulationModes.TranslateX;
        }

#746 – Specifying Inertial Deceleration

In WPF, you can use inertia so that objects will continue moving on the screen after you lift your finger off the screen.

Calculation of inertial behavior requires both an initial velocity and a deceleration.  WPF knows the initial velocity of an object, based on how fast you are moving it on the screen.  The deceleration value is something that you specify.

Initial velocity values are typically in the range of around 0-4 DIPs/ms (DIPs per millisecond), or 0-42 in/sec.

Deceleration is expressed in DIPs/ms^2 (DIPs per millisecond squared).  If we want to decelerate to 0 within about 1/2 sec, we can use values in the range of  0-0.008 DIPs/ms^2.  (4 / 500).  This is equivalent to 83 ft/sec^2.

If you start with a deceleration value in in/sec^2, you can convert to DIPs/ms^2 using the formula:

x’ = x * 96 / (1000 * 1000)

You can experiment with different deceleration values to get the exact deceleration behavior that you want in your application.

#745 – The Basics of Inertia

Inertia is the idea that an object will resist a change in motion.  For touch manipulation in WPF, inertia means that objects can continue moving a little bit after you lift your finger from the screen.

Inertial behavior depends on two things–the initial velocity of the object a specified deceleration value.

The initial velocity is the speed at which the object is moving across the screen when you let go of it.  The deceleration is the rate at which the initial velocity should be decreased, until it eventually reaches zero.  In other words–how quickly does the object slow down?

The deceleration value has units that are DIPs (device independent pixels) per ms^2 (millisecond squared, or “per millisecond per millisecond”).  I.e. DIPs/ms^2.  In other words, if the object’s initial velocity is expressed in DIPs/ms, how much should that velocity decrease every millisecond?

#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));
        }
    }

#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));
        }
    }

741-001