Search code examples
c#winformscustom-controlspaint

Draw Gradient Label


Is it possible to apply a gradient to label text?

Right now I am taking over a controls OnPaint and drawing the string of text that I want; however, this is to specific. I really want to make it so that the label itself gets applied the gradient colors I want. So in turn each character would have the gradient specified as the text has changed.

So instead of using the ForeColor I would apply a LinearGradientBrush. I am using WinForms at the moment.

EDIT 1

Here is the code that I am currently using. However, this only applies the gradient to all of the characters. I would like to change it so that each character in the string is applied.

// Draw the formatted text string to the DrawingContext of the control.
Font font = new Font("BankGothic Md BT", 48f, FontStyle.Bold);
LinearGradientBrush brush = new LinearGradientBrush(label1.Location, new Point(label1.Width, label1.Height), Color.Goldenrod, Color.Black);
e.Graphics.DrawString(label1.Text, font, brush, 0,0);

Edit 2

Here is what I did. I just extended the Label class and inherited OnPaint.

public partial class LabelEx : Label {
    public LabelEx() {
        InitializeComponent();
    }

    protected override void OnPaint(PaintEventArgs e) {
        // Draw the formatted text string to the DrawingContext of the control.
        //base.OnPaint(e);
        Font font = new Font("Tahoma", 48f, FontStyle.Bold);
        LinearGradientBrush brush = new LinearGradientBrush(new Rectangle(0, 0, Width, Height + 5), Color.Gold, Color.Black, LinearGradientMode.Vertical);
        e.Graphics.DrawString(Text, font, brush, 0, 0);

    }
}

Which gives me a nice gradient text label.

Thanks!


Solution

  • Here is what I did. I just extended the Label class and inherited OnPaint.

    public partial class LabelEx : Label {
    
    public LabelEx() {
        InitializeComponent();
    }
    
    protected override void OnPaint(PaintEventArgs e) {
        // Draw the formatted text string to the DrawingContext of the control.
        //base.OnPaint(e);
        Font font = new Font("Tahoma", 48f, FontStyle.Bold);
        LinearGradientBrush brush = new LinearGradientBrush(new Rectangle(0, 0, Width, Height + 5), Color.Gold, Color.Black, LinearGradientMode.Vertical);
        e.Graphics.DrawString(Text, font, brush, 0, 0);
    
    }
    
    }