先上效果图
鼠标三个事件
private void Form1_MouseDown(object sender, MouseEventArgs e) { //记录开始点 this.mousedown = true; this.startpoint = e.Location; } private void Form1_MouseMove(object sender, MouseEventArgs e) { //记录结束点。绘制到窗口上 if (mousedown) { this.endpoint = e.Location; this.Refresh(); gform.DrawImage(this.bmsave, new Point(0, 0)); Rectangle rect = new Rectangle(); this.rect_play(ref rect); gform.DrawRectangle(new Pen(Color.Black), rect); } } private void Form1_MouseUp(object sender, MouseEventArgs e) { //记录结束点。绘制到bitmap上 this.endpoint = e.Location; this.mousedown = false; Rectangle rect = new Rectangle(); this.rect_play(ref rect); g.DrawRectangle(new Pen(Color.Black), rect); gform.DrawImage(this.bmsave, new Point(0, 0)); }
根据startpoint和endpoint两个点去确定要画的矩形Location和width,heigth
private void rect_play( ref Rectangle rect) { //根据两个点确定矩形的左上角点Location if (this.startpoint.X > this.endpoint.X && this.startpoint.Y < this.endpoint.Y) { rect.Location = new Point(this.endpoint.X, this.startpoint.Y); } else if (this.startpoint.X < this.endpoint.X && this.startpoint.Y > this.endpoint.Y) { rect.Location = new Point(this.startpoint.X, this.endpoint.Y); } else if (this.startpoint.X > this.endpoint.X && this.startpoint.Y > this.endpoint.Y) { rect.Location = this.endpoint; } else { rect.Location = this.startpoint; } //获取两点的X,Y距离 rect.Width = Math.Abs(this.startpoint.X - this.endpoint.X); rect.Height = Math.Abs(this.startpoint.Y - this.endpoint.Y); if (rect.Width == 0 && rect.Height == 0) { //防止误点的时候进行绘制 } else if (rect.Width == 0) { rect.Width = 1; } else if (rect.Height == 0) { rect.Height = 1; } }
完整实例代码链接:http://pan.baidu.com/s/1sjkpic1
画的时候窗口闪的特别厉害啊,因为大量的Refresh和Draw,开双缓冲也不起多大作用
迟点有时间用QT c++做一个,QT写出来的应该是不会闪烁的
时间: 2024-12-15 01:57:05