Search code examples
c#graphic

Drawing rectangles and circles in C# not working properly


So I'm creating a 2d grid with drawings of rectangles and circles inside of a flowLayoutPanel. The problem I'm getting however is that they are not being drawn completely.

This is the code of the event when a button is pushed.

    private void DrawIt()
    {

        System.Drawing.Graphics graphics = flowLayoutPanel1.CreateGraphics();
        graphics.Clear(Form1.ActiveForm.BackColor);

        int row = Convert.ToInt32(textBox1.Text);
        int column = Convert.ToInt32(textBox2.Text);

        flowLayoutPanel1.Width = (row * 50) + 30;
        flowLayoutPanel1.Height = (column * 50) + 1;

        for (int j = 0; j < column; j++)
        {
            for (int i = 0; i < row; i++)
            {
                System.Drawing.Rectangle rectangle = new System.Drawing.Rectangle(50 * i, 50*j, 50, 50);
                graphics.DrawEllipse(System.Drawing.Pens.Black, rectangle);
                graphics.DrawRectangle(System.Drawing.Pens.Red, rectangle);
            }
        }
    }

I make each rectangle the size of 50 px so I know how big to calculate the width and height. I even added some extra in case I messed up. But in the end I get the following:

Incomplete drawings

Any ideas on what could be the problem?


Solution

  • You create the graphics from the panel and then change its size. The graphics object therefore clips to the previous size.

    Change the size before you create the graphics object:

    int row = Convert.ToInt32(textBox1.Text);
    int column = Convert.ToInt32(textBox2.Text);
    
    flowLayoutPanel1.Width = (row * 50) + 30;
    flowLayoutPanel1.Height = (column * 50) + 1;
    
    System.Drawing.Graphics graphics = flowLayoutPanel1.CreateGraphics();
    graphics.Clear(Form1.ActiveForm.BackColor);
    
    for (int j = 0; j < column; j++)
    {
        for (int i = 0; i < row; i++)
        {
            System.Drawing.Rectangle rectangle = new System.Drawing.Rectangle(50 * i, 50 * j, 50, 50);
            graphics.DrawEllipse(System.Drawing.Pens.Black, rectangle);
            graphics.DrawRectangle(System.Drawing.Pens.Red, rectangle);
        }
    }