我试图通过扩展 System.Windows.Forms.button 类在 c# 中添加渐变。我遇到的问题是它不会在设计或运行时向按钮添加渐变,尽管设计器确实选择了颜色 1、颜色 2 和角度字段,因此它肯定会被正确覆盖和实例化。我错过了什么吗?
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);
}
这将从按钮的左边缘到右边缘绘制一个水平线性渐变(红色到白色)。请注意,我在上面的代码中使用了常量颜色。你应该用你的属性替换它们。同样,如果您想支持渐变角度,请使用简单的数学运算来计算渐变的起点和终点。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句