简体   繁体   English

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

[英]Draw a Polygon using Mouse Points in C#

I need to be able to draw a polygon using mouse click locations. 我需要能够使用鼠标单击位置绘制多边形。 Here is my current code: 这是我目前的代码:

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

Thanks 谢谢

Ok here is some sample code: 好的,这里是一些示例代码:

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

First, add this code: 首先,添加以下代码:

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

On the object you are drawing on, capture the OnClick event. 在您正在绘制的对象上,捕获OnClick事件。 One of the arguments should have the X and Y coordinates of the click. 其中一个参数应该具有点击的X和Y坐标。 Add them to the points array: 将它们添加到points数组:

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

And then finally, where you're drawing the lines, use this code: 最后,在绘制线条的地方,使用以下代码:

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

EDIT: 编辑:

Ok, so the above code isn't exactly correct. 好的,所以上面的代码并不完全正确。 First of all, its most likely a Click event instead of a OnClick event. 首先,它最有可能是Click事件而不是OnClick事件。 Second, To get the mouse position, you need two variables declared up with the points array, 第二,要获得鼠标位置,需要使用points数组声明两个变量,

    int x = 0, y = 0;

Then have a mouse move event: 然后有一个鼠标移动事件:

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

Then, in your Click event: 然后,在您的Click事件中:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM