在C# WPF中绘制多点连线

6

我是一名初学者,正在学习C# WPF技术。

我想使用点数组在WPF C#中创建一条线。

例如:

Point[] points = 
{
  new Point(3,  5),              
  new Point(1 , 40),
  new Point(12, 30),
  new Point(20, 2 )
};

Line myLine = new Line( points );

我该怎么做?

也许这个链接会有帮助:https://dev59.com/e3I-5IYBdhLWcg3wEEBV - kenny
1个回答

9

如果您想用Line来绘制它,请编写一个方法,或者您可以使用Polyline

     public MainWindow()
    {
        InitializeComponent();
        canvas.Children.Clear();
        Point[] points = new Point[4]
        {
            new Point(0,  0),
            new Point(300 , 300),
            new Point(400, 500),
            new Point(700, 100 )
        };
        DrawLine(points);
        //DrawLine2(points);
    }

    private void DrawLine(Point[] points)
    {
        int i;
        int count = points.Length;
        for (i = 0; i < count - 1; i++)
        {
            Line myline = new Line();
            myline.Stroke = Brushes.Red;
            myline.X1 = points[i].X;
            myline.Y1 = points[i].Y;
            myline.X2 = points[i + 1].X;
            myline.Y2 = points[i + 1].Y;
            canvas.Children.Add(myline);
        }
    }

    private void DrawLine2(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 = 1;
        canvas.Children.Add(line);
    }

1
谢谢,非常有用!+1 - Leonel Aguilar

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接