首页 > 解决方案 > 在固定的方形图片框中制作方形矩形,如网格

问题描述

我正在使用 c# 和 Visual Studio(.NET Framework) 开发一个项目,在该项目中,用户可以使用 PictureBox 与排列在网格中的一些方形框进行交互。默认大小为 20 x 20 用户可以更改 PictureBox 中的正方形数量,但 PictureBox 的大小应保持不变。我使用 WinForms。

我通过使用我的逻辑和一些互联网的代码尝试过的代码,我让它作为一个带有正方形的正方形网格工作,但是当我增加 xNum 或 yNum 时,网格开始变得越来越小。这是我执行矩形绘制的函数:

 public Graphics CreateRectangles(int xNum, int yNum, Graphics g)
        {
            rectList.Clear();

            int width = (pictureBox1.Image.Height / xNum) - 1;
            int height = (pictureBox1.Image.Height / yNum) - 1;
            int both = (width + height) / 2;

            Rectangle rect = new Rectangle();
            rect.Size = new Size(both, both);
            for(int x = 0; x < xNum; x++)
            {
                rect.X = x * rect.Width;
                for(int y = 0; y < yNum; y++)
                {
                    rect.Y = y * rect.Height;
                    rectList.Add(rect);
                }
            }
            pictureBox1.Refresh();
            foreach (Rectangle rec in rectList)
            {
                Pen p = new Pen(Color.Blue);
                g.DrawRectangle(p, rec);
            }
            g.DrawLine(new Pen(Color.Blue), 0, yNum * height, xNum * width, yNum * height);
            return g;
        }

每当我想绘制时,我都会清除屏幕

                pictureBox1.Image = new Bitmap((Screen.PrimaryScreen.Bounds.Width / 8) * 7, (Screen.PrimaryScreen.Bounds.Height / 8) * 7);

请帮我解决这个问题,使 pictureBox1 中的正方形区域的大小保持最大,而不会与其他 GUI 元素重叠。提前致谢。

编辑:我知道如果我有相对大小,那么单元格大小会变小,但这是预期的行为,但我不希望表格的整个框架变小,就像我增加 xNum 时一样,外框/盒子的大小应保持不变

标签: c#.netrectanglesdrawrectangle

解决方案


推荐阅读