Compartilhar via


Visão Geral sobre Transformações

Este tópico descreve como usar o 2-D Transform classes para girar, redimensionar, mover (traduzir) e inclinar FrameworkElement objetos.

Este tópico contém as seguintes seções.

  • What Is a Transform?
  • Transform Classes
  • Common Transformation Properties
  • Transformations and Coordinate Systems
  • Transforming a FrameworkElement
  • Exemplo: Girar um graus de FrameworkElement 45
  • Animating Transformations
  • Freezable Features
  • Tópicos relacionados

What Is a Transform?

A Transform defines how to map, or transform, points from one coordinate space to another coordinate space. This mapping is described by a transformation Matrix, which is a collection of three rows with three columns of Double values.

Observação

Windows Presentation Foundation (WPF)usa as matrizes de linha principal.Vectors are expressed as row-vectors, not column vectors.

The following table shows the structure of a WPF matrix.

A 2-D transformation matrix

M11

Padrão: 1.0

M12

Padrão: 0.0

0.0

M21

Padrão: 0.0

M22

Padrão: 1.0

0.0

OffsetX

Padrão: 0.0

OffsetY

Padrão: 0.0

1.0

By manipulating matrix values, you can rotate, scale, skew, and move (translate) an object. For example, if you change the value in the first column of the third row (the OffsetX value) to 100, you can use it to move an object 100 units along the x-axis. If you change the value in the second column of the second row to 3, you can use it to stretch an object to three times its current height. Se você alterar os dois valores, você move as 100 unidades do objeto ao longo do eixo x e alongar a altura por um fator de 3. Porque Windows Presentation Foundation (WPF) somente suporta transformações de afim, os valores na coluna à direita são sempre 0, 0, 1.

Although Windows Presentation Foundation (WPF) enables you to directly manipulate matrix values, it also provides several Transform classes that enable you to transform an object without knowing how the underlying matrix structure is configured. For example, the ScaleTransform class enables you to scale an object by setting its ScaleX and ScaleY properties, instead of manipulating a transformation matrix. Likewise, the RotateTransform class enables you to rotate an object by just setting its Angle property.

Transform Classes

Windows Presentation Foundation (WPF) provides the following 2-D Transform classes for common transformation operations:

Class

Description

Example

Illustration

RotateTransform

Rotates an element by the specified Angle.

Como: Rotate an Object

Ilustração de giro

ScaleTransform

Scales an element by the specified ScaleX and ScaleY amounts.

Como: Scale an Element

Ilustração de dimensionamento

SkewTransform

Skews an element by the specified AngleX and AngleY amounts.

Como: Inclinar um elemento

Ilustração de inclinação

TranslateTransform

Moves (translates) an element by the specified X and Y amounts.

Como: Transladar um elemento

Ilustração de mudança de posição

For creating more complex transformations, Windows Presentation Foundation (WPF) provides the following two classes:

Class

Description

Example

TransformGroup

Groups multiple TransformGroup objects into a single Transform that you can then apply to transform properties.

Como: Aplicar várias transformações a um objeto

MatrixTransform

Creates custom transformations that are not provided by the other Transform classes. When you use a MatrixTransform, you manipulate a Matrix directly.

Como: Usar uma MatrixTransform para Criar Transformações Personalizadas

Windows Presentation Foundation (WPF) also provides 3-D transformations. Para obter mais informações, consulte o Transform3D classe.

Common Transformation Properties

One way to transform an object is to declare the appropriate Transform type and apply it to the transformation property of the object. Different types of objects have different types of transformation properties. The following table lists several commonly used Windows Presentation Foundation (WPF) types and their transformation properties.

Type

Transformation properties

Brush

Transform, RelativeTransform

ContainerVisual

Transform

DrawingGroup

Transform

FrameworkElement

RenderTransform, LayoutTransform

Geometry

Transform

TextEffect

Transform

UIElement

RenderTransform

Transformations and Coordinate Systems

When you transform an object, you do not just transform the object, you transform coordinate space in which that object exists. Por padrão, uma transformação é centralizada na origem do sistema de coordenadas do objeto de destino: (0,0). The only exception is TranslateTransform; a TranslateTransform has no center properties to set because the translation effect is the same regardless of where it is centered.

O exemplo a seguir utiliza um RotateTransform para girar uma Rectangle elemento, um tipo de FrameworkElement, 45 graus sobre seu centro de padrão (0, 0). The following illustration shows the effect of the rotation.

A Rectangle element rotated 45 degrees about the point (0,0)

Um FrameworkElement girado 45 graus ao redor do ponto (0,0)

<Canvas Width="200" Height="200">
  <Rectangle 
    Canvas.Left="100" Canvas.Top="100"
    Width="50" Height="50" 
    Fill="RoyalBlue" Opacity="1.0">
    <Rectangle.RenderTransform>
      <RotateTransform Angle="45" />
    </Rectangle.RenderTransform>
  </Rectangle>
</Canvas>

By default, the element rotates about its upper-left corner, (0, 0). The RotateTransform, ScaleTransform, and SkewTransform classes provide CenterX and CenterY properties that enable you to specify the point at which the transform is applied.

O próximo exemplo também utiliza um RotateTransform para girar uma Rectangle elemento 45 graus; No entanto, desta vez o CenterX e CenterY propriedades são definidas para que o RotateTransform tem um centro de (25, 25). The following illustration shows the effect of the rotation.

A Rectangle element rotated 45 degrees about the point (25, 25)

Um Geometry girado 45 graus ao redor do ponto (25, 25)

<Canvas Width="200" Height="200">
  <Rectangle 
    Canvas.Left="100" Canvas.Top="100"
    Width="50" Height="50" 
    Fill="RoyalBlue" Opacity="1.0">
    <Rectangle.RenderTransform>
      <RotateTransform Angle="45" CenterX="25" CenterY="25" />
    </Rectangle.RenderTransform>
  </Rectangle>
</Canvas>

Transforming a FrameworkElement

To apply transformations to a FrameworkElement, create a Transform and apply it to one of the two properties that the FrameworkElement class provides:

  • LayoutTransform – A transform that is applied before the layout pass. After the transform is applied, the layout system processes the transformed size and position of the element.

  • RenderTransform – A transform that modifies the appearance of the element but is applied after the layout pass is complete. By using the RenderTransform property instead of the LayoutTransform property, you can obtain performance benefits.

Which property should you use? Because of the performance benefits that it provides, use the RenderTransform property whenever possible, especially when you use animated Transform objects. Use the LayoutTransform property when scaling, rotating, or skewing and you need the parent of the element to adjust to the transformed size of the element. Note that, when they are used with the LayoutTransform property, TranslateTransform objects appear to have no effect on elements. That is because the layout system returns the translated element to its original position as part of its processing.

For additional information about layout in Windows Presentation Foundation (WPF), see Sistema de layout overview.

Exemplo: Girar um graus de FrameworkElement 45

The following example uses a RotateTransform to rotate a button clockwise by 45 degrees. The button is contained in a StackPanel that has two other buttons.

Por padrão, um RotateTransform gira sobre o ponto (0, 0). Because the example does not specify a center value, the button rotates about the point (0, 0), which is its upper-left corner. The RotateTransform is applied to the RenderTransform property. The following illustration shows the result of the transformation.

Clockwise rotation 45 degrees from upper-left corner

Um botão transformado com RenderTransform

<Border Margin="30" 
  HorizontalAlignment="Left" VerticalAlignment="Top"
  BorderBrush="Black" BorderThickness="1" >
  <StackPanel Orientation="Vertical">
    <Button Content="A Button" Opacity="1" />
    <Button Content="Rotated Button">
      <Button.RenderTransform>
        <RotateTransform Angle="45" />
      </Button.RenderTransform>
    </Button>
    <Button Content="A Button" Opacity="1" />
  </StackPanel>
</Border>

O próximo exemplo também utiliza um RotateTransform Girar um botão de 45 graus no sentido horário, mas ele também define o RenderTransformOrigin do botão (0,5, 0,5). The value of the RenderTransformOrigin property is relative to the size of the button. As a result, the rotation is applied to the center of the button, instead of its upper-left corner. The following illustration shows the result of the transformation.

Clockwise rotation 45 degrees around center

Um botão invertido transformado ao redor de seu centro

<Border Margin="30"   
  HorizontalAlignment="Left" VerticalAlignment="Top"
  BorderBrush="Black" BorderThickness="1">
  <StackPanel Orientation="Vertical">
    <Button Content="A Button" Opacity="1" />
    <Button Content="Rotated Button"
      RenderTransformOrigin="0.5,0.5">
      <Button.RenderTransform>
        <RotateTransform Angle="45" />
      </Button.RenderTransform>
    </Button>
    <Button Content="A Button" Opacity="1" />
  </StackPanel>
</Border>

The following example uses the LayoutTransform property instead of the RenderTransform property to rotate the button. This causes the transformation to affect the layout of the button, which triggers a full pass by the layout system. As a result, the button is rotated and then repositioned because its size has changed. The following illustration shows the result of the transformation.

LayoutTransform used to rotate the button

Um botão transformado com LayoutTransform

<Border Margin="30"   
 HorizontalAlignment="Left" VerticalAlignment="Top"
 BorderBrush="Black" BorderThickness="1">
  <StackPanel Orientation="Vertical">

    <Button Content="A Button" Opacity="1" />   
    <Button Content="Rotated Button">
      <Button.LayoutTransform>
        <RotateTransform Angle="45"  />
      </Button.LayoutTransform>
    </Button>   
    <Button Content="A Button" Opacity="1" />
  </StackPanel>
</Border>

Animating Transformations

Because they inherit from the Animatable class, the Transform classes can be animated. To animate a Transform, apply an animation of a compatible type to the property you want to animate.

The following example uses a Storyboard and a DoubleAnimation with a RotateTransform to make a Button spin in place when it is clicked.

<Page 
  xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml"
  Title="Button Animated RotateTransform Example"
  Background="White" Margin="50">
  <StackPanel>



    <Button Content="A Button"
      RenderTransformOrigin="0.5,0.5">
      <Button.RenderTransform>
        <RotateTransform x:Name="AnimatedRotateTransform" Angle="0" />
      </Button.RenderTransform>
      <Button.Triggers>
        <EventTrigger RoutedEvent="Button.Click">
          <BeginStoryboard>
            <Storyboard>
              <DoubleAnimation 
                Storyboard.TargetName="AnimatedRotateTransform"
                Storyboard.TargetProperty="Angle" 
                To="360" Duration="0:0:1" FillBehavior="Stop" />
            </Storyboard>
          </BeginStoryboard>
        </EventTrigger>
      </Button.Triggers>
    </Button>

  </StackPanel>
</Page>

Para obter o exemplo completo, consulte exemplos de transformações 2D. For more information about animations, see the Revisão de Animação.

Freezable Features

Porque ele herda o Freezable classe, o Transform classe fornecem vários recursos especiais: Transformobjetos podem ser declarados como recursos, compartilhadas entre vários objetos, feitas somente leitura para melhorar o desempenho, clonado e feitas thread-safe. For more information about the different features that are provided by Freezable objects, see the Visão geral sobre objetos Freezable.

Consulte também

Referência

Transform

Matrix

Outros recursos

Transformations How-to Topics

Exemplos de transformações 2D