此项目源码下载地址:https://github.com/lizhiqiang0204/WpfLineChartV1.1
效果图如下:
此项目把折线图制作成了一个控件,在主界面设置好参数直接调用即可,下面是主程序片段
public MainWindow() { InitializeComponent(); userControl1_Para.xGrap = 2;//设置X轴相邻采集点的间隔 userControl1_Para.xGrapLable = 100;//设置X轴时间标签的间隔 userControl1_Para.xGrapLablePoint = userControl1_Para.xGrapLable/ userControl1_Para.xGrap;//相邻两个时间标签内有多少个采集点 userControl1_Para.xWidth = userControl.Width - 50; userControl1_Para.yGrap = -10; userControl1_Para.yStartValue = 100; userControl1_Para.yGrapLable = 50; userControl1_Para.yLables = ((int)userControl.Height - 50) / userControl1_Para.yGrapLable; userControl.myCanvasInit(userControl1_Para); } private void timer_Tick(object sender, EventArgs e) { y = y + 0.1; //随机生成Y坐标 //collectPoint.point = new Point(i, (new Random()).Next(0, 100)); collectPoint.point = new Point(x, Math.Sin(y)*100+100); collectPoint.curTime = DateTime.Now; userControl.AddPoint1(collectPoint); }
类库添加点的函数
public void AddPoint1(CollectPoint collectPoint) { x = x + userControl1_Para.xGrap; collectPoint.point.X = x; //移动背景不移动点 double xMove = collectPoint.point.X * (-1) + userControl1_Para.xWidth; _myPolyline.Points.Add(collectPoint.point);//添加新的数据点 _myCanvas.Margin = new Thickness(xMove, 0, 0, 0);//设置外边距实现移动,放大缩小 //移动X轴标签背景 TextBlock xText = new TextBlock(); xText.Visibility = Visibility.Hidden; xText.SetValue(Grid.RowProperty, 1); //设置按钮所在Grid控件的行 xGrid.Children.Add(xText);//为每个点添加对应的时间值 xText.Text = collectPoint.curTime.ToString("HH:mm:ss"); xText.Margin = new Thickness(collectPoint.point.X, 0, 0, 0); collectPoints.Add((new CollectPoint() { point = collectPoint.point, curTime = collectPoint.curTime })); xLableCanvas.Margin = new Thickness(xMove, 0, 0, 0);//设置外边距实现移动,放大缩小 if (xMove % userControl1_Para.xGrapLable == 0) xText.Visibility = Visibility.Visible; if (collectPoint.point.X > userControl1_Para.xWidth) { _myPolyline.Points.RemoveAt(0); collectPoints.RemoveAt(0); xGrid.Children.RemoveAt(0); } }
本人也是新手,代码规范写的不是很好,见谅!