C# 窗体渐变色

文章目录

在winform项目开发中,需要实现渐变色。本文就详细介绍如何实现。效果如下:

实现方案

利用Color类中FromArgb属性,通过for循环,修改color颜色,并使用Graphics类绘制

知识点

Color

FromArgb:

csharp 复制代码
public static System.Drawing.Color FromArgb (int red, int green, int blue);

参数:

  • red :Int32 新Color的红色分量值。 有效值为 0 到 255。
  • green Int32 新Color的绿色组件值。 有效值为 0 到 255。
  • blue Int32 新Color的蓝色分量值。 有效值为 0 到 255。

返回

Color

csharp 复制代码
Color color1 = new Color();
for(int i=0;i<=255;i++)
{
    color1.FromArgb(1,i,100);
}

SolidBrush

定义单色画笔。 画笔用于填充图形形状,如矩形、椭圆、扇形、多边形和封闭路径。 此类不能被继承。

SolidBrush(Color) 初始化指定颜色的新 SolidBrush 对象。

csharp 复制代码
Color color1 = new Color();
for(int i=0;i<=255;i++)
{
    color1.FromArgb(1,i,100);
    SolidBrush SBrush = new SolidBrush(color);//实例化一个单色画笔类对象SBrush
}

Pen

定义用于绘制直线和曲线的对象。 此类不能被继承。

Pen(Brush, Single): 用指定的 Pen 和 Color 属性初始化 Width 类的新实例。
参数

  • brush :Brush.一个 Brush,决定此 Pen 的特征。
  • width :Single。新 Pen 的宽度。
csharp 复制代码
Color color1 = new Color();
for(int i=0;i<=255;i++)
{
    color1.FromArgb(1,i,100);
    SolidBrush SBrush = new SolidBrush(color);//实例化一个单色画笔类对象SBrush
    Pen pen = new Pen(SBrush, 1);//实例化一个用于绘制直线和曲线的对象pen
}

Graphics

封装一个 GDI+ 绘图图面。 此类不能被继承。

方法

DrawRectangle:绘制由坐标对、宽度和高度指定的矩形。

DrawRectangle(Pen, Int32, Int32, Int32, Int32):绘制由坐标对、宽度和高度指定的矩形。
参数

  • pen :Pen。确定矩形的颜色、宽度和样式的 Pen。

  • x : Int32,要绘制的矩形左上角的 x 坐标。

  • y : Int32,要绘制的矩形左上角的 y 坐标。

  • width: Int32 ,要绘制的矩形的宽度。

  • height: Int32.要绘制的矩形的高度。

OnPaintBackground(PaintEventArgs)

Control.OnPaintBackground(PaintEventArgs) 方法

绘制控件的背景。

代码展示

csharp 复制代码
protected override void OnPaintBackground(PaintEventArgs e)
{
    int intLocation, intHeight;//定义两个int型的变量intLocation、intHeight 
    intLocation = this.ClientRectangle.Location.Y;//为变量intLocation赋值
    intHeight = this.ClientRectangle.Height / 200;//为变量intHeight赋值
    for (int i =255; i >= 0; i--)
    {
        Color color = new Color();//定义一个Color类型的实例color
        //为实例color赋值
        color = Color.FromArgb(1, i, 100);
        SolidBrush SBrush = new SolidBrush(color);//实例化一个单色画笔类对象SBrush
        Pen pen = new Pen(SBrush, 1);//实例化一个用于绘制直线和曲线的对象pen
        e.Graphics.DrawRectangle(pen, this.ClientRectangle.X, intLocation, this.Width, intLocation + intHeight);//绘制图形
        intLocation = intLocation + intHeight;//重新为变量intLocation赋值
    }
}
相关推荐
程序喵大人2 小时前
【C++进阶】STL算法与函数对象 - 09 函数对象保存状态并复用规则
开发语言·c++·算法·stl·函数对象
牛哇网络工作室7 小时前
UnityHDRP写实数字人全流程基础5—语音输入和语音识别
android·unity·c#·游戏引擎·aigc·语音识别·xcode
hsjiasb8 小时前
FreeRTOS学习(二十七)——任务栈与栈溢出检测
开发语言·stm32·学习·学习笔记·freertos
丰锋ff8 小时前
3.1 Qt事件之事件处理器
开发语言·qt
多弗朗皮卡丘9 小时前
C语言梦开始的地方7:函数
c语言·开发语言
月华路9 小时前
G1 垃圾回收:脏卡队列、记忆集与并发精化线程机制
java·开发语言
gugucoding9 小时前
47. 【Java】Java内存模型(JMM)与可见性
java·开发语言
m0_3807438710 小时前
从零调用 Claude 教程
开发语言·python·node.js
起床学FPGA10 小时前
AI回答问题之后,会自动跳到最下面的问题
开发语言·javascript·ecmascript
x_x-F11 小时前
网络数据从网卡到用户态:一场基于内存所有权转移的接力赛
开发语言·网络·php