使用DrawPolygon在C#中创建单个六边形

时间:2016-05-15 09:09:45

标签: c# visual-studio

好的,所以我创建了一个三角形,但我不能为我的生活找出坐标来创建一个简单的六边形,

Point[] shape = new Point[3];        
            shape[0] = new Point(200, 100);        
            shape[1] = new Point(300, 200);
            shape[2] = new Point(100, 200);

这会产生一个三角形,但我无法弄清楚六角形的x和y值,听起来像一个简单的问题,但我的大脑今天工作不正常,下面是六角形的数组我无法想象超出价值观。

Point[] shape = new Point[6];        
                shape[0] = new Point(0, 0);         
                shape[1] = new Point(0, 0);
                shape[2] = new Point(0, 0);     
                shape[3] = new Point(0, 0);
                shape[4] = new Point(0, 0);
                shape[5] = new Point(0, 0);

任何帮助都会非常感谢!

1 个答案:

答案 0 :(得分:9)

由于我已经写过评论,我想我应该在一些真实的代码中证明这一点。

我创建了一个带有Panel对象的WinForms应用程序,我可以在其上绘制。然后,我已经覆盖了Paint事件,以便画出六边形。

    private void panel1_Paint(object sender, PaintEventArgs e)
    {
        var graphics = e.Graphics;

        //Get the middle of the panel
        var x_0 = panel1.Width / 2;
        var y_0 = panel1.Height / 2;

        var shape = new PointF[6];

        var r = 70; //70 px radius 

        //Create 6 points
        for(int a=0; a < 6; a++)
        {
            shape[a] = new PointF(
                x_0 + r * (float)Math.Cos(a * 60 * Math.PI / 180f), 
                y_0 + r * (float)Math.Sin(a * 60 * Math.PI / 180f));
        }

        graphics.DrawPolygon(Pens.Red, shape);            
    }

然后绘制

hexagon

正如我所说,关键是要将六边形视为一个&#34;离散的&#34;圈。这些点都被计算为在正圆的外部,然后用直线连接。您可以使用此技术创建所有常规n-Point形状(五边形,例如5-regular形状;)

所以,你只是&#34;刻字&#34;获得六边形的圆圈中的6个点,如此图所示,具有常规的5点形状:

hexa2

然后请记住,您可以计算点的(x,y)坐标,其极坐标为(r, phi)

coordinate_trafo

enter image description here

您还可以在其中添加偏移量offset,在我的情况下,我正在绘制框架的中心。