简述

  WPF开发中经常需要绘制曲线、直方图等。虽然WPF自带了绘制图形等基础功能,但做程序一个很基础的原则就是避免重复造轮子。在GitHub上找到了微软官方的WPF绘制曲线开源库:InteractiveDataDisplay.WPF。
我使用的IDE是VS201x,建议使用NuGet安装--引用InteractiveDataDisplay.WPF。如何使用NuGet,请自行百度。
以下是我实验的该开源库绘制的WPF曲线程序。

代码

MainWindow.xaml


    
        
            
            
        

        
        
            
                
            
            
        

        
        
            
                
            
            
        

    

MainWindow.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Threading;
using InteractiveDataDisplay.WPF;

namespace WpfDrawPlot
{
    /// 
    /// MainWindow.xaml 的交互逻辑
    /// 
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();

            //线程中更新曲线
            Thread threadTmp = new Thread( UpdateChart );
            threadTmp.Start();
        }

        private void UpdateChart()
        {
            int nPointNum = 100;
            Random randm = new Random();
            double[] dArray = new double[ nPointNum ];
            double[] dX = new double[ nPointNum ];
            double[] dY = new double[ nPointNum ];
            double dRandomtTmp = 0;

            while( true )
            {
                Thread.Sleep( 1000 );//每秒刷新一次
                for ( int n = 0; n < dArray.Length; n++ )
                {
                    dRandomtTmp = randm.NextDouble();
                    dArray[ n ] = ( dRandomtTmp < 0.5 ) ? -dRandomtTmp * dArray.Length : dRandomtTmp * dArray.Length;
                }
                for ( int n = 0; n < dX.Length; n++ )
                {
                    dX[ n ] = n;
                    dY[ n ] = randm.Next( dX.Length );
                }

                //更新UI
                Dispatcher.Invoke( new Action( delegate
                {
                    this.BarChart.PlotBars( dArray );
                    this.LineChart.Plot( dX, dY );
                } ) );
            }
        }
    }
}

效果

WPF:WPF绘制曲线_第1张图片