我想画一个简单的Path
,它使用Polygon
的RenderedGeometry
作为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
的Arrange
和Measure
方法来执行此操作:
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
};