前言
在窗体设计时,可以通过设置窗体的backcolor属性来改变窗口的背景颜色,但是该属性改变后整个窗体的客户区都会变成这种颜色,这样显得非常单调。如果窗体的客户区可以像标题栏一样能够体现颜色的渐变效果,那么窗体风格将会另有一番风味。
1.让背景渐变色的理论基础
在实现窗体背景色渐变功能时主要用到了color结构的fromargb方法,color结构表示一种argb颜色(alpha、红色、绿色和蓝色),其fromargb方法用来从指定的8位颜色值(红色、绿色和蓝色)创建color结构,该方法为可重载方法,其最常用的语法格式如下:
publie static color fromargb(int red,int green,int blue)
fromargb方法中的参数说明如表:
参 数 | 说 明 |
red | 新color的红色分量值,有效值为0~255 |
green | 新color的绿色分量值,有效值为0~255 |
blue | 新color的蓝色分量值,有效值为0~255 |
返回值 | 创建的color结构 |
2.让背景渐变色的方法
fromargb方法就是用3种不同的色值来返回一个颜色,而稍微调整某一种颜色值就可以使整体的颜色发生细微的变化,在窗体中至上而下每行填充一种稍微调整后的颜色,这样整体看来就会产生渐变的效果。可以利用窗体的graphics对象对窗体进行绘图,该对象可以完全操控窗体的客户区。
3.一个实施例
生成渐变的蓝色背景。
(1)form1.designer.cs
namespace _184
{
partial class form1
{
/// <summary>
/// required designer variable.
/// </summary>
private system.componentmodel.icontainer components = null;
/// <summary>
/// clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void dispose(bool disposing)
{
if (disposing && (components != null))
{
components.dispose();
}
base.dispose(disposing);
}
#region windows form designer generated code
/// <summary>
/// required method for designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void initializecomponent()
{
suspendlayout();
//
// form1
//
autoscaledimensions = new sizef(7f, 17f);
autoscalemode = autoscalemode.font;
clientsize = new size(368, 252);
name = "form1";
startposition = formstartposition.centerscreen;
text = "窗体背景渐变色";
resumelayout(false);
}
#endregion
}
}(2)form1.cs
// 窗体渐变色
namespace _184
{
public partial class form1 : form
{
public form1()
{
initializecomponent();
}
/// <summary>
/// 重写窗体背景色
/// </summary>
protected override void onpaintbackground(painteventargs e)
{
int intlocation, intheight;
intlocation = clientrectangle.location.y;//为变量intlocation赋值
intheight = clientrectangle.height / 200;//为变量intheight赋值
for (int i = 255; i >= 0; i--)
{
color color = color.fromargb(1, i, 100);
solidbrush sbrush = new(color); //实例化一个单色画笔类对象sbrush
pen pen = new(sbrush, 1); //实例化一个用于绘制直线和曲线的对象pen
e.graphics.drawrectangle(pen, clientrectangle.x, intlocation, width, intlocation + intheight);//绘制图形
intlocation += intheight; //重新为变量intlocation赋值
}
}
}
}(3)渐变的蓝色背景

到此这篇关于c#创建背景色渐变窗体的方法实例的文章就介绍到这了,更多相关c#创建背景色渐变窗体内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论