使用鼠标点绘制多边形的C#代码

5
我需要能够使用鼠标点击位置绘制多边形。这是我的当前代码:
 //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);
                }

谢谢


我假设你正在使用WinForms。你提供了代码,但它是否有效?你的问题是什么? - GôTô
是的,我是。但是它不起作用,我无法想出如何将鼠标点击存储在数组中,以便它们可以像在MS Paint中一样通过线连接起来。 - Chris Bacon
用户应该如何绘制多边形?逐行绘制还是一次性绘制整个多边形?您希望用户左键单击x次以获取点,然后右键单击以进行绘制(否则您如何知道用户何时完成)? - GôTô
理想情况下,用户可以无限制地绘制多边形形状,直到右键单击停止。 - Chris Bacon
2个回答

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

3

首先,添加以下代码:

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

在你绘制的对象上,捕获OnClick事件。其中一个参数应该包含点击的X和Y坐标。将它们添加到points数组中:
points.Add(new Point(xPos, yPos));

最后,在绘制线条时,请使用以下代码:

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

编辑:

好的,上面的代码并不完全正确。首先,它很可能是一个点击事件而不是一个OnClick事件。其次,为了获取鼠标位置,你需要在points数组中声明两个变量。

    int x = 0, y = 0;

然后有一个鼠标移动事件:
    private void MouseMove(object sender, MouseEventArgs e)
    {
        x = e.X;
        y = e.Y;
    }

然后,在您的点击事件中:

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

目前我在OnClick事件中没有任何代码,那么这个事件的代码应该怎么写呢? - Chris Bacon
这些都在PictureBox事件中吗? - Chris Bacon
目前它并没有在picturebox上显示多边形,而是显示在其后的边缘上。 - Chris Bacon
在它的边缘后面?你指的是什么? - Entity
哦,看起来PictureBox有一个MouseClick事件,而不是Click事件。 - Entity
显示剩余3条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接