添加一个panel先
private void panel7_Paint(object sender, PaintEventArgs e)
{
//LinearGradientBrush brush = new LinearGradientBrush(e.ClipRectangle, Color.Green, Color.Blue, LinearGradientMode.Vertical);
//e.Graphics.FillRectangle(brush, e.ClipRectangle);
}
或者
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
protected override void OnPaint(PaintEventArgs e)
{
const int samples = 100;
int height = 60;
int width = this.ClientRectangle.Width / samples;
for (int i = 0; i < samples; i++)
{
Color color = FromScale((double)i / samples);
Rectangle rect = new Rectangle(width * i, 0, width, height);
using (Brush brush = new SolidBrush(color))
{
e.Graphics.FillRectangle(brush, rect);
}
}
}
static Color[] colors = { Color.Blue, Color.Cyan, Color.Yellow, Color.Red };
static Color FromScale(double value)
{
if (value < 0 || value > 1) throw new ArgumentException("value must be in [0~1]");
value *= (colors.Length - 1);
int section = Math.Min((int)Math.Floor(value), colors.Length - 2);
double t = value - section;
Color c1 = colors[section], c2 = colors[section + 1];
return Color.FromArgb(
Interpolate(t, c1.R, c2.R),
Interpolate(t, c1.G, c2.G),
Interpolate(t, c1.B, c2.B)
);
}
static int Interpolate(double t, int i, int j)
{
int value = (int)(i * (1 - t) + j * t);
return Math.Min(255, Math.Max(0, value));
}
}