C#winform窗体背景渐变色

发布时间:2023年12月26日
  1. 从一个方向到另一个方向的渐变色,例如从左到右,从左上到右下,在窗体代码中添加如下代码,改一下颜色和渐变方向即可
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);
}
  1. 以某一点为圆心的渐变色,这是我用的方法的原理
    在这里插入图片描述
    代码如下:
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);
        }
    }
}

效果:
在这里插入图片描述
改一下色彩中心位置
在这里插入图片描述
在这里插入图片描述
这方法会导致窗体缩放比较卡,可能是因为缩放窗体背景频繁重画,目前还不知道怎么解决。

文章来源:https://blog.csdn.net/NJJML/article/details/135217093
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。