2010-10-21 58 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