时间:2022-11-10 09:21:36 | 栏目:.NET代码 | 点击:次
本文实例为大家分享了C#使用Chart绘制曲线的具体代码,供大家参考,具体内容如下
新建一个控制台应用程序,程序名:WindowsFormsApp2,将下面的代码拷贝进去即可
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Windows.Forms.DataVisualization.Charting; namespace WindowsFormsApp2 { public partial class Form1 : Form { public Form1() { InitializeComponent(); timer1.Interval = 5000; textBox1.Text = "0"; } private void Form1_Load(object sender, EventArgs e) { } private void chart1_Click(object sender, EventArgs e) { } private void button1_Click(object sender, EventArgs e) { timer1.Start(); } private void timer1_Tick(object sender, EventArgs e) { // 设置曲线的样式 Series series = chart1.Series[0]; // 画样条曲线(Spline) series.ChartType = SeriesChartType.Spline; // 线宽2个像素 series.BorderWidth = 2; // 线的颜色:红色 series.Color = System.Drawing.Color.Red; // 图示上的文字 series.LegendText = "动态曲线"; // 测试代码 数据转换 int values = Convert.ToInt16(textBox1.Text); // 在chart中显示数据 int x = 0; series.Points.AddXY(x, values); x++; if (x == 100) x = 0; // 设置显示范围 ChartArea chartArea = chart1.ChartAreas[0]; chartArea.AxisX.Minimum = 0; chartArea.AxisX.Maximum = System.Double.NaN; chartArea.AxisY.Minimum = 0d; chartArea.AxisY.Maximum = System.Double.NaN; //自动去判断 } private void textBox1_TextChanged(object sender, EventArgs e) { } private void textBox2_TextChanged(object sender, EventArgs e) { } } }
小编分享一段收藏的代码:C#更新数组实现动态曲线:
private void timer定时_Tick(object sender, EventArgs e) { if (Flash == 0) //当刷新时 { Pen middleLine = new Pen(Color.White); SolidBrush blackBrush = new SolidBrush(Color.Black); //定义了一个单色的黑色画笔 graphic = Graphics.FromImage(pictureBox图像.Image); graphic.FillRectangle(blackBrush, 0, 0, 500, 251); //将画布填充为黑色矩形 Point pt1 = new Point(0, 125); //中间线的两点 Point pt2 = new Point(500, 125); graphic.DrawLine(middleLine, pt1, pt2); //画中间线 } Random random = new Random(); pointList = new Point[50]; //实例化坐标数组* int data = random.Next(-800, 800); //生成一个随机数 // Point p; //申明一个坐标变量 for (int i = 1; i <50 ; i++) //更新数组 { N[i - 1] = N[i]; pointList[i - 1] = pointList[i]; //更新点的坐标 } N[49] = data; pointList[49].X = 49 * time; pointList[49].Y = data; if (Flash == 0) { if (Flash == 0) { int k1 = 0, k2 = 0; for (int i = 0; i < 49; i++) { k1 = (int)(lineD - N[i] / times); k2 = (int)(lineD - N[i + 1] / times); graphic.FillEllipse(new SolidBrush(Color.Red), (i * time), k1, 4, 4); //填充边框所定义的椭圆内部,由椭圆边框左上角坐标和椭圆宽度和高度组成 //graphic.DrawLine(new Pen(Color.FromArgb(255, 255, 0), 1), new Point(i * time, k1), new Point((i + 1) * time, k2)); //两点之间连线 pointList[i].X = i * time; pointList[i].Y = k1; } graphic.FillEllipse(new SolidBrush(Color.Red), (49 * time), k2, 4, 4); graphic.DrawCurve(new Pen(Color.FromArgb(255, 255, 0), 1), pointList, 0.5f); } pictureBox图像.Refresh(); //刷新picturebox } }