因为自己刚接触winform一星期,没有找到动态绘图的方法,所以自己写了个,写的不好,请轻拍,请指教~
自定义一个控件,然后实现:
public partial class CheckResult : UserControl { public CheckResult() { InitializeComponent(); } private void CheckResult_Load(object sender, EventArgs e) { } /// <summary> /// 检测失败,划叉号 /// </summary> public void DrawFailMark() { int brushWidth = 14; Point startPoint = new Point(50, 3); Pen pen = new Pen(Brushes.Red, brushWidth); int x = startPoint.X; int y = startPoint.Y; using (Graphics g1 = this.pictureBox1.CreateGraphics()) { g1.Clear(this.BackColor); DrawFailMarkLines(false, g1, pen, x, y, startPoint); g1.Save(); } //以上动态画出的线在窗口缩小或隐藏后重新显示时会因为form的重绘而消失,所以需要用Bitmap再画一遍 this.pictureBox1.Refresh(); Bitmap bmp = new Bitmap(this.pictureBox1.Width, this.pictureBox1.Height); Graphics g2 = Graphics.FromImage(bmp); g2.Clear(this.BackColor); DrawFailMarkLines(true, g2, pen, x, y, startPoint); g2.Dispose(); this.pictureBox1.Image = bmp; } private void DrawFailMarkLines(bool isRedraw, Graphics g, Pen pen, int x, int y, Point startPoint) { for (int i = 0; i < 14; i++) { g.DrawLine(pen, x, y, x + 10, y + 10); x += 10; y += 10; i++; if (!isRedraw) { Thread.Sleep(50);//通过线程sleep实现动态绘图 } } y = startPoint.Y; for (int i = 0; i < 14; i++) { g.DrawLine(pen, x, y, x - 10, y + 10); x -= 10; y += 10; i++; if (!isRedraw) { Thread.Sleep(50);//通过线程sleep实现动态绘图 } } g.Save(); } /// <summary> /// 检测成功,划对号 /// </summary> public void DrawSuccessMark() { int brushWidth = 14; Point startPoint = new Point(50, 50); Pen pen = new Pen(Brushes.Green, brushWidth); int x = startPoint.X; int y = startPoint.Y; using (Graphics g1 = this.pictureBox1.CreateGraphics()) { g1.Clear(this.BackColor); DrawSuccessMarkLines(false, g1, pen, x, y, startPoint, brushWidth); g1.Save(); } //以上动态画出的线在窗口缩小或隐藏后重新显示时会因为form的重绘而消失,所以需要用Bitmap再画一遍 this.pictureBox1.Refresh(); Bitmap bmp = new Bitmap(this.pictureBox1.Width, this.pictureBox1.Height); Graphics g2 = Graphics.FromImage(bmp); g2.Clear(this.BackColor); DrawSuccessMarkLines(true, g2, pen, x, y, startPoint, brushWidth); g2.Dispose(); this.pictureBox1.Image = bmp; } private void DrawSuccessMarkLines(bool isRedraw, Graphics g, Pen pen, int x, int y, Point startPoint, int brushWidth) { for (int i = 0; i < 7; i++) { g.DrawLine(pen, x, y, x + 10, y + 10); x += 10; y += 10; i++; if (!isRedraw) { Thread.Sleep(50);//通过线程sleep实现动态绘图 } } x -= brushWidth / 2; for (int i = 0; i < 15; i++) { g.DrawLine(pen, x, y, x + 10, y - 10); x += 10; y -= 10; i++; if (!isRedraw) { Thread.Sleep(50);//通过线程sleep实现动态绘图 } } } }