我试图通过扩展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();
}
}
答案 0 :(得分:-1)
您需要覆盖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);
}
这将从按钮的左边缘到右边缘绘制水平线性渐变(红色到白色)。请注意,我在上面的代码中使用了常量颜色。您应该用您的属性替换它们。同样,如果要支持渐变角度,请使用简单的数学计算渐变的起点和终点。