C#绘制多条线

时间:2015-06-05 06:52:00

标签: c# line draw

我使用此代码绘制了多行,但我觉得有更好的方法可以做到这一点。
例如。通过使用多维数组?还是清单?

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

    }

2 个答案:

答案 0 :(得分:6)

我会在struct Point中创建一个具有该行的起点和终点的Line类,并创建该类的列表,而不是有四个数组。

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

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

现在你有了带有必填字段和方法的线类来绘制线条。您可能在其他类中的drawLines方法将创建MyLine类的列表,并可以使用Line类方法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();
    }
}

答案 1 :(得分:1)

这可能会更好。

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

}