Partilhar via


Visão geral da geometria

Esta visão geral descreve como usar as classes WPF (Windows Presentation Foundation) Geometry para descrever formas. Este tópico também contrasta as diferenças entre Geometry objetos e Shape elementos.

O que é uma geometria?

A Geometry classe e as classes que derivam dela, como EllipseGeometry, PathGeometrye CombinedGeometry, permitem descrever a geometria de uma forma 2D. Essas descrições geométricas têm muitos usos, como definir uma forma para pintar na tela ou definir regiões de teste de colisão e recorte. Você pode até usar uma geometria para definir um caminho de animação.

Geometry Os objetos podem ser simples, como retângulos e círculos, ou compósitos, criados a partir de dois ou mais objetos de geometria. Geometrias mais complexas podem ser criadas usando as PathGeometry classes and StreamGeometry , que permitem descrever arcos e curvas.

Como um Geometry é um tipo de Freezable, os objetos Geometry fornecem várias funcionalidades especiais: podem ser declarados como recursos, partilhados entre múltiplos objetos, tornados apenas para leitura para melhorar o desempenho, clonados e tornados seguros para threads. Para obter mais informações sobre os diferentes recursos fornecidos por objetos Freezable, consulte a Freezable Objects Overview.

Geometrias vs. Formas

As Geometry classes e Shape parecem semelhantes na medida em que ambas descrevem formas 2D (comparar EllipseGeometry e Ellipse por exemplo), mas há diferenças importantes.

Por um lado, a Geometry classe herda da Freezable classe enquanto a Shape classe herda de FrameworkElement. Por serem elementos, Shape os objetos podem renderizar-se e participar do sistema de layout, enquanto Geometry os objetos não.

Embora Shape os objetos sejam mais facilmente utilizáveis do que Geometry os objetos, Geometry os objetos são mais versáteis. Enquanto um Shape objeto é usado para renderizar gráficos 2D, um Geometry objeto pode ser usado para definir a região geométrica para gráficos 2D, definir uma região para corte ou definir uma região para teste de interseções, por exemplo.

A forma do caminho

Uma Shape, a classe Path, na verdade usa um Geometry para descrever o seu conteúdo. Definindo a propriedade Data de Path com Geometry e definindo suas propriedades Fill e Stroke, pode renderizar um Geometry.

Propriedades comuns que aceitam uma geometria

As seções anteriores mencionaram que os objetos Geometry podem ser usados com outros objetos para uma variedade de propósitos, como desenhar formas, animar e recortar. A tabela a seguir lista várias classes que têm propriedades que usam um Geometry objeto.

Tipo Propriedade
DoubleAnimationUsingPath PathGeometry
DrawingGroup ClipGeometry
GeometryDrawing Geometry
Path Data
UIElement Clip

Tipos de geometria simples

A classe base para todas as geometrias é a classe Geometryabstrata. As classes que derivam da Geometry classe podem ser agrupadas aproximadamente em três categorias: geometrias simples, geometrias de caminho e geometrias compostas.

Classes de geometria simples incluem LineGeometry, RectangleGeometrye e EllipseGeometry são usadas para criar formas geométricas básicas, como linhas, retângulos e círculos.

  • A LineGeometry é definido especificando o ponto inicial da linha e o ponto final.

  • A RectangleGeometry é definido com uma Rect estrutura que especifica sua posição relativa e sua altura e largura. Você pode criar um retângulo arredondado definindo as RadiusX propriedades e RadiusY .

  • Um EllipseGeometry é definido por um ponto central, um raio x e um raio y. Os exemplos a seguir mostram como criar geometrias simples para renderização e recorte.

Essas mesmas formas, bem como formas mais complexas, podem ser criadas usando um PathGeometry ou combinando objetos de geometria juntos, mas essas classes fornecem um meio mais simples para produzir essas formas geométricas básicas.

O exemplo a seguir mostra como criar e renderizar um LineGeometry. Como observado anteriormente, um Geometry objeto é incapaz de desenhar a si mesmo, portanto, o exemplo usa uma Path forma para renderizar a linha. Como uma linha não tem área, definir a propriedade Fill do Path não teria efeito; em vez disso, apenas as propriedades Stroke e StrokeThickness são especificadas. A ilustração a seguir mostra a saída do exemplo.

LineGeometry
Uma Geometria de Linha desenhada de (10,20) a (100,130)

<Path Stroke="Black" StrokeThickness="1" >
  <Path.Data>
    <LineGeometry StartPoint="10,20" EndPoint="100,130" />
  </Path.Data>
</Path>
LineGeometry myLineGeometry = new LineGeometry();
myLineGeometry.StartPoint = new Point(10,20);
myLineGeometry.EndPoint = new Point(100,130);

Path myPath = new Path();
myPath.Stroke = Brushes.Black;
myPath.StrokeThickness = 1;
myPath.Data = myLineGeometry;
Dim myLineGeometry As New LineGeometry()
myLineGeometry.StartPoint = New Point(10,20)
myLineGeometry.EndPoint = New Point(100,130)

Dim myPath As New Path()
myPath.Stroke = Brushes.Black
myPath.StrokeThickness = 1
myPath.Data = myLineGeometry

O próximo exemplo mostra como criar e renderizar um EllipseGeometry. O exemplo define o Center do EllipseGeometry no ponto 50,50 e tanto o raio x quanto o raio y são definidos como 50, o que cria um círculo com um diâmetro de 100. O interior da elipse é pintado atribuindo um valor à propriedade Fill do elemento Path, neste caso Gold. A ilustração a seguir mostra a saída do exemplo.

Uma EllipseGeometry graphicsmm_ellipse
Uma geometria de elipse desenhada em (50,50)

<Path Fill="Gold" Stroke="Black" StrokeThickness="1">
  <Path.Data>
    <EllipseGeometry Center="50,50" RadiusX="50" RadiusY="50" />
  </Path.Data>
</Path>
EllipseGeometry myEllipseGeometry = new EllipseGeometry();
myEllipseGeometry.Center = new Point(50, 50);
myEllipseGeometry.RadiusX = 50;
myEllipseGeometry.RadiusY = 50;

Path myPath = new Path();
myPath.Fill = Brushes.Gold;
myPath.Stroke = Brushes.Black;
myPath.StrokeThickness = 1;
myPath.Data = myEllipseGeometry;
Dim myEllipseGeometry As New EllipseGeometry()
myEllipseGeometry.Center = New Point(50, 50)
myEllipseGeometry.RadiusX = 50
myEllipseGeometry.RadiusY = 50

Dim myPath As New Path()
myPath.Fill = Brushes.Gold
myPath.Stroke = Brushes.Black
myPath.StrokeThickness = 1
myPath.Data = myEllipseGeometry

O exemplo a seguir mostra como criar e renderizar um RectangleGeometry. A posição e as dimensões do retângulo são definidas por uma Rect estrutura. A posição é 50,50 e a altura e largura são ambas 25, o que cria um quadrado. A ilustração a seguir mostra a saída do exemplo.

Um retânguloGeometria
Geometria do retângulo desenhado em 50,50

<Path Fill="LemonChiffon" Stroke="Black" StrokeThickness="1">
  <Path.Data>
    <RectangleGeometry Rect="50,50,25,25" />
  </Path.Data>
</Path>
RectangleGeometry myRectangleGeometry = new RectangleGeometry();
myRectangleGeometry.Rect = new Rect(50,50,25,25);

Path myPath = new Path();
myPath.Fill = Brushes.LemonChiffon;
myPath.Stroke = Brushes.Black;
myPath.StrokeThickness = 1;
myPath.Data = myRectangleGeometry;
Dim myRectangleGeometry As New RectangleGeometry()
myRectangleGeometry.Rect = New Rect(50,50,25,25)

Dim myPath As New Path()
myPath.Fill = Brushes.LemonChiffon
myPath.Stroke = Brushes.Black
myPath.StrokeThickness = 1
myPath.Data = myRectangleGeometry

O exemplo a seguir mostra como usar um EllipseGeometry como a região do clipe para uma imagem. Um Image objeto é definido com um Width de 200 e um Height de 150. Um EllipseGeometry com um RadiusX valor de 100, um RadiusY valor de 75 e um Center valor de 100,75 é definido como a Clip propriedade da imagem. Apenas a parte da imagem que está dentro da área da elipse será exibida. A ilustração a seguir mostra a saída do exemplo.

Uma imagem com e sem recorte
Uma EllipseGeometry usada para recortar um controlador de imagem

<Image
  Source="sampleImages\Waterlilies.jpg"
  Width="200" Height="150" HorizontalAlignment="Left">
  <Image.Clip>
    <EllipseGeometry
      RadiusX="100"
      RadiusY="75"
      Center="100,75"/>
  </Image.Clip>
</Image>

// Create the image to clip.
Image myImage = new Image();
Uri imageUri =
    new Uri(@"C:\\Documents and Settings\\All Users\\Documents\My Pictures\\Sample Pictures\\Water lilies.jpg", UriKind.Relative);
myImage.Source = new BitmapImage(imageUri);
myImage.Width = 200;
myImage.Height = 150;
myImage.HorizontalAlignment = HorizontalAlignment.Left;

// Use an EllipseGeometry to define the clip region.
EllipseGeometry myEllipseGeometry = new EllipseGeometry();
myEllipseGeometry.Center = new Point(100, 75);
myEllipseGeometry.RadiusX = 100;
myEllipseGeometry.RadiusY = 75;
myImage.Clip = myEllipseGeometry;


' Create the image to clip.
Dim myImage As New Image()
Dim imageUri As New Uri("C:\\Documents and Settings\\All Users\\Documents\My Pictures\\Sample Pictures\\Water lilies.jpg", UriKind.Relative)
myImage.Source = New BitmapImage(imageUri)
myImage.Width = 200
myImage.Height = 150
myImage.HorizontalAlignment = HorizontalAlignment.Left

' Use an EllipseGeometry to define the clip region. 
Dim myEllipseGeometry As New EllipseGeometry()
myEllipseGeometry.Center = New Point(100, 75)
myEllipseGeometry.RadiusX = 100
myEllipseGeometry.RadiusY = 75
myImage.Clip = myEllipseGeometry

Geometrias de Trajetória

A PathGeometry classe e seu equivalente leve, a StreamGeometry classe, fornecem os meios para descrever várias figuras complexas compostas por arcos, curvas e linhas.

No coração de um PathGeometry está uma coleção de PathFigure objetos, assim chamada porque cada figura descreve uma forma discreta no PathGeometry. Cada PathFigure é composto por um ou mais PathSegment objetos, cada um dos quais descreve um segmento da figura.

Existem muitos tipos de segmentos.

Tipo de segmento Descrição Exemplo
ArcSegment Cria um arco elíptico entre dois pontos. Crie um arco elíptico.
BezierSegment Cria uma curva cúbica de Bezier entre dois pontos. Crie uma curva cúbica de Bezier.
LineSegment Cria uma linha entre dois pontos. Criar um LineSegment em um PathGeometry
PolyBezierSegment Cria uma série de curvas cúbicas de Bezier. Consulte a página do tipo PolyBezierSegment.
PolyLineSegment Cria uma série de linhas. Consulte a página do tipo PolyLineSegment.
PolyQuadraticBezierSegment Cria uma série de curvas quadráticas de Bezier. Veja a página PolyQuadraticBezierSegment.
QuadraticBezierSegment Cria uma curva de Bezier quadrática. Crie uma curva quadrática de Bezier.

Os segmentos dentro de um PathFigure são combinados em uma única forma geométrica, com o ponto final de cada segmento sendo o ponto inicial do próximo segmento. A propriedade StartPoint de um PathFigure especifica o ponto a partir do qual o primeiro segmento é desenhado. Cada segmento subsequente começa no ponto final do segmento anterior. Por exemplo, uma linha vertical de 10,50 a 10,150 pode ser definida definindo a propriedade StartPoint como 10,50 e criando um LineSegment com uma configuração de propriedade Point de 10,150.

O exemplo a seguir cria um simples PathGeometry composto por um único PathFigure com um LineSegment e o exibe usando um Path elemento . O PathFigure objeto StartPoint é configurado para 10,20 e a LineSegment é definida com um ponto final de 100,130. A ilustração a seguir mostra o PathGeometry criado por este exemplo.

LineGeometry
Um PathGeometry que contém um único LineSegment

<Path Stroke="Black" StrokeThickness="1">
  <Path.Data>
    <PathGeometry>
      <PathGeometry.Figures>
        <PathFigure StartPoint="10,20">
          <PathFigure.Segments>
            <LineSegment Point="100,130"/>
          </PathFigure.Segments>
        </PathFigure>
      </PathGeometry.Figures>
    </PathGeometry>
  </Path.Data>
</Path>

// Create a figure that describes a
// line from (10,20) to (100,130).
PathFigure myPathFigure = new PathFigure();
myPathFigure.StartPoint = new Point(10,20);
myPathFigure.Segments.Add(
    new LineSegment(new Point(100,130),
    true /* IsStroked */ ));

/// Create a PathGeometry to contain the figure.
PathGeometry myPathGeometry = new PathGeometry();
myPathGeometry.Figures.Add(myPathFigure);

// Display the PathGeometry.
Path myPath = new Path();
myPath.Stroke = Brushes.Black;
myPath.StrokeThickness = 1;
myPath.Data = myPathGeometry;

' Create a figure that describes a 
' line from (10,20) to (100,130).
Dim myPathFigure As New PathFigure()
myPathFigure.StartPoint = New Point(10,20)
myPathFigure.Segments.Add(New LineSegment(New Point(100,130), True)) ' IsStroked 

''' Create a PathGeometry to contain the figure.
Dim myPathGeometry As New PathGeometry()
myPathGeometry.Figures.Add(myPathFigure)

' Display the PathGeometry. 
Dim myPath As New Path()
myPath.Stroke = Brushes.Black
myPath.StrokeThickness = 1
myPath.Data = myPathGeometry

Vale a pena contrastar este exemplo com o anterior LineGeometry . A sintaxe usada para um PathGeometry é muito mais detalhada do que a usada para um simples LineGeometry, e pode fazer mais sentido usar a LineGeometry classe neste caso, mas a sintaxe detalhada do PathGeometry permite regiões geométricas extremamente complexas e complexas.

Geometrias mais complexas podem ser criadas usando uma combinação de PathSegment objetos.

O próximo exemplo usa a BezierSegment, a LineSegmente an ArcSegment para criar forma. O exemplo primeiro cria uma curva cúbica de Bezier é definindo quatro pontos: um ponto inicial, que é o ponto final do segmento anterior, um ponto final (Point3), e dois pontos de controle (Point1 e Point2). Os dois pontos de controle de uma curva cúbica de Bezier se comportam como ímãs, atraindo porções do que de outra forma seria uma linha reta em direção a si mesmos, produzindo uma curva. O primeiro ponto de controle, Point1, afeta a porção inicial da curva, o segundo ponto de controle, Point2afeta a porção final da curva.

O exemplo então adiciona um LineSegment, que é desenhado entre o ponto final do BezierSegment precedente até o ponto especificado pela sua propriedade LineSegment.

O exemplo então adiciona um ArcSegment, que é desenhado do ponto final do precedente LineSegment para o ponto especificado por sua Point propriedade. O exemplo também especifica os raios x e y do arco (Size), um ângulo de rotação (RotationAngle), um sinalizador indicando quão grande deve ser o ângulo do arco resultante (IsLargeArc), e um valor indicando em que direção o arco é desenhado (SweepDirection). A ilustração a seguir mostra a forma criada por este exemplo.

Uma PathGeometry com um arco.
PathGeometry

<Path Stroke="Black" StrokeThickness="1" >
  <Path.Data>
    <PathGeometry>
      <PathGeometry.Figures>
        <PathFigure StartPoint="10,50">
          <PathFigure.Segments>
            <BezierSegment
              Point1="100,0"
              Point2="200,200"
              Point3="300,100"/>
            <LineSegment Point="400,100" />
            <ArcSegment
              Size="50,50" RotationAngle="45"
              IsLargeArc="True" SweepDirection="Clockwise"
              Point="200,100"/>
          </PathFigure.Segments>
        </PathFigure>
      </PathGeometry.Figures>
    </PathGeometry>
  </Path.Data>
</Path>

// Create a figure.
PathFigure myPathFigure = new PathFigure();
myPathFigure.StartPoint = new Point(10,50);
myPathFigure.Segments.Add(
    new BezierSegment(
        new Point(100,0),
        new Point(200,200),
        new Point(300,100),
        true /* IsStroked */  ));
myPathFigure.Segments.Add(
    new LineSegment(
        new Point(400,100),
        true /* IsStroked */ ));
myPathFigure.Segments.Add(
    new ArcSegment(
        new Point(200,100),
        new Size(50,50),
        45,
        true, /* IsLargeArc */
        SweepDirection.Clockwise,
        true /* IsStroked */ ));

/// Create a PathGeometry to contain the figure.
PathGeometry myPathGeometry = new PathGeometry();
myPathGeometry.Figures.Add(myPathFigure);

// Display the PathGeometry.
Path myPath = new Path();
myPath.Stroke = Brushes.Black;
myPath.StrokeThickness = 1;
myPath.Data = myPathGeometry;

' Create a figure.
Dim myPathFigure As New PathFigure()
myPathFigure.StartPoint = New Point(10,50)
myPathFigure.Segments.Add(New BezierSegment(New Point(100,0), New Point(200,200), New Point(300,100), True)) ' IsStroked 
myPathFigure.Segments.Add(New LineSegment(New Point(400,100), True)) ' IsStroked 
myPathFigure.Segments.Add(New ArcSegment(New Point(200,100), New Size(50,50), 45, True, SweepDirection.Clockwise, True)) ' IsStroked  -  IsLargeArc 

''' Create a PathGeometry to contain the figure.
Dim myPathGeometry As New PathGeometry()
myPathGeometry.Figures.Add(myPathFigure)

' Display the PathGeometry. 
Dim myPath As New Path()
myPath.Stroke = Brushes.Black
myPath.StrokeThickness = 1
myPath.Data = myPathGeometry

Geometrias ainda mais complexas podem ser criadas usando múltiplos objetos PathFigure dentro de um PathGeometry.

O exemplo a seguir cria um PathGeometry com dois objetos PathFigure, cada um dos quais contém vários objetos PathSegment. O PathFigure do exemplo acima e um PathFigure com PolyLineSegment e QuadraticBezierSegment são utilizados. A PolyLineSegment é definido com uma matriz de pontos e o QuadraticBezierSegment é definido com um ponto de controle e um ponto final. A ilustração a seguir mostra a forma criada por este exemplo.

Um PathGeometry com um arco que inclui dois objetos PathFigure.
Um PathGeometry com várias figuras

<Path Stroke="Black" StrokeThickness="1" >
  <Path.Data>
    <PathGeometry>
      <PathGeometry.Figures>
        <PathFigure StartPoint="10,50">
          <PathFigure.Segments>
            <BezierSegment
              Point1="100,0"
              Point2="200,200"
              Point3="300,100"/>
            <LineSegment Point="400,100" />
            <ArcSegment
              Size="50,50" RotationAngle="45"
              IsLargeArc="True" SweepDirection="Clockwise"
              Point="200,100"/>
          </PathFigure.Segments>
        </PathFigure>
        
        <PathFigure StartPoint="10,100">
          <PathFigure.Segments>
            <PolyLineSegment Points="50,100 50,150" />
            <QuadraticBezierSegment Point1="200,200" Point2="300,100"/>
          </PathFigure.Segments>
        </PathFigure>                
      </PathGeometry.Figures>
    </PathGeometry>
  </Path.Data>
</Path>

PathGeometry myPathGeometry = new PathGeometry();

// Create a figure.
PathFigure pathFigure1 = new PathFigure();
pathFigure1.StartPoint = new Point(10,50);
pathFigure1.Segments.Add(
    new BezierSegment(
        new Point(100,0),
        new Point(200,200),
        new Point(300,100),
        true /* IsStroked */ ));
pathFigure1.Segments.Add(
    new LineSegment(
        new Point(400,100),
        true /* IsStroked */ ));
pathFigure1.Segments.Add(
    new ArcSegment(
        new Point(200,100),
        new Size(50,50),
        45,
        true, /* IsLargeArc */
        SweepDirection.Clockwise,
        true /* IsStroked */ ));
myPathGeometry.Figures.Add(pathFigure1);

// Create another figure.
PathFigure pathFigure2 = new PathFigure();
pathFigure2.StartPoint = new Point(10,100);
Point[] polyLinePointArray =
    new Point[]{ new Point(50, 100), new Point(50, 150)};
PolyLineSegment myPolyLineSegment = new PolyLineSegment();
myPolyLineSegment.Points =
    new PointCollection(polyLinePointArray);
pathFigure2.Segments.Add(myPolyLineSegment);
pathFigure2.Segments.Add(
    new QuadraticBezierSegment(
        new Point(200,200),
        new Point(300,100),
        true /* IsStroked */ ));
myPathGeometry.Figures.Add(pathFigure2);

// Display the PathGeometry.
Path myPath = new Path();
myPath.Stroke = Brushes.Black;
myPath.StrokeThickness = 1;
myPath.Data = myPathGeometry;

Dim myPathGeometry As New PathGeometry()

' Create a figure.
Dim pathFigure1 As New PathFigure()
pathFigure1.StartPoint = New Point(10,50)
pathFigure1.Segments.Add(New BezierSegment(New Point(100,0), New Point(200,200), New Point(300,100), True)) ' IsStroked 
pathFigure1.Segments.Add(New LineSegment(New Point(400,100), True)) ' IsStroked 
pathFigure1.Segments.Add(New ArcSegment(New Point(200,100), New Size(50,50), 45, True, SweepDirection.Clockwise, True)) ' IsStroked  -  IsLargeArc 
myPathGeometry.Figures.Add(pathFigure1)

' Create another figure.
Dim pathFigure2 As New PathFigure()
pathFigure2.StartPoint = New Point(10,100)
Dim polyLinePointArray() As Point = { New Point(50, 100), New Point(50, 150)}
Dim myPolyLineSegment As New PolyLineSegment()
myPolyLineSegment.Points = New PointCollection(polyLinePointArray)
pathFigure2.Segments.Add(myPolyLineSegment)
pathFigure2.Segments.Add(New QuadraticBezierSegment(New Point(200,200), New Point(300,100), True)) ' IsStroked 
myPathGeometry.Figures.Add(pathFigure2)

' Display the PathGeometry. 
Dim myPath As New Path()
myPath.Stroke = Brushes.Black
myPath.StrokeThickness = 1
myPath.Data = myPathGeometry

StreamGeometry

Tal como a classe PathGeometry, a StreamGeometry define uma forma geométrica complexa que pode conter curvas, arcos e linhas. Ao contrário de um PathGeometry, o conteúdo de um StreamGeometry não suporta vinculação de dados, animação ou modificação. Use um StreamGeometry quando precisar descrever uma geometria complexa, mas não quiser a sobrecarga de suporte à vinculação de dados, animação ou modificação. Devido à sua eficiência, a classe StreamGeometry é uma boa escolha para descrever adornos.

Para obter um exemplo, consulte Criar uma forma usando um StreamGeometry.

Sintaxe de marcação de caminho

Os tipos PathGeometry e StreamGeometry suportam uma sintaxe de atributo XAML (Linguagem de Marcação de Aplicações Extensível) utilizando uma série especial de comandos de mover e desenhar. Para obter mais informações, consulte Sintaxe de marcação de caminho.

Geometrias Compósitas

Os objetos de geometria composta podem ser criados usando um GeometryGroup, a CombinedGeometry, ou chamando o método Geometry estático Combine.

  • O CombinedGeometry objeto e o Combine método executam uma operação booleana para combinar a área definida por duas geometrias. Geometry objetos que não têm área são descartados. Apenas dois Geometry objetos podem ser combinados (embora estas duas geometrias também possam ser geometrias compostas).

  • A GeometryGroup classe cria uma fusão dos Geometry objetos que contém sem combinar sua área. Qualquer número de Geometry objetos pode ser adicionado a um GeometryGroup. Para obter um exemplo, consulte Criar uma forma composta.

Como eles não executam uma operação de combinação, o uso de GeometryGroup objetos fornece benefícios de desempenho em relação ao uso de CombinedGeometry objetos ou do Combine método.

Geometrias combinadas

A seção anterior mencionou o CombinedGeometry objeto e o Combine método combinam a área definida pelas geometrias que eles contêm. A GeometryCombineMode enumeração especifica como as geometrias são combinadas. Os valores possíveis para a GeometryCombineMode propriedade são: Union, Intersect, Exclude, e Xor.

No exemplo a seguir, o CombinedGeometry é definido com um modo de combinação de união. Tanto o Geometry1 como o Geometry2 são definidos como círculos do mesmo raio, mas com centros deslocados por 50.

<Path Stroke="Black" StrokeThickness="1" Fill="#CCCCFF">
  <Path.Data>
    
    <!-- Combines two geometries using the union combine mode. -->
    <CombinedGeometry GeometryCombineMode="Union">
      <CombinedGeometry.Geometry1>
        <EllipseGeometry RadiusX="50" RadiusY="50" Center="75,75" />
      </CombinedGeometry.Geometry1>
      <CombinedGeometry.Geometry2>
        <EllipseGeometry RadiusX="50" RadiusY="50" Center="125,75" />
      </CombinedGeometry.Geometry2>
    </CombinedGeometry>
  </Path.Data>
</Path>

Resultados do modo de combinação da União

No exemplo a seguir, a CombinedGeometry é definida com um modo de combinação de Xor. Tanto o Geometry1 como o Geometry2 são definidos como círculos do mesmo raio, mas com centros deslocados por 50.

<Path Stroke="Black" StrokeThickness="1" Fill="#CCCCFF">
  <Path.Data>
    
    <!-- Combines two geometries using the XOR combine mode. -->
    <CombinedGeometry GeometryCombineMode="Xor">
      <CombinedGeometry.Geometry1>
        <EllipseGeometry RadiusX="50" RadiusY="50" Center="75,75" />
      </CombinedGeometry.Geometry1>
      <CombinedGeometry.Geometry2>
        <EllipseGeometry RadiusX="50" RadiusY="50" Center="125,75" />
      </CombinedGeometry.Geometry2>
    </CombinedGeometry>
  </Path.Data>
</Path>

Resultados do modo de combinação Xor

Para obter exemplos adicionais, consulte Criar uma forma composta e Criar uma geometria combinada.

Funcionalidades Congeláveis

Como herda da classe Freezable, a Geometry class fornece vários recursos especiais: os objetos Geometry podem ser declarados como Recursos XAML, compartilhados entre vários objetos, tornados apenas para leitura para melhorar o desempenho, clonados e protegidos para threads. Para obter mais informações sobre os diferentes recursos fornecidos por objetos Freezable, consulte a Freezable Objects Overview.

Outras características de geometria

A Geometry classe também fornece métodos utilitários úteis, como os seguintes:

Consulte a Geometry classe para obter uma lista completa de seus métodos.

Ver também