Polyline 只绘制 2 条线 & Point.Parse 问题

Polyline only draws 2 lines & Point.Parse issue

两个简单的问题,首先为什么我的 Polyline 只连接字符串 W、X 和 Y。
其次,是否可以为多个点解析一个字符串,即:将所有数字存储在字符串 W 中,然后 Point.Parse(W) 用于所有点。

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

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

您当前的 Points 集合定义了 4 个顶点,这将生成 3 条连接线:

1 行从 Point(0, 0)Point(99, 99)
1 行从 Point(99, 99)Point(99, 300)
Point(99, 300)Point(600, 300)

的 1 行

像这样:

\
 \
  \
   |
   |
   |____________

如果您没有看到这种结果,您的 Grid 可能没有足够的 space 来包含所有绘图,然后将被截断。

PointCollection.Parse() 方法允许您指定一个字符串,其中包含以逗号分隔的点集合或以 space.
分隔的成对 Point 引用 这些都是有效的:

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

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

然后您可以拥有一个包含所有 Points 个引用的字符串。
您的代码可能会这样修改:

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