如何在渐变背景面板上设置标签backColor

时间:2015-08-11 01:59:48

标签: c# label panel

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

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

我的代码如下

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();

        }

哪一部分错了?

1 个答案:

答案 0 :(得分:2)

以下行存在问题:

Graphics g = panel1.CreateGraphics();

将其更改为:

Graphics g = e.Graphics;

您还可以在构造函数中放入以下代码(以避免在面板为Invalidated时重新分配):

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