- using System;
- using System.Collections.Generic;
- using System.ComponentModel;
- using System.Data;
- using System.Drawing;
- using System.Text;
- using System.Windows.Forms;
- using System.Threading; //增加线程命名空间
- namespace 正弦曲线
- {
- public partial class Form1 : Form
- {
- public Form1()
- {
- InitializeComponent();
- }
- private void Form1_Paint(object sender, PaintEventArgs e)
- {
- Thread t1 = new Thread(new ThreadStart(MyDraw)); //定义线程
- t1.IsBackground = true; //设置线程为后台线程,运行时不影响主线程
- t1.Start(); //启动线程
- // MyDraw();
- }
- private void MyDraw()
- {
- //通过许多短的直线构建出正弦曲线
- float x1, x2, y1, y2;
- x1 = 0;
- y1 = 300;
- Graphics g = this.CreateGraphics();
- Pen p = new Pen(Color.Red);
- for (int i = 0; i < this.Width; i += 5)
- {
- //得到直线的终点
- x2 = x1 + 5;
- y2 = (float)(-50 * Math.Sin(x2 / 60) + 300);
- //画直线
- g.DrawLine(p, x1, y1, x2, y2);
- //画完直线后,将终点当起点,准备画下一条直线
- x1 = x2;
- y1 = y2;
- Thread.Sleep(100); //实现暂停功能,每次循环暂停100毫秒
- }
- g.Dispose();
- }
- }
- }
在上面的 Form1_Paint()方法中,如果把前三行注释掉,而只使用第四行代码,一样可以实现画图,但你会明显感觉到窗体被卡死了。这就是使用线程的好处.
本文介绍了一个使用C#和Windows Forms绘制动态正弦曲线的应用实例。通过创建后台线程来逐段绘制正弦曲线,避免了界面卡顿的问题,并介绍了如何利用线程改善用户体验。
17万+

被折叠的 条评论
为什么被折叠?



