绘制多条线

本文关键字:绘制 | 更新日期: 2023-09-27 17:53:25

我用这段代码画了多条线,但我觉得有更好的方法。
例如,通过使用多维数组?还是一个列表?

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

绘制多条线

我将创建一个Line类,在struct point中具有行起始点和行结束点,并创建该类的列表,而不是四个数组。

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

这样可能更好。

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