C# 绘制多条线

C# Draw multiple Lines

我正在使用这段代码绘制多条线,但我觉得有更好的方法。
例如。通过使用多维数组?或列表?

    private void drawLines()
    {
        int[] x1 = {   0,   0, 112, 222,   0, 333,   0,   1};
        int[] x2 = { 334, 334, 112, 222, 334, 333, 334,   1 };
        int[] y1 = { 100, 200, 300, 300,   1, 300, 300, 300 };
        int[] y2 = { 100, 200,   0,   0,   1,   0, 300,   0 };

        for (int i = 0; i < x1.Length; i++)
        {
            Line line = new Line();
            Grid myGrid = gg;
            line.Stroke = Brushes.Black;
            line.X1 = x1[i];
            line.X2 = x2[i];
            line.Y1 = y1[i];
            line.Y2 = y2[i];
            line.StrokeThickness = 2;
            myGrid.Children.Add(line);
        }

    }

我会制作一条线 class,在 struct Point 中包含该线的起点和终点,并制作该线的列表 class 而不是四个数组。

public class MyLine
{
     public Point StartPoint {get; set;}
     public Point EndPoint {get; set;}

     public void DrawLine()
     {
         //Draw line code goes here
     }
}

现在您有第 class 行,其中包含必填字段和绘制线条的方法。您可能在其他 class 中使用的 drawLines 方法将创建 MyLine class 列表,并可以使用 Line class 方法 DrawLine

绘制该行列表
private void DrawLines()
{
    List<MyLine> listMyLines = new  List<MyLine>();
    listMyLines.Add(new MyLine{StartPoint = new Point(0, 100), EndPoint = new Point(334, 100)});       

    for (int i = 0; i < listMyLines.Count; i++)
    {
         listMyLines[i].DrawLine();
    }
}

这可能会更好。

private void drawLInes()
{
    drawLines(
        new int[] { 0, 334, 100, 100 },
        new int[] { 0, 334, 200, 200 },
        new int[] { 112, 112, 300, 0 }
        // ...
        );
}

private void drawLines(params int[][] lines)
{
    for (int i = 0; i < lines.Length; i++)
    {
        Line line = new Line();
        Grid myGrid = gg;
        line.Stroke = Brushes.Black;
        line.X1 = lines[i][0];
        line.X2 = lines[i][1];
        line.Y1 = lines[i][2];
        line.Y2 = lines[i][3];
        line.StrokeThickness = 2;
        myGrid.Children.Add(line);
    }

}