【问题标题】:Draw a Polygon using Mouse Points in C#在 C# 中使用鼠标点绘制多边形
【发布时间】:2011-04-28 15:15:43
【问题描述】:

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

 //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。您提供了代码,但它有效吗?你的问题是什么?
  • 是的,我是,是的,它不起作用,我不知道如何将鼠标点击存储在数组中,以便它们通过一条线连接起来,就像在 MS Paint 中一样跨度>
  • 用户应该如何绘制多边形?一行一行,还是一次整个多边形?您希望用户左键单击 x 次,然后右键单击以绘制(否则您如何知道用户何时完成)?
  • 理想情况下,一行一行的点数不限,直到用户右键单击停止绘制多边形形状

标签: c# polygon mouseclick-event


【解决方案1】:

首先,添加这段代码:

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

【讨论】:

  • OnClick 事件的代码应该如何显示,因为目前我在该事件中没有任何内容?
  • 你在什么上面画多边形?
  • 这一切都在图片框事件中吗?
  • 现在它没有在图片框上显示多边形,它显示在它后面的边缘
  • 在它后面的边缘?你这是什么意思?
【解决方案2】:

好的,这里有一些示例代码:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-22
    • 1970-01-01
    • 1970-01-01
    • 2016-03-25
    • 2011-01-20
    相关资源
    最近更新 更多