C# 如何在渐变背景面板上设置标签背景色

C# 如何在渐变背景面板上设置标签背景色,c#,label,panel,C#,Label,Panel,面板控件的背景色设置为颜色渐变 我想设置相同的面板背景颜色和标签包颜色 我的代码如下所示 private void panel1_Paint(object sender, PaintEventArgs e) { Graphics g = panel1.CreateGraphics(); LinearGradientBrush lgb = new LinearGradientBrush(new Rectangle(0, 0, this

面板控件的背景色设置为颜色渐变

我想设置相同的面板背景颜色和标签包颜色

我的代码如下所示

private void panel1_Paint(object sender, PaintEventArgs e)
        {
            Graphics g = panel1.CreateGraphics();
            LinearGradientBrush lgb = new LinearGradientBrush(new Rectangle(0, 0, this.panel1.Width, this.panel1.Height), Color.Black, Color.Black, LinearGradientMode.Horizontal);
            ColorBlend cb = new ColorBlend();
            cb.Colors = new Color[] { Color.Black, Color.White };
            cb.Positions = new Single[] { 0.0F, 1.0F };
            lgb.InterpolationColors = cb;

            g.FillRectangle(lgb, new Rectangle(0, 0, this.panel1.Width, this.panel1.Height));
            label1.Parent = panel1;
            label1.BackColor = Color.Transparent;
            lgb.Dispose();
            g.Dispose();

        }

哪个部分出错?

下面的行有问题:

Graphics g = panel1.CreateGraphics();
将其更改为:

Graphics g = e.Graphics;
您还可以将以下代码放入构造函数中(以避免在面板失效时重新指定):

label1.Parent = panel1;
label1.BackColor = Color.Transparent;