Compartilhar via


Passo a passo: criando seu primeiro aplicativo touch

O WPF permite que os aplicativos respondam ao toque. Por exemplo, você pode interagir com um aplicativo usando um ou mais dedos em um dispositivo sensível ao toque, como uma tela sensível ao toque Este passo a passo cria um aplicativo que permite que o usuário mova, redimensione ou gire um único objeto usando o toque.

Pré-requisitos

Você precisa dos seguintes componentes para concluir este passo a passo:

  • Visual Studio.

  • Um dispositivo que aceita entrada por toque, como uma tela sensível ao toque, que dá suporte ao Windows Touch.

Além disso, você deve ter uma compreensão básica de como criar um aplicativo no WPF, especialmente como assinar e lidar com um evento. Para obter mais informações, consulte Passo a passo: Meu Primeiro Aplicativo Desktop WPF.

Criando o aplicativo

Para criar o aplicativo

  1. Crie um novo projeto de aplicativo WPF no Visual Basic ou no Visual C# chamado BasicManipulation. Para obter mais informações, consulte Passo a passo: Meu Primeiro Aplicativo Desktop do WPF.

  2. Substitua o conteúdo de MainWindow.xaml pelo XAML a seguir.

    Essa marcação cria um aplicativo simples que contém um Rectangle vermelho em um Canvas. A propriedade IsManipulationEnabled do Rectangle é definida como true para que ele receba eventos de manipulação. O aplicativo assina os eventos ManipulationStarting, ManipulationDelta e ManipulationInertiaStarting. Esses eventos contêm a lógica para mover a Rectangle quando o usuário a manipula.

    <Window x:Class="BasicManipulation.MainWindow"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            Title="Move, Size, and Rotate the Square"
            WindowState="Maximized"
            ManipulationStarting="Window_ManipulationStarting"
            ManipulationDelta="Window_ManipulationDelta"
            ManipulationInertiaStarting="Window_InertiaStarting">
      <Window.Resources>
    
        <!--The movement, rotation, and size of the Rectangle is 
            specified by its RenderTransform.-->
        <MatrixTransform x:Key="InitialMatrixTransform">
          <MatrixTransform.Matrix>
            <Matrix OffsetX="200" OffsetY="200"/>
          </MatrixTransform.Matrix>
        </MatrixTransform>
    
      </Window.Resources>
    
      <Canvas>
        <Rectangle Fill="Red" Name="manRect"
                     Width="200" Height="200" 
                     RenderTransform="{StaticResource InitialMatrixTransform}"
                     IsManipulationEnabled="true" />
      </Canvas>
    </Window>
    
    
  3. Se você estiver usando o Visual Basic, na primeira linha de MainWindow.xaml, substitua x:Class="BasicManipulation.MainWindow" por x:Class="MainWindow".

  4. Na classe MainWindow, adicione o seguinte manipulador de eventos ManipulationStarting.

    O evento ManipulationStarting ocorre quando o WPF detecta que a entrada de toque começa a manipular um objeto. O código especifica que a posição da manipulação deve ser relativa à Window definindo a propriedade ManipulationContainer.

    void Window_ManipulationStarting(object sender, ManipulationStartingEventArgs e)
    {
        e.ManipulationContainer = this;
        e.Handled = true;
    }
    
    Private Sub Window_ManipulationStarting(ByVal sender As Object, ByVal e As ManipulationStartingEventArgs)
        e.ManipulationContainer = Me
        e.Handled = True
    End Sub
    
  5. Na classe MainWindow, adicione o seguinte manipulador de eventos ManipulationDelta.

    O evento ManipulationDelta ocorre quando a entrada por toque muda de posição e pode ocorrer várias vezes durante uma manipulação. O evento também pode ocorrer depois que um dedo é levantado. Por exemplo, se o usuário arrastar um dedo por uma tela, o evento ManipulationDelta ocorrerá várias vezes à medida que o dedo se move. Quando o usuário levanta um dedo da tela, o evento ManipulationDelta continua ocorrendo para simular inércia.

    O código aplica o DeltaManipulation à RenderTransform do Rectangle para movê-lo à medida que o usuário move a entrada tátil. Ele também verifica se o Rectangle está fora dos limites da Window quando o evento ocorre durante a inércia. Nesse caso, o aplicativo chama o método ManipulationDeltaEventArgs.Complete para encerrar a manipulação.

    void Window_ManipulationDelta(object sender, ManipulationDeltaEventArgs e)
    {
    
        // Get the Rectangle and its RenderTransform matrix.
        Rectangle rectToMove = e.OriginalSource as Rectangle;
        Matrix rectsMatrix = ((MatrixTransform)rectToMove.RenderTransform).Matrix;
    
        // Rotate the Rectangle.
        rectsMatrix.RotateAt(e.DeltaManipulation.Rotation,
                             e.ManipulationOrigin.X,
                             e.ManipulationOrigin.Y);
    
        // Resize the Rectangle.  Keep it square
        // so use only the X value of Scale.
        rectsMatrix.ScaleAt(e.DeltaManipulation.Scale.X,
                            e.DeltaManipulation.Scale.X,
                            e.ManipulationOrigin.X,
                            e.ManipulationOrigin.Y);
    
        // Move the Rectangle.
        rectsMatrix.Translate(e.DeltaManipulation.Translation.X,
                              e.DeltaManipulation.Translation.Y);
    
        // Apply the changes to the Rectangle.
        rectToMove.RenderTransform = new MatrixTransform(rectsMatrix);
    
        Rect containingRect =
            new Rect(((FrameworkElement)e.ManipulationContainer).RenderSize);
    
        Rect shapeBounds =
            rectToMove.RenderTransform.TransformBounds(
                new Rect(rectToMove.RenderSize));
    
        // Check if the rectangle is completely in the window.
        // If it is not and intertia is occuring, stop the manipulation.
        if (e.IsInertial && !containingRect.Contains(shapeBounds))
        {
            e.Complete();
        }
    
        e.Handled = true;
    }
    
    Private Sub Window_ManipulationDelta(ByVal sender As Object, ByVal e As ManipulationDeltaEventArgs)
    
        ' Get the Rectangle and its RenderTransform matrix.
        Dim rectToMove As Rectangle = e.OriginalSource
        Dim rectTransform As MatrixTransform = rectToMove.RenderTransform
        Dim rectsMatrix As Matrix = rectTransform.Matrix
    
    
        ' Rotate the shape
        rectsMatrix.RotateAt(e.DeltaManipulation.Rotation,
                             e.ManipulationOrigin.X,
                             e.ManipulationOrigin.Y)
    
        ' Resize the Rectangle. Keep it square 
        ' so use only the X value of Scale.
        rectsMatrix.ScaleAt(e.DeltaManipulation.Scale.X,
                            e.DeltaManipulation.Scale.X,
                            e.ManipulationOrigin.X,
                            e.ManipulationOrigin.Y)
    
        'move the center
        rectsMatrix.Translate(e.DeltaManipulation.Translation.X,
                              e.DeltaManipulation.Translation.Y)
    
        ' Apply the changes to the Rectangle.
        rectTransform = New MatrixTransform(rectsMatrix)
        rectToMove.RenderTransform = rectTransform
    
        Dim container As FrameworkElement = e.ManipulationContainer
        Dim containingRect As New Rect(container.RenderSize)
    
        Dim shapeBounds As Rect = rectTransform.TransformBounds(
                                    New Rect(rectToMove.RenderSize))
    
        ' Check if the rectangle is completely in the window.
        ' If it is not and intertia is occuring, stop the manipulation.
        If e.IsInertial AndAlso Not containingRect.Contains(shapeBounds) Then
            e.Complete()
        End If
    
        e.Handled = True
    End Sub
    
  6. Na classe MainWindow, adicione o seguinte manipulador de eventos ManipulationInertiaStarting.

    O evento ManipulationInertiaStarting ocorre quando o usuário levanta todos os dedos da tela. O código define a velocidade inicial e a desaceleração para o movimento, a expansão e a rotação do retângulo.

    void Window_InertiaStarting(object sender, ManipulationInertiaStartingEventArgs e)
    {
    
        // Decrease the velocity of the Rectangle's movement by
        // 10 inches per second every second.
        // (10 inches * 96 pixels per inch / 1000ms^2)
        e.TranslationBehavior.DesiredDeceleration = 10.0 * 96.0 / (1000.0 * 1000.0);
    
        // Decrease the velocity of the Rectangle's resizing by
        // 0.1 inches per second every second.
        // (0.1 inches * 96 pixels per inch / (1000ms^2)
        e.ExpansionBehavior.DesiredDeceleration = 0.1 * 96 / (1000.0 * 1000.0);
    
        // Decrease the velocity of the Rectangle's rotation rate by
        // 2 rotations per second every second.
        // (2 * 360 degrees / (1000ms^2)
        e.RotationBehavior.DesiredDeceleration = 720 / (1000.0 * 1000.0);
    
        e.Handled = true;
    }
    
    Private Sub Window_InertiaStarting(ByVal sender As Object,
                                       ByVal e As ManipulationInertiaStartingEventArgs)
    
        ' Decrease the velocity of the Rectangle's movement by 
        ' 10 inches per second every second.
        ' (10 inches * 96 pixels per inch / 1000ms^2)
        e.TranslationBehavior.DesiredDeceleration = 10.0 * 96.0 / (1000.0 * 1000.0)
    
        ' Decrease the velocity of the Rectangle's resizing by 
        ' 0.1 inches per second every second.
        ' (0.1 inches * 96 pixels per inch / (1000ms^2)
        e.ExpansionBehavior.DesiredDeceleration = 0.1 * 96 / (1000.0 * 1000.0)
    
        ' Decrease the velocity of the Rectangle's rotation rate by 
        ' 2 rotations per second every second.
        ' (2 * 360 degrees / (1000ms^2)
        e.RotationBehavior.DesiredDeceleration = 720 / (1000.0 * 1000.0)
    
        e.Handled = True
    End Sub
    
  7. Compile e execute o projeto.

    Você deve ver um quadrado vermelho aparecer na janela.

Testando o aplicativo

Para testar o aplicativo, experimente as manipulações a seguir. Observe que você pode fazer mais de um dos seguintes ao mesmo tempo.

  • Para mover o Rectangle, coloque um dedo na Rectangle e mova o dedo pela tela.

  • Para redimensionar a Rectangle, coloque dois dedos na Rectangle e mova os dedos para mais perto ou mais distantes um do outro.

  • Para girar a Rectangle, coloque dois dedos na Rectangle e gire os dedos em volta um do outro.

Para causar inércia, levante rapidamente os dedos da tela enquanto executa as manipulações anteriores. O Rectangle continuará a se mover, redimensionar ou girar por alguns segundos antes de parar.

Consulte também