在C#中使用鼠标点绘制多边形

时间:2010-10-21 13:47:23

标签: c# polygon mouseclick-event

我需要能够使用鼠标点击位置绘制多边形。 这是我目前的代码:

 //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);
                }

由于

2 个答案:

答案 0 :(得分:4)

这里有一些示例代码:

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);
}

答案 1 :(得分: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事件。其次,要获得鼠标位置,需要使用points数组声明两个变量

    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));
    }