protected override void OnPaint(PaintEventArgs e)
{
// 创建线性渐变画刷
LinearGradientBrush brush = new LinearGradientBrush(
ClientRectangle, Color.Blue, Color.Red,
LinearGradientMode.Vertical);
// 填充窗体背景
e.Graphics.FillRectangle(brush, ClientRectangle);
base.OnPaint(e);
}
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace DisplayBoard.Method
{
public class SetBGColor
{
//设置渐变色
public static void SetGradientBackground(Form form,float circleX, float circleY, Color outSide, Color inSide)
{
// 创建 GraphicsPath 以定义椭圆的形状
GraphicsPath path = new GraphicsPath();
float x = form.ClientRectangle.Left - form.ClientRectangle.Width / 2;
float y = form.ClientRectangle.Top - form.ClientRectangle.Height * 0.3f;
float width = form.ClientRectangle.Width * 2;
float height = form.ClientRectangle.Height * 1.5f;
RectangleF rectangle = new RectangleF(//横纵坐标、宽高
x,
y,
width,
height);
path.AddEllipse(rectangle);
PathGradientBrush brush = new PathGradientBrush(path);
// 设置渐变颜色
Color[] gradientColors = new Color[]
{
outSide
};
brush.CenterColor = inSide;
// 设置中心颜色(浅色)
brush.SurroundColors = gradientColors;
// 设置中心点
PointF centerPoint = new PointF(circleX, circleY);
brush.CenterPoint = centerPoint;
// 绘制渐变背景
form.BackgroundImage = new Bitmap(form.Width, form.Height);
using (Graphics graphics = Graphics.FromImage(form.BackgroundImage))
{
graphics.FillRectangle(brush, form.ClientRectangle);
}
}
}
}
调用:
namespace DisplayBoard
{
public partial class FrmHome : Form
{
public FrmHome()
{
InitializeComponent();
DoubleBuffered = true;//启用双缓冲
SetBGColor.SetGradientBackground1(this,0,0,Color.Red,Color.Green);
}
}
}
效果:
改一下色彩中心位置
这方法会导致窗体缩放比较卡,可能是因为缩放窗体背景频繁重画,目前还不知道怎么解决。