DrawBorder没有';将自定义矩形传递给它时不起作用

本文关键字:不起作用 没有 自定义 DrawBorder | 更新日期: 2023-09-27 18:19:49

在向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中看到的数据。温贝托的评论给了我发生了什么的最后线索,我已经同意了他的回答。

DrawBorder没有';将自定义矩形传递给它时不起作用

您的"size"计算看起来像是以高换宽,以宽换高:

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)

我认为您正试图在一对控件周围绘制一个边框:一个与标签左侧对齐的图标。是这样吗?

+------------------------------+|||ICON answered_choice_1|--->两个控件周围4倍边距的边界||+------------------------------+^^|22像素|

如果是这样,则说明您的绘画代码有问题。它试图使用answered_choice_1的"表面"(Graphics实例)在其区域外绘制。这行不通。

相反,您可以将图标和标签放置在面板内,然后在需要时绘制面板的边框。有点像你已经做过的,但指的是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边框颜色将由系统定义。