c# – 使用自定义绘图在按钮上绘制标签

所以我有这个小应用程序,有一个按钮和一个标签.该按钮具有自定义OnPaint方法,使其看起来独特.标签目前没有.然而,标签似乎是在按钮内部绘制,没有明显的原因.看这个:

为清楚起见,我已禁用渲染填充矩形,因为它主要涵盖了问题.这是我的按钮的OnPaint代码:

    protected override void OnPaint(PaintEventArgs e)
    {
        Graphics g = e.Graphics;
        g.SmoothingMode = SmoothingMode.HighQuality;
        Pen p = new Pen (Color.Black, 2);
        Rectangle fillRect = new Rectangle (e.ClipRectangle.X, e.ClipRectangle.Y, e.ClipRectangle.Width - 2, e.ClipRectangle.Height - 2);
        Brush b;
        if (MouseHovering)
        {
            b = new SolidBrush (Color.DarkSlateGray);
        } 
        else
        {
            b = new SolidBrush (Color.Gray);
        }
        //g.FillRectangle (b, fillRect);
        g.DrawRectangle (p, e.ClipRectangle);
        //g.DrawString (Text, new Font ("Arial", 8), new SolidBrush (Color.Black), new Point (4, 4));
    }

以下是在主窗体类中创建标签和按钮的代码:

label = new Label ();
label.Text = "Hello World";
label.Top = 15;
label.Left = 180;
label.AutoSize = true;
Controls.Add (label);
CButton b = new CButton ();
b.Text = "Click me for a new sentence";
b.AutoSize = true;
b.Top = 10; b.Left = 10;
Controls.Add (b);

上面的内容在构造函数中调用.然后按下按钮时,标签文本设置如下:

label.Text = Specifier + " " + Verb + " a " + CommonNoun;

那么这里发生了什么,我该如何解决?如果您需要任何其他代码来了解问题,请不要犹豫.

最佳答案 有些东西不见了. g.Clear(背景色);将清除Graphics对象正在绘制的缓冲区的内容.

protected override void OnPaint(PaintEventArgs e)
    {
        Graphics g = e.Graphics;
        g.Clear(BackColor);
        g.SmoothingMode = SmoothingMode.HighQuality;
        Pen p = new Pen (Color.Black, 2);
        Rectangle fillRect = new Rectangle (e.ClipRectangle.X, e.ClipRectangle.Y, e.ClipRectangle.Width - 2, e.ClipRectangle.Height - 2);
        Brush b;
        if (MouseHovering)
        {
            b = new SolidBrush (Color.DarkSlateGray);
        } 
        else
        {
            b = new SolidBrush (Color.Gray);
        }
        //g.FillRectangle (b, fillRect);
        g.DrawRectangle (p, e.ClipRectangle);
        //g.DrawString (Text, new Font ("Arial", 8), new SolidBrush (Color.Black), new Point (4, 4));
        b.Dispose();   //ADD THIS
        p.Dispose();   //ADD THIS TOO
    }

还要记住,处理您正在使用的任何GDI资源非常重要.这些可能是.NET构造,但它们实际上是后台中的非托管对象.正确处理它们可以防止内存泄漏和难以理解的崩溃.

此外,您不应该使用剪辑矩形,使用控件的实际边界.

最好的选择是将它们包装在using语句中:

protected override void OnPaint(PaintEventArgs e)
    {
        Graphics g = e.Graphics;
        g.SmoothingMode = SmoothingMode.HighQuality;

        Color fillColor = MouseHovering ? Color.DarkSlateGray : Color.Gray;

        using (Pen p = new Pen(Color.Black, 2))
        using (Brush b = new SolidBrush(fillColor))
        {
            Rectangle fillRect = new Rectangle (0, 0, this.Width, this.Height);

            g.DrawRectangle (p, e.ClipRectangle);
        }
    }

使用using语句具有额外的好处,如果在使用中存在异常,则对象仍将被正确处理.另一种选择是将它们包装在try..catch中.最后,除非你需要对异常做一些事情,否则这会更加清晰.

点赞