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

时间:2017-04-25 09:30:34

标签: c# wpf path polygon

我想绘制一个简单的Path,其中使用RenderedGeometry Polygon作为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没有显示任何内容。

2 个答案:

答案 0 :(得分:2)

您应该强制在几何体之前渲染几何体Canvas。您可以通过调用Arrange的{​​{1}}和Measure方法来执行此操作:

Polygon

答案 1 :(得分:1)

您不应该使用Polygon元素来定义路径的几何。

而是直接创建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
};