重写Labeld控件实现渐变背景 - (第十二讲)
视频讲解如下:
网盘下载,提取码:pt2b
https://pan.baidu.com/s/1C2ri-X89szdMtxfgc-feGg
这里给大家讲解一下如何重写Labeld控件实现渐变背景
重写控件后的效果如下:

using System.Drawing;
using System.Drawing.Drawing2D;
using System.Windows.Forms;
namespace WindowsFormsApp
{
public class MyLabel : Label
{
/// <summary>
/// 默认颜色
/// </summary>
public Color DefaultColor { get; set; } = Color.FromArgb(142, 207, 247);
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
//画个渐变的矩形,大小跟Label1一样大。
e.Graphics.FillRectangle(new LinearGradientBrush(e.ClipRectangle,
Color.White, DefaultColor, LinearGradientMode.Vertical), e.ClipRectangle);
//写字,居中,Font用Label1
this.BorderStyle = BorderStyle.None;
StringFormat stringFormat = new StringFormat();
stringFormat.Alignment = StringAlignment.Center;
stringFormat.LineAlignment = StringAlignment.Center;
Brush brush = new SolidBrush(this.ForeColor);
e.Graphics.DrawString(this.Text, this.Font, brush, e.ClipRectangle, stringFormat);
}
}
}