C# 无法在c中创建按钮渐变#

C# 无法在c中创建按钮渐变#,c#,winforms,C#,Winforms,我试图通过扩展System.Windows.Forms.button类在c#中添加渐变。我遇到的问题是,无论是在设计还是运行时,它都不会向按钮添加渐变,尽管设计师会选择color1、color2和angle字段,因此它肯定会被正确覆盖和实例化。我错过什么了吗 class ps_button : System.Windows.Forms.Button { private Color _Color1 = Color.FromArgb(255, 224, 138, 25); priva

我试图通过扩展System.Windows.Forms.button类在c#中添加渐变。我遇到的问题是,无论是在设计还是运行时,它都不会向按钮添加渐变,尽管设计师会选择color1、color2和angle字段,因此它肯定会被正确覆盖和实例化。我错过什么了吗

class ps_button : System.Windows.Forms.Button
{
    private Color _Color1 = Color.FromArgb(255, 224, 138, 25);
    private Color _Color2 = Color.FromArgb(255, 245, 202, 134);
    private float _ColorAngle = 45f;

    public Color Color1
    {
        get { return _Color1; }
        set
        {
            _Color1 = value;
            this.Invalidate(); // Tell the Form to repaint itself
        }
    }

    public Color Color2
    {
        get { return _Color2; }
        set
        {
            _Color2 = value;
            this.Invalidate(); // Tell the Form to repaint itself
        }
    }

    public float ColorAngle
    {
        get { return _ColorAngle; }
        set
        {
            _ColorAngle = value;
            this.Invalidate(); // Tell the Form to repaint itself
        }

    }
    protected override void OnPaintBackground(PaintEventArgs pevent)
    {
        // Getting the graphics object
        Graphics g = pevent.Graphics;

        // Creating the rectangle for the gradient
        Rectangle rBackground = new Rectangle(0, 0,
                                  this.Width, this.Height);

        // Creating the lineargradient
        System.Drawing.Drawing2D.LinearGradientBrush bBackground
            = new System.Drawing.Drawing2D.LinearGradientBrush(rBackground,
                                              _Color1, _Color2, _ColorAngle);

        // Draw the gradient onto the form
        g.FillRectangle(bBackground, rBackground);

        // Disposing of the resources held by the brush
        bBackground.Dispose();
    }
}

您需要覆盖
OnPaint()
函数,并使用GDI+绘制渐变

下面几行:

protected override void OnPaint(PaintEventArgs pevent)
{
  base.OnPaint(pevent);

  pevent.Graphics.FillRectangle(new System.Drawing.Drawing2D.LinearGradientBrush(
    new PointF(0, this.Height / 2), new PointF(this.Width, this.Height / 2),
    Color.Red, Color.White), this.ClientRectangle);
}

这将从按钮的左边缘到右边缘绘制一个水平线性渐变(红色到白色)。注意,我在上面的代码中使用了常量颜色。您应该用您的属性替换它们。类似地,如果要支持渐变角度,请使用简单的数学计算渐变的起点和终点。

是否更改了按钮的“样式”属性?样式?你是说平底鞋吗?设置为标准。C#没有按钮。我添加了
winforms
标记,因为您在继承中指出了这一点;可能是因为@DanielA.White问起风格的问题。我完全不知道你用的是OnPaintBackground而不是onpaintevent。好吧,但我把OnPaintBackground写得太多了。如果我将其更改为onPaint,它确实可以工作,但会在按钮的文本和边框上方绘制。你应该在绘制背景后调用基础绘制。我不知道为什么你会被否决,将其从
OnPaintBackground
更改为
OnPaintBackground
会绘制颜色。但它会覆盖边框/文本。在之后调用onPaint似乎无法解决这个问题。啊,我明白了,除非我告诉它,否则paint不会绘制文本。@PatrickSchomburg:有关OnPaintBackground()为什么不工作的讨论,请参阅。