【问题标题】:How do I remove the margin when drawing a rectangle inside a panel in a Windows Form?在 Windows 窗体的面板内绘制矩形时如何删除边距?
【发布时间】:2017-07-07 04:54:22
【问题描述】:

首先,就上下文而言,我是 C# 的初学者,我正在玩表单。

我试图在表单(“Form1”)上的面板(“myPanel”)上绘制一个矩形,但是有一个边距或某种我无法删除的填充。

我已将“myPanel”的“padding”和“margin”属性设置为 0,但没有成功。

代码是:

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);
        }
    }
}

结果截图:

如何删除矩形与内部左边缘和上边缘之间的填充?我天真的期望矩形从左上角开始。

任何帮助将不胜感激。

【问题讨论】:

  • 面板内部有自己的坐标,所以topLeftx = 0, topLefty = 0。
  • 不要使用myPanel.Location,图纸应该在myPanel.ClientRectangle里面

标签: c# winforms


【解决方案1】:

左上角的坐标 x = 0, y = 0。但你也应该记住矩形边框的宽度。如果您希望矩形边框完全适合包含它的面板,那么您应该进入边框宽度的一半:

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);
}

结果:

【讨论】:

  • plotWindow.ClientSize
  • @LarsTech 这是另一个控件,与myPanel无关
  • 然后我假设 OP 想要myPanel.ClientSize。目前尚不清楚 plotWindow 将在哪里发挥作用。
  • @LarsTech OP 明确表示他希望左边缘和上边缘适合:'如何删除矩形与内部左边缘和上边缘之间的填充?'。所以由 OP 决定这里的高度和宽度是多少
  • 我要使用的 plotWindow 应该是 myPanel。称其为 OP 的拼写错误。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多