将自定义矩形传递给它时,DrawBorder不起作用

时间:2012-01-10 11:26:23

标签: c# .net winforms

在将新的矩形对象传递给它时,我似乎无法使DrawBorder工作:

private void answered_choice_1_paint(object sender, PaintEventArgs e)
{
    Size s = new Size(Math.Max(answered_choice_1.Height, icon_correct.Height) + 4,  answered_choice_1.Width + 22 + this.default_margin + 4);
    Point p = new Point(answered_choice_1.Location.X - 22 - this.default_margin - 2, answered_choice_1.Location.Y - 2);
    Rectangle r = new Rectangle(p, s);
    if (icon_correct.Location.Y == answered_choice_1.Location.Y)
    {
        ControlPaint.DrawBorder(e.Graphics, r, Color.Green, ButtonBorderStyle.Solid);
    }
}

但是,传递标签的矩形有效:

private void answered_choice_1_paint(object sender, PaintEventArgs e)
{
    if (icon_correct.Location.Y == answered_choice_1.Location.Y)
    {
        ControlPaint.DrawBorder(e.Graphics, answered_choice_1.DisplayRectangle, Color.Green, ButtonBorderStyle.Solid);
    }
}

从代码中可以看出,我的目的是在answered_choice_1标签和icon_correct pictureBox周围绘制一个矩形边框,所以第二个代码摘录会绘制一个矩形,但我想绘制第一段摘录中的矩形。

修改 我把它缩小到了这个范围:

int x,y;
x = answered_choice_1.Location.X - 22 - this.default_margin - 2;
y = answered_choice_1.Location.Y - 2;
Point p = new Point(x, y);

使用调试器我发现answered_choice_1.Location.Y - 2评估为210购买y得到值0;这很奇怪但是一致:如果我为Rectangle r调用一个不同的构造函数,我会得到相同的结果。

任何进一步的帮助将不胜感激。

第二次编辑之前的编辑错误,尽管这是我在Visual Studio IDE中看到的数据。温贝托的评论给了我最后的线索,我已经批准了他的回答。

2 个答案:

答案 0 :(得分:2)

您的“尺寸”计算看起来像宽度高度和高度宽度:

Size s = new Size(Math.Max(answered_choice_1.Height, icon_correct.Height) + 4,
                  answered_choice_1.Width + 22 + this.default_margin + 4);

由于很难说出代码的其余部分是什么样的,我只能猜测它的反转可能有用:

Size s = new Size(answered_choice_1.Width + 22 + this.default_margin + 4,
                  Math.Max(answered_choice_1.Height, icon_correct.Height) + 4)

答案 1 :(得分:1)

我认为你试图在一对控件周围画一个边框:一个标签左边的图标。是这种情况吗?

+------------------------------+
|                              |
| ICON   answered_choice_1     |---> border on a 4px margin around both controls
|                              |
+------------------------------+
^        ^
|  22px  |

如果是这样,您的绘画代码有问题。它试图使用answered_choice_1的“surface”(图形实例)在区域外绘制。它不起作用。

相反,您可以将图标和标签放在面板中,然后在需要时绘制面板的边框。有点像你已经做过,但提到panel_1而不是answered_choice_1

private void panel_1_paint(object sender, PaintEventArgs e)
{
    if (icon_correct.Location.Y == answered_choice_1.Location.Y)
    {
        ControlPaint.DrawBorder(e.Graphics, panel_1.DisplayRectangle,  Color.Green, ButtonBorderStyle.Solid);
    }
}

或者,您可以为面板指定FixedSingle边框样式,但AFAIK边框颜色将由系统定义。