Search code examples
c#parsingpointpolyline

Polyline only draws 2 lines & Point.Parse issue


Two quick questions, first why is my Polyline only connecting strings W, X, and Y.
Second is it possible to parse one string for multiple points, ie: store all of the numbers in string W and then Point.Parse(W) for all points.

private void Button_Click(object sender, RoutedEventArgs e)
{
    string W = "0,0";
    string X = "99,99";
    string Y = " 99, 300";
    string Z = "600, 300";
    Point[] points = { Point.Parse(W), Point.Parse(X), Point.Parse(Y), Point.Parse (Z)};
    DrawLine(points);
}

private void DrawLine(Point[] points)
{
    Polyline line = new Polyline();
    PointCollection collection = new PointCollection();
    foreach (Point p in points)
    {
        collection.Add(p);
    }
    line.Points = collection;
    line.Stroke = new SolidColorBrush(Colors.Black);
    line.StrokeThickness =3;
    myGrid.Children.Add(line);
}

Solution

  • A Polyline connects the vertices specified with its Points property, expressed in the form of a PointCollection.

    Your current collection of Points defines 4 vertices, which will generate 3 connected lines:

    1 line from Point(0, 0) to Point(99, 99)
    1 line from Point(99, 99) to Point(99, 300)
    1 line from Point(99, 300) to Point(600, 300)

    Something like this:

    \
     \
      \
       |
       |
       |____________
    

    If you don't see this kind of result, your Grid might not have enough space to contain all the drawing, which will then be truncated.

    The PointCollection.Parse() method allows you to specify a string containing a collection of Points separated by a comma or pairs of Point references separated by a space.
    These are both valid:

    string points = "0,0,99,99,99,300,600,300";
    
    string points = "0,0 99,99 99,300 600,300";
    

    You could then have a single string containing all Points references.
    Your code might be modified this way:

    using System.Windows.Media;
    using System.Windows.Shapes;
    
    string points = "0,0,99,99,99,300,600,300";
    PointCollection collection = PointCollection.Parse(points);
    DrawLine(collection);
    
    
    private void DrawLine(PointCollection points)
    {
        Polyline line = new Polyline();
        line.Points = points;
        line.Stroke = new SolidColorBrush(Colors.Black);
        line.StrokeThickness = 3;
        myGrid.Children.Add(line);
    }