在程序设计时,可以通过设置窗体的BackColor属性来改变窗口的背景颜色。但是这个属性改变后整个窗体的客户区都会变成这种颜色,并且非常单调。如果窗体的客户区可以向标题栏一样能够体现颜色的渐变效果,那么窗体风格将会另有一番风味。
C#中可以通过Color.FromArgb( )方法返回一种颜色,下面详细介绍一下该方法。
Color.FromArgb( )方法用来返回Color的颜色值,该方法语法结构如下:
public static Color FromArgb (
int red,
int green,
int blue
)
参数说明如下。
l red:新Color的红色分量值。有效值为从0~255。
l green:新Color的绿色分量值。有效值为从0~255。
l blue:新Color的蓝色分量值。有效值为从0~255。
l 返回值:此方法创建的Color。
该函数就是用3种不同的色值来返回一个颜色,而稍微的调整某一种颜色值就可以使整体的颜色发生细微的变化,在窗体中至上而下每行填充一种稍微调整后的颜色,这样整体看来就会产生渐变的效果。可以利用窗体的Graphics对象对窗体进行绘图,该对象可以完全操控窗体的客户区。
注意:颜色值在0~255之间。
实现过程
(1)创建一个项目,将其命名为Ex01_30,默认窗体为Form1。
(2)在Form1窗体中添加Button用来使颜色渐变;添加TextBox控件用来输入颜色RGB值。
(3)主要程序代码。
触发重新绘制事件的实现代码如下:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
this.Hide();
this.Visible = true;
}
protected override void OnPaintBackground(PaintEventArgs e)
{
//void OnPaintBackground(PaintEventArgs e)
int y, dy;
y = this.ClientRectangle.Location.Y;
dy = this.ClientRectangle.Height / 256;
for (int i = 255; i >= 0; i--)
{
Color c = new Color();
c = Color.FromArgb(Convert.ToInt32(textBox1.Text), i,Convert.ToInt32(textBox2.Text));
SolidBrush sb = new SolidBrush(c);
Pen p = new Pen(sb, 1);
e.Graphics.DrawRectangle(p, this.ClientRectangle.X, y, this.Width, y + dy);
y = y + dy;
}
}
}
}
效果图如下: