如何:创建复合形状

更新:2007 年 11 月

此示例演示如何使用 Geometry 对象创建复合形状并使用 Path 元素显示这些复合形状。在下面的示例中,将 LineGeometryEllipseGeometryRectangleGeometryGeometryGroup 一起使用以创建复合形状。然后,使用 Path 元素绘制这些几何图形。

示例

<!-- Displays the geometry. --> 
<Path Stroke="Black" StrokeThickness="1" Fill="#CCCCFF">
  <Path.Data>

    <!-- Creates a composite shape from three geometries. -->
    <GeometryGroup FillRule="EvenOdd">
      <LineGeometry StartPoint="10,10" EndPoint="50,30" />
      <EllipseGeometry Center="40,70" RadiusX="30" RadiusY="30" />              
      <RectangleGeometry Rect="30,55 100 30" />
    </GeometryGroup>
  </Path.Data>
</Path>
// Create a Path to be drawn to the screen.
Path myPath = new Path();
myPath.Stroke = Brushes.Black;
myPath.StrokeThickness = 1;
SolidColorBrush mySolidColorBrush = new SolidColorBrush();
mySolidColorBrush.Color = Color.FromArgb(255, 204, 204, 255);
myPath.Fill = mySolidColorBrush;

// Create the line geometry to add to the Path
LineGeometry myLineGeometry = new LineGeometry();
myLineGeometry.StartPoint = new Point(10, 10);
myLineGeometry.EndPoint = new Point(50, 30);

// Create the ellipse geometry to add to the Path
EllipseGeometry myEllipseGeometry = new EllipseGeometry();
myEllipseGeometry.Center = new Point(40, 70);
myEllipseGeometry.RadiusX = 30;
myEllipseGeometry.RadiusY = 30;

// Create a rectangle geometry to add to the Path
RectangleGeometry myRectGeometry = new RectangleGeometry();
myRectGeometry.Rect = new Rect(30, 55, 100, 30);

// Add all the geometries to a GeometryGroup.
GeometryGroup myGeometryGroup = new GeometryGroup();
myGeometryGroup.Children.Add(myLineGeometry);
myGeometryGroup.Children.Add(myEllipseGeometry);
myGeometryGroup.Children.Add(myRectGeometry);

myPath.Data = myGeometryGroup;

// Add path shape to the UI.
StackPanel mainPanel = new StackPanel();
mainPanel.Children.Add(myPath);
this.Content = mainPanel;

下图显示在上一示例中创建的形状。

复合几何图形

使用 GeometryGroup 创建的复合几何图形

更复杂的形状(如多边形和含曲线线段的形状)可使用 PathGeometry 创建。有关演示如何使用 PathGeometry 创建形状的示例,请参见如何:使用 PathGeometry 创建形状。 尽管此示例使用 Path 元素向屏幕呈现形状,但 Geometry 对象也可用来描述 GeometryDrawingDrawingContext 的内容。此外,这些对象还可用于剪裁和命中测试。

此示例摘自一个更大的示例;有关完整的示例,请参见几何图形示例