使用渲染几何图形作为路径数据不起作用



我想画一个简单的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之前将其渲染。您可以通过调用PolygonArrangeMeasure方法来执行此操作:

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
};

或者使用路径标记语法直接从字符串创建几何图形:

var path = new Path
{
Data = Geometry.Parse("M0,0 L0,100 150,150Z"),
Stroke = Brushes.LightBlue,
StrokeThickness = 2,
Fill = Brushes.Green,
Opacity = 0.5
};

相关内容

  • 没有找到相关文章

最新更新