2010-10-21 95 views
4

我需要能夠使用鼠標點擊位置繪製多邊形。 這裏是我當前的代碼:在C中使用鼠標點繪製多邊形#

//the drawshape varible is called when a button is pressed to select use of this tool 
      if (DrawShape == 4) 
       { 
        Point[] pp = new Point[3]; 
        pp[0] = new Point(e.Location.X, e.Location.Y); 
        pp[1] = new Point(e.Location.X, e.Location.Y); 
        pp[2] = new Point(e.Location.X, e.Location.Y); 
        Graphics G = this.CreateGraphics(); 
        G.DrawPolygon(Pens.Black, pp); 
       } 

感謝

+0

我假設你在winforms上。你提供的代碼,但它的工作?你的問題是什麼? – 2010-10-21 14:00:19

+0

是的,是的,它是行不通的,我可以;噸工作了如何存儲鼠標點擊陣列中,他們被加入一條線,就像在MS漆 – 2010-10-21 14:02:11

+0

用戶應該如何繪製一個多邊形?一行一行,或整個多邊形一次?您希望用戶左鍵單擊點數x次,然後右鍵單擊繪製(否則,您如何知道用戶何時完成)? – 2010-10-21 14:18:27

回答

5

確定這裏是一些示例代碼:

private List<Point> polygonPoints = new List<Point>(); 

private void TestForm_MouseClick(object sender, MouseEventArgs e) 
{ 
    switch(e.Button) 
    { 
     case MouseButtons.Left: 
      //draw line 
      polygonPoints.Add(new Point(e.X, e.Y)); 
      if (polygonPoints.Count > 1) 
      { 
       //draw line 
       this.DrawLine(polygonPoints[polygonPoints.Count - 2], polygonPoints[polygonPoints.Count - 1]); 
      } 
      break; 

     case MouseButtons.Right: 
      //finish polygon 
      if (polygonPoints.Count > 2) 
      { 
       //draw last line 
       this.DrawLine(polygonPoints[polygonPoints.Count - 1], polygonPoints[0]); 
       polygonPoints.Clear(); 
      } 
      break; 
    } 
} 

private void DrawLine(Point p1, Point p2) 
{ 
    Graphics G = this.CreateGraphics(); 
    G.DrawLine(Pens.Black, p1, p2); 
} 
3

首先,添加以下代碼:

List<Point> points = new List<Point>(); 

在您繪製的對象,捕捉onclick事件。其中一個參數應具有點擊的X和Y座標。將它們添加到點數組:

points.Add(new Point(xPos, yPos)); 

然後終於,你在哪裏畫線,使用此代碼:

if (DrawShape == 4) 
{ 
    Graphics G = this.CreateGraphics(); 
    G.DrawPolygon(Pens.Black, points.ToArray()); 
} 

編輯:

好了,以上代碼不完全正確。首先,它最有可能是Click事件而不是OnClick事件。其次,爲了讓鼠標的位置,你需要申報了點陣列的兩個變量,

int x = 0, y = 0; 

然後讓鼠標移動事件:

private void MouseMove(object sender, MouseEventArgs e) 
    { 
     x = e.X; 
     y = e.Y; 
    } 

然後,在你的Click事件:

private void Click(object sender, EventArgs e) 
    { 
     points.Add(new Point(x, y)); 
    } 
+0

OnClick事件的代碼應該如何查看,因爲此刻我根本沒有該事件的任何內容? – 2010-10-21 14:06:11

+0

你在畫什麼多邊形? – Entity 2010-10-21 14:08:58

+0

在圖片箱 – 2010-10-21 14:11:42