使用 RenderedGeometry 作为路径数据不起作用

Using RenderedGeometry as Data of Path does not work

我想画一个简单的 Path,它使用 PolygonRenderedGeometry 作为 Data

Polygon polygon = new Polygon();
polygon.Points = new PointCollection { new Point(0, 0), new Point(0, 100), new Point(150, 150) };
var path = new Path
{ 
    Data = polygon.RenderedGeometry,
    Stroke = Brushes.LightBlue,
    StrokeThickness = 2,
    Fill = Brushes.Green,
    Opacity = 0.5
}; 
Panel.SetZIndex(path, 2);
canvas.Children.Add(path);

但是我的 Canvas 没有显示任何内容。

您应该在将几何体渲染到 Canvas 之前强制渲染它。您可以通过调用 Polygon:

ArrangeMeasure 方法来完成此操作
Polygon polygon = new Polygon();
polygon.Points = new PointCollection { new Point(0, 0), new Point(0, 100), new Point(150, 150) };
polygon.Arrange(new Rect(canvas.RenderSize));
polygon.Measure(canvas.RenderSize);
var path = new Path
{
    Data = polygon.RenderedGeometry,
    Stroke = Brushes.LightBlue,
    StrokeThickness = 2,
    Fill = Brushes.Green,
    Opacity = 0.5
};
Panel.SetZIndex(path, 2);
canvas.Children.Add(path);

您不应该使用多边形元素来定义路径的几何形状。

而是像这样直接创建一个 PathGeometry

var figure = new PathFigure
{
    StartPoint = new Point(0, 0),
    IsClosed = true
};

figure.Segments.Add(new PolyLineSegment
{
    Points = new PointCollection { new Point(0, 100), new Point(150, 150) },
    IsStroked = true
});

var geometry = new PathGeometry();
geometry.Figures.Add(figure);

var path = new Path
{
    Data = geometry,
    Stroke = Brushes.LightBlue,
    StrokeThickness = 2,
    Fill = Brushes.Green,
    Opacity = 0.5
};

或使用 Path Markup Syntax:

直接从字符串创建几何图形
var path = new Path
{
    Data = Geometry.Parse("M0,0 L0,100 150,150Z"),
    Stroke = Brushes.LightBlue,
    StrokeThickness = 2,
    Fill = Brushes.Green,
    Opacity = 0.5
};