简体   繁体   中英

Using RenderedGeometry as Data of Path does not work

I want to draw a simple Path which uses RenderedGeometry of a Polygon as 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);

However my Canvas does not display anything.

You should force the geometry to be rendered before you it to the Canvas . You can do this by calling the Arrange and Measure methods of the Polygon :

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

You shouldn't be using a Polygon element to define the Geometry of a Path.

Instead directly create a PathGeometry like this:

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

Or directly create a Geometry from a string using 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
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM