Click here to Skip to main content
15,867,686 members
Articles / Programming Languages / C#
Article

Simple Label Gradient

Rate me:
Please Sign up or sign in to vote.
4.59/5 (21 votes)
20 Mar 20033 min read 158.3K   5.7K   92   16
Simple Label Gradient Control

Sample Image - LabelGradient.jpg

Introduction

This article demonstartes a simple gradient label control in C#.

Making the control

Open Visual Studio.NET and create a new project. Select Class Library and enter LabelGradient for the project name then click OK. Rename the Class1.cs file in solution explorer to LabelGradient.cs, and rename the default class and the constructor to LabelGradient.

Adding project references

In Solution Explorer, select LabelGradient, right click, choose Add Reference. The Add References dialog box opens. Select the .NET tab. Scroll down and highlight the System.Windows.Forms.dll then click select. Repeat the process for System.Drawing.dll, then click OK.

Now add the following namespaces to the code to save some typing.

C#
using System.Windows.Forms;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.ComponentModel;

I' am going to base the component around the Label class. To use the Label class as my base class, I must derive from it. To do this we change the default class definition from

C#
public class LabelGradient

to

C#
public class LabelGradient : Label

Note: The icon in solution explorer will automatically change.

Declare variables

C#
protected Color gradientColorOne = Color.White;
protected Color gradientColorTwo = Color.Blue;
protected LinearGradientMode lgm = LinearGradientMode.ForwardDiagonal;
protected Border3DStyle b3dstyle = Border3DStyle.Bump;

The direction of the linear gradient, ForwardDiagonal specifies a gradient from upper left to lower right.

C#
protected LinearGradientMode lgm = LinearGradientMode.ForwardDiagonal;

Properties

Take the description in the Property Browser window, under the category of Appearance and specify the default value for the property.

C#
[DefaultValue(typeof(Color),"White"),
Description("The first gradient color."),
Category("Appearance"),
]

Now let's define our properties for GradientColorOne.

C#
//GradientColorOne Properties

public Color GradientColorOne
{
    get
    {
        return gradientColorOne;
    }
    set
    {
        gradientColorOne = value;
        Invalidate();
    }
}

The Invalidate() method invalidates the specified region of our control and causes a paint message to be sent to our control.

LinearGradientMode Properties

C#
//LinearGradientMode Properties
[
DefaultValue(typeof(LinearGradientMode),"ForwardDiagonal"),
Description("Gradient Mode"),
Category("Appearance"),
]

public LinearGradientMode GradientMode
{
    get
    {
        return lgm;
    }
    set
    {
        lgm = value;
        Invalidate();
    }
}

Border3DStyle Properties

Note the use of the new modifier keyword in

C#
new public Border3DStyle BorderStyle

This hides the BorderStyle property inherited from the base class.

To hide an inherited member, declare it in the derived class using the same name, and modify it with the new modifier.

C#
//Border3DStyle Properties
[
DefaultValue(typeof(Border3DStyle),"Bump"),
Description("BorderStyle"),
Category("Appearance"),
]
// hide BorderStyle inherited from the base class
new public Border3DStyle BorderStyle
{
    get
    {
        return b3dstyle;
    }
    set
    {
        b3dstyle = value;
        Invalidate();
    }
}

Removing Unwanted Properties

The LabelGradient class inherited the default BackColor property, which we no longer wish to use. We can shadow the default BackColor by overriding it, allowing us to hide it.

The Browsable attribute set to false specifies that the property should not be displayed in the Property Browser window.

EditorBrowsable attribute set to EditorBrowsableState.Never hides the property of the control from intelliSense.

C#
// Remove BackColor Property
[
Browsable(false),
EditorBrowsable(EditorBrowsableState.Never)
]
public override System.Drawing.Color BackColor
{
    get
    {
        return new System.Drawing.Color();
    }
    set {;}
}

Painting the control

All we need to do now is paint the control with the two gradient color's and tell it the direction of the linear gradient border style.

OnPaintBackground paints the background of the window and is guaranteed to be fast. While OnPaint paints the details and might be slower because individual paint requests are combined into one Paint event.

First we must override the OnPaintBackground method, then we create a graphics object, the PaintEventArgs specifies the graphics object used to paint the control.

C#
Rectangle rect = new Rectangle (0,0,this.Width,this.Height)

draws our rectangle and LinearGradientBrush defines our brush fill. ControlPaint.DrawBorder3D method draws a three-dimensional style border around the control.

The using statement defines a scope at the end of which an object will be disposed as long as the object implements the System.IDisposable interface, as System.Drawing.Brush does. Thanks to Richard_D for the tip on the using statement.

gfx.FillRectangle(lgb,rect) fills our rectangle with our brush fill type. When overriding OnPaintBackground in a derived class, it is not necessary to call the base class's OnPaintBackground method as with OnPaint.

protected override void 
        OnPaintBackground(System.Windows.Forms.PaintEventArgs pevent)
{
    Graphics gfx = pevent.Graphics;

    Rectangle rect = new Rectangle (0,0,this.Width,this.Height);

    // Dispose of brush resources after use
    using (LinearGradientBrush lgb = new LinearGradientBrush(rect, 
                    gradientColorOne,gradientColorTwo,lgm))
        gfx.FillRectangle(lgb,rect);

    ControlPaint.DrawBorder3D(gfx,rect,b3dstyle);
}

The Complete Code

C#
using System;
using System.Windows.Forms;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.ComponentModel;

namespace LabelGradient
{
    /// <summary>
    /// Summary description for LabelGradient.
    /// </summary>

    public class LabelGradient : Label
    {

        #region Implementtation Member Fields
        protected Color gradientColorOne = Color.White;
        protected Color gradientColorTwo = Color.Blue;
        protected LinearGradientMode lgm = 
                LinearGradientMode.ForwardDiagonal;
        protected Border3DStyle b3dstyle = Border3DStyle.Bump;
        #endregion

        #region GradientColorOne Properties
        [
        DefaultValue(typeof(Color),"White"),
        System.ComponentModel.Description("The first gradient color."),
        System.ComponentModel.Category("Appearance"),
        ]

        //GradientColorOne Properties
        public Color GradientColorOne
        {
            get
            {
                return gradientColorOne;
            }
            set
            {
                gradientColorOne = value;
                Invalidate();
            }
        }
        #endregion

        #region GradientColorTwo Properties
        [
        DefaultValue(typeof(Color),"Blue"),
        Description("The second gradient color."),
        Category("Appearance"),
        ]

        //GradientColorTwo Properties
        public Color GradientColorTwo
        {
            get
            {
                return gradientColorTwo;
            }
            set
            {
                gradientColorTwo = value;
                Invalidate();
            }
        }

        #endregion

        #region LinearGradientMode Properties
        //LinearGradientMode Properties
        [
        DefaultValue(typeof(LinearGradientMode),"ForwardDiagonal"),
        Description("Gradient Mode"),
        Category("Appearance"),
        ]

        public LinearGradientMode GradientMode
        {
            get
            {
                return lgm;
            }

            set
            {
                lgm = value;
                Invalidate();
            }
        }
        #endregion

        #region Border3DStyle Properties
        //Border3DStyle Properties
        [
        DefaultValue(typeof(Border3DStyle),"Bump"),
        Description("BorderStyle"),
        Category("Appearance"),
        ]

        // hide BorderStyle inherited from the base class
        new public Border3DStyle BorderStyle
        {
            get
            {
                return b3dstyle;
            }
            set
            {
                b3dstyle = value;
                Invalidate();
            }
        }
        #endregion

        #region Removed Properties

        // Remove BackColor Property
        [
        Browsable(false),
        EditorBrowsable(EditorBrowsableState.Never)
        ]
        public override System.Drawing.Color BackColor
        {
            get
            {
                return new System.Drawing.Color();
            }
            set {;}
        }

        #endregion

        public LabelGradient()
        {
            //
            // TODO: Add constructor logic here
            //
        }

        protected override void 
            OnPaintBackground(System.Windows.Forms.PaintEventArgs pevent)
        {
            Graphics gfx = pevent.Graphics;

            Rectangle rect = new Rectangle (0,0,this.Width,this.Height);

            // Dispose of brush resources after use
            using (LinearGradientBrush lgb = new 
                LinearGradientBrush(rect, 
                    gradientColorOne,gradientColorTwo,lgm))

                gfx.FillRectangle(lgb,rect);

            ControlPaint.DrawBorder3D(gfx,rect,b3dstyle);
        }
    }
}

Testing the control

Right click on solution explorer and select Add New Project, the add new project dialog appears. Enter Demo for the name and click OK. Now drag the LabelGradient from the toolbox onto the form. Right click Demo in solution explorer and select Set as startup project. Now click Build solution from the build menu.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
United Kingdom United Kingdom
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionGreat Tool! Pin
Member 1130758130-Jan-15 21:07
Member 1130758130-Jan-15 21:07 
QuestionNeed license details - Would like to use this code in my application. Pin
James Gopinath8-Jul-14 0:31
James Gopinath8-Jul-14 0:31 
GeneralMy vote of 5 Pin
Pasan Eeriyagama3-Apr-13 18:10
Pasan Eeriyagama3-Apr-13 18:10 
Generalthanks it's nice code Pin
Aarti Meswania1-Nov-12 23:29
Aarti Meswania1-Nov-12 23:29 
GeneralMy vote of 4 Pin
DevilVikas31-Aug-12 16:04
DevilVikas31-Aug-12 16:04 
QuestionUse in commercial app? Pin
Joseph Wee6-Jan-08 18:56
Joseph Wee6-Jan-08 18:56 
General3-color gradients Pin
ssepan25-Feb-07 7:32
ssepan25-Feb-07 7:32 
GeneralRe: 3-color gradients Pin
ssepan25-Feb-07 7:38
ssepan25-Feb-07 7:38 
Questioncan u help me fix this problem? Pin
gyokusei29-Apr-05 17:44
gyokusei29-Apr-05 17:44 
GeneraliNot Firing OnPaintBackground Pin
Tony James Jarvis1-May-04 23:38
Tony James Jarvis1-May-04 23:38 
GeneralRe: iNot Firing OnPaintBackground Pin
mazzoo14-Nov-04 23:06
mazzoo14-Nov-04 23:06 
GeneralLooks great, but... Pin
Michael Russell11-Jan-04 9:15
Michael Russell11-Jan-04 9:15 
GeneralTwo thumbs up Pin
the_warlord31-Dec-02 6:37
the_warlord31-Dec-02 6:37 
GeneralRe: Two thumbs up Pin
Dion Heskett1-Jan-03 0:33
Dion Heskett1-Jan-03 0:33 
GeneralNice work! Pin
Richard Deeming28-Oct-02 0:37
mveRichard Deeming28-Oct-02 0:37 
GeneralRe: Nice work! Pin
Dion Heskett28-Oct-02 2:00
Dion Heskett28-Oct-02 2:00 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.