在 C# WPF 中绘制多点线

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25438139/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 12:24:01  来源:igfitidea点击:

Draw multi-point Lines in C# WPF

c#wpf

提问by Leonel Aguilar

Im new in C# WPF. I want to create a Line in WPF C# with a Point array.

我是 C# WPF 的新手。我想在 WPF C# 中创建一个带有 Point 数组的 Line。

Like:

喜欢:

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

Line myLine = new Line( points );

How can I do this?

我怎样才能做到这一点?

回答by Rang

if you want to draw it with Line, write a method, or you can use Polyline

如果你想用 绘制它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);
    }