Paul
Paul

Reputation: 897

How do I remove the margin when drawing a rectangle inside a panel in a Windows Form?

Firstly, for context, I'm a beginner in C# and I'm playing around with forms.

I have attempted to draw a rectangle to a panel ("myPanel") on a form ("Form1") but there is a margin or some sort of padding which I cannot remove.

I have set the "padding" and "margin" properties of "myPanel" to 0 with no success.

The code is:

namespace Forms___Playing_with_Graphics
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void myPanel_Paint(object sender, PaintEventArgs e)
        {

            // rectangle, slightly smaller than size of panel
            int topLeftx = myPanel.Location.X;
            int topLefty = myPanel.Location.Y;
            int width = myPanel.Size.Width - 5;
            int height = myPanel.Size.Height - 5;

            Graphics g = e.Graphics;

            Rectangle r = new Rectangle(topLeftx, topLefty, width, height);
            Pen p = new Pen(Color.Black, 5F);

            g.DrawRectangle(p, r);
        }
    }
}

A screenshot of the result:

Panel with mysterious padding

How do I remove this padding between the rectangle and the inside left and top edges? My naive expectation was for the rectangle to start in the very top-left corner.

Any help would be greatly appreciated.

Upvotes: 1

Views: 1267

Answers (1)

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236208

Top left corner has coordinates x = 0, y = 0. But you should also keep in mind width of rectangle border. If you want rectangle border to fit exactly to the panel which contains it, then you should step inside half of border width:

private void myPanel_Paint(object sender, PaintEventArgs e)
{
    float borderWidth = 5f;
    float topLeftx = borderWidth / 2;
    float topLefty = borderWidth / 2;
    float width = panel2.ClientSize.Width - borderWidth;
    float height = panel2.ClientSize.Height - borderWidth;

    Graphics g = e.Graphics;
    Pen pen = new Pen(Color.Black, borderWidth);
    g.DrawRectangle(pen, topLeftx, topLefty, width, height);
}

Result:

enter image description here

Upvotes: 1

Related Questions