C# winform折线图绘制

C# winform折线图绘制

之前用PyQt5做过这个玩具,学winformGDI+做个实验。

效果
在这里插入图片描述

源码

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;

namespace lineChart
{
    public partial class Form1 : Form
    {
        private List<int[]> dotList = new List<int[]>();  // 保存每个点的坐标

        private int PART = 5;  // X轴点的距离

        private int num = 0;  // 标记当前点数

        public Form1()
        {
            InitializeComponent();
        }


        // 绘制
        private void updateShow()
        {
            int width = this.pictureBox1.Size.Width;
            int height = this.pictureBox1.Size.Height;
            Bitmap codeImage = new Bitmap(width, height);  // 制作图片大小的画布
            Graphics g = Graphics.FromImage(codeImage);

            PointF[] points = new PointF[this.dotList.Count];  //点坐标列表

            for (int i=0; i < this.dotList.Count; i++)
            {
                PointF pointF = new PointF(this.dotList[i][0], this.dotList[i][1]);
                points[i] = pointF;
            }

            Pen pen = new Pen(Color.Red, 2);  // 创建绘笔

            g.DrawLines(pen, points);  // 绘制线段

            this.pictureBox1.Image = codeImage;
        }

        

        // 定时器生成随机数
        private void timer_Tick(object sender, EventArgs e)
        {
            int[] site = new int[2];

            if (num < (this.pictureBox1.Size.Width / PART))
                num += 1;
            else
            {
                this.dotList.RemoveAt(0);
                foreach(int[] dot in this.dotList)
                {
                    dot[0] -= PART;
                }
            }

            site[0] = num * PART;

            int minY = int.Parse(this.textBox2.Text);
            int maxY = int.Parse(this.textBox3.Text);

            Random rd = new Random();
            int random = rd.Next(minY, maxY);

            site[1] = random * (this.pictureBox1.Size.Height / (maxY - minY) );
            
            this.dotList.Add(site);

            this.textBox1.Text = random.ToString();

            if (this.dotList.Count > 1 )
                this.updateShow();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            timer.Enabled = true;
        }

        private void button2_Click(object sender, EventArgs e)
        {
            timer.Enabled = false;
        }
    }
}

设计器做的UI各控件名称

名称 Name 控件
最小值输入框 textBox2 TextBox
最大值输入框 textBox3 TextBox
实时值显示框 textBox1 TextBox
启动按钮 button1 Button
停止按钮 button2 Button
图片显示 pictureBox1 pictureBox
定时器 timer Timer

PyQt5做的相同例子:https://blog.csdn.net/weixin_42686768/article/details/88375360

发布了34 篇原创文章 · 获赞 54 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/weixin_42686768/article/details/105531890
今日推荐