I have a WinForms user control and I’m trying to draw 15 rows of 15 squares. If the size of the control changes, then the squares should get smaller, but still have 15 rows of 15 squares, like this pattern:
OOOOOOOOOOOOOOO
OOOOOOOOOOOOOOO
OOOOOOOOOOOOOOO
OOOOOOOOOOOOOOO
OOOOOOOOOOOOOOO
OOOOOOOOOOOOOOO
OOOOOOOOOOOOOOO
OOOOOOOOOOOOOOO
OOOOOOOOOOOOOOO
OOOOOOOOOOOOOOO
OOOOOOOOOOOOOOO
OOOOOOOOOOOOOOO
OOOOOOOOOOOOOOO
OOOOOOOOOOOOOOO
OOOOOOOOOOOOOOO
I am trying to use ClientSize.Width and ClientSize.Height to divide by 15, but its not coming out exactly right. Any help with this algorithm would be appreciated!
This is in C#, by the way.
Here is the code I have:
Graphics g = e.Graphics;
g.DrawRectangle(Pens.Black, 0, 0, ClientSize.Width - 1, ClientSize.Height - 1);
if (ClientSize.Width > ClientSize.Height)
{
int ndx = (int)Math.Ceiling(ClientSize.Height/15f);
for (int x = 0; x < ClientSize.Width; x += ndx)
{
for (int y=0 ; y<ClientSize.Height; y+=ndx)
{
g.DrawLine(Pens.Black, x, y, x + ndx, y);
g.DrawLine(Pens.Black, x, y, x, y + ndx);
}
}
}
else
{
int ndx = (int)Math.Ceiling(ClientSize.Width / 15f);
for (int x = 0; x < ClientSize.Width; x += ndx)
{
for (int y = 0; y < ClientSize.Height; y += ndx)
{
g.DrawLine(Pens.Black, x, y, x + ndx, y);
g.DrawLine(Pens.Black, x, y, x, y + ndx);
}
}
}
g.Dispose();
Part of the problem is that your grid will only fit if the container’s width and height are exactly divisible by 15. Try rounding down.
After you draw your grid, explicitly blackout the area past the last row and column. You’ll have a thick black border but it will clearly define the 15×15 grid.
If you want to avoid the black border, force the
ClientSize.Widthand.Heightto be multiples ofColumnCountandRowCountrespectively.