如何按照附图所示设置表单的背景颜色?
一种方法是直接将图像作为表单的BackgroundImage
使用。
如果想要实现更加灵活的途径,可以使用OnPaintBackground
手动绘制表单的背景:
protected override void OnPaintBackground(PaintEventArgs e)
{
using (var brush = new LinearGradientBrush
(DisplayRectangle, Color.Black, Color.DarkGray, LinearGradientMode.Vertical))
{
e.Graphics.FillRectangle(brush, DisplayRectangle);
}
}
protected override void OnResize(EventArgs e)
{
base.OnResize(e);
Invalidate(); // Force repainting on resize
}
结果:
winform
的OnPaint事件
进行修改。查看以下链接以了解更多详细信息。LinearGradientBrush
进行如下操作:LinearGradientBrush brush = new LinearGradientBrush(rect, Color.Orange, Color.Orchid, LinearGradientMode.ForwardDiagonal);
OnPaint重载的代码片段:
Protected Overrides Sub OnPaint(ByVal e As System.Windows.Forms.PaintEventArgs)
' Declare a variable of type Graphics named formGraphics.
' Assign the address (reference) of this forms Graphics object
' to the formGraphics variable.
Dim formGraphics As Graphics = e.Graphics
' Declare a variable of type LinearGradientBrush named gradientBrush.
' Use a LinearGradientBrush constructor to create a new LinearGradientBrush object.
' Assign the address (reference) of the new object
' to the gradientBrush variable.
Dim gradientBrush As New LinearGradientBrush(New Point(0, 0), New Point(Width, 0), Color.White, Color.DarkMagenta)
' Here are two more examples that create different gradients.
' Comment the Dim statement immediately above and uncomment one of these
' Dim statements to see how varying the two colors changes the gradient result.
' Dim gradientBrush As New LinearGradientBrush(New Point(0, 0), New Point(Width, 0), Color.Chartreuse, Color.SteelBlue)
' Dim gradientBrush As New LinearGradientBrush(New Point(0, 0), New Point(Width, 0), Color.White, Color.SteelBlue)
formGraphics.FillRectangle(gradientBrush, ClientRectangle)
End Sub
另一种方法是使用OnPaintBackground
事件并使用LinearGradientBrush
参考:MSDN
protected override void OnPaintBackground(PaintEventArgs e) {
Rectangle rc = new Rectangle(0, 0, this.ClientSize.Width, this.ClientSize.Height);
using (LinearGradientBrush brush = new LinearGradientBrush(rc, Color.Red, Color.Blue, 45F)) {
e.Graphics.FillRectangle(brush, rc);
}
参考资料:
如何在VB.NET和VB2005中为窗体添加渐变背景
Windows Forms 2.0-绘制美丽的渐变背景
使用C#将渐变/阴影背景设置为Windows窗体
在此处检查与Resize
相关的信息:
this.Invalidate()
-
在您的窗体或控件上创建渐变背景
还可以查看这个SO线程.. VB.NET渐变填充表单上的透明控件背景?