Using RenderedGeometry as path data doesn't work

I want to draw a simple Path

one that uses RenderedGeometry

for Polygon

both 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 mine Canvas

doesn't display anything.

+3


source to share


2 answers


You must make the geometry render before going to Canvas

. You can do this by calling methods Arrange

and Measure

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

      

+2


source


You cannot use the Polygon element to define the geometry of the path.

Instead, create 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 geometry from 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
};

      

+1


source







All Articles