標籤:
先上
滑鼠三個事件
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寫出來的應該是不會閃爍的
C#表單上繪製矩形