2014-04-14 63 views
3

我一直在用C#繪製應用程序;我想添加一個選項來切換用當前畫筆繪製橢圓。我一直難以理解如何使橢圓的大小和Y位置在按住鼠標的同時發生變化。有任何想法嗎? 這是我的代碼。用於繪製應用程序的可定製橢圓

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 ZSPainter 
{ 
    public partial class Form1 : Form 
    { 
     string drawToolString; 
     Graphics g; 
     bool c = false; 
     bool drawEllipse = false; 
     Point sp = new Point(0, 0); 
     Point ep = new Point(0, 0); 
     Pen p = new Pen(Color.Black, 1); 
     Brush b = new SolidBrush(Color.Black); 
     public Form1() 
     { 
      InitializeComponent(); 
     } 

     private void penToolStripMenuItem_Click(object sender, EventArgs e) 
     { 
      drawToolString = "pen"; 
      toolString.Text = "Current Tool: Pen"; 
     } 

     private void brushToolStripMenuItem_Click(object sender, EventArgs e) 
     { 
      drawToolString = "brush"; 
      toolString.Text = "Current Tool: Brush"; 
     } 

     private void Form1_MouseDown(object sender, MouseEventArgs e) 
     { 
      sp = e.Location; 
      if(e.Button == MouseButtons.Left) 
       c = true; 
     } 

     private void Form1_MouseMove(object sender, MouseEventArgs e) 
     { 
      if (drawToolString == "pen" && c) 
      { 
       ep = e.Location; 
       g = this.CreateGraphics(); 
       if(!drawEllipse) 
       g.DrawLine(p, sp, ep); 
       /*else 
       * 
        *------Here is where I want an ellipse to drawn if drawEllipse is true.------ 

       */ 


      } 
      else if (drawToolString == "brush" && c) 
      { 
       ep = e.Location; 
       g = this.CreateGraphics(); 
       if(!drawEllipse) 
       g.DrawLine(new Pen(b, 3), sp, ep); 
       /*else 
       * 
        *------Here is where I want an ellipse to drawn if drawEllipse is true.------ 

       */ 
      } 
      sp = ep; 
     } 

     private void Form1_MouseUp(object sender, MouseEventArgs e) 
     { 
      c = false; 
     } 

     private void ellipse_Click(object sender, EventArgs e) 
     { 
      drawEllipse = !drawEllipse; 
     } 
    } 
} 

回答

0

使用圖片框與透明的背景和橢圓已經從(每例)圖像文件繪製,並把它在鼠標的座標。

但是要小心,這會給你的代碼帶來很多麻煩,你正在繪製到窗體上,當它刷新時,所有的東西都會在刷新的區域被清除,所以如果你放置並移動控件,將被清除。

我建議創建一個位圖,將此位圖設置爲表單的背景並繪製到該位圖,然後它將保持不變(並且更容易保存)。

此外,您需要在MouseDown事件上設置鼠標捕獲並在MouseUp上釋放,否則表單在顯示圖片框後不會捕獲MouseMove事件。

如果您不想使用圖片框,但是將繪圖切換爲位圖,則可以在該圖形上繪製並刷新之前繪製橢圓的區域,這樣繪圖將被保留,並且橢圓會移過來。