Click here to Skip to main content
15,867,771 members
Articles / Desktop Programming / Windows Forms
Article

How to Use Transparent Images and Labels in Windows Forms

Rate me:
Please Sign up or sign in to vote.
4.61/5 (33 votes)
8 Apr 2008CPOL4 min read 306.8K   12.2K   119   32
The controls in Windows Forms (.NET) don't support true transparency. In this article, we show how to use transparent labels and images.
Image 1

Introduction - No Transparency in Windows Forms!

If you've tried to work with more complex forms that include images and labels, you probably found out that Windows Forms doesn't support true transparency. You're probably tearing your hair out - but don't sweat!

Even if you use the Transparent value for a control's BackColor you won't get transparency. What really happens is that the control will actually render its parent's background. This behaviour is visible on the following picture.

No_Transparency.gif

In this article, we will show you a simple way to get labels with pictures as background and also how you can use images and text with correct transparency.

How To Make Transparent Labels

Using a picture for background and labels or text in the foreground with real transparency can actually be achieved quite easily. In this chapter, we will show how to make a label's background transparent.

There are two ways which you can use to get a label to handle transparency correctly with an image as background (there are actually more ways to do this, but we're only going to talk about the more straightforward ones):

  1. By setting a Panel's BackgroundImage property and putting the Label(s) inside it
  2. By parenting the PictureBox to the Label (label.Parent = pictureBox;)

We will approach the first solution, which doesn't require any code and we can see the result right away in the designer.

Setting_Transparent_Label.gif

First, start by dragging a Panel to your form. Now set the BackgroundImage property to the image that you would like to see as the background (you can use the BackgroundImageLayout to control its behaviour).

Finally, add a Label and set the BackColor property to Transparent (the first option in the Web tab). The final result should be similar to the following image.

Transparent_Label.gif

This allows us to use labels with transparency, but the images are still broken (no transparency between them)! Don't worry, in the next chapter we will discuss a solution to use images with real transparency.

Using GDI+ for Drawing Images with Transparency

Drawing images with correct transparency is a little more tricky, because we can't use the default controls that come with Windows Forms and .NET.

For more complex image and graphics manipulation, we can use GDI+, which stands for Graphics Device Interface (it can be found in the System.Drawing namespace).

What we'll do is create a generic control that we can then arbitrarily inherit to draw images and text. This can be found in the project's source code, but if you want to understand how it works, then read on.

Generic Control for Drawing Images

Start by creating a new class which inherits from Panel. Lets call it DrawingArea. This class will have an abstract OnDraw method which will be overridden by its subclasses, so we also need to declare the class as abstract.

Also, we'll add a Graphics object where all the drawing will take place. You should have something like this:

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

/// <summary>
/// Use this for drawing custom graphics and text with transparency.
/// Inherit from DrawingArea and override the OnDraw method.
/// </summary>
abstract public class DrawingArea : Panel
{
    /// <summary>
    /// Drawing surface where graphics should be drawn.
    /// Use this member in the OnDraw method.
    /// </summary>
    protected Graphics graphics;

    /// <summary>
    /// Override this method in subclasses for drawing purposes.
    /// </summary>
    abstract protected void OnDraw();
} 

We need to make sure our control's background transparency will be correctly handled. For this, we override the CreateParams property to make sure the correct style is included when the control is instantiated (thanks to Bob Powell for this tip).

C#
protected override CreateParams CreateParams
{
    get
    {
        CreateParams cp = base.CreateParams;
        cp.ExStyle |= 0x00000020; //WS_EX_TRANSPARENT

        return cp;
    }
}

Now, only two more things are needed. First we must make sure that the background doesn't get drawn. We do this by overriding the OnPaintBackground method with nothing in it.

The second thing that's needed is to override the OnPaint method. This allows us to define the procedure that will be called when it's time for the control to paint itself.

C#
protected override void OnPaintBackground(PaintEventArgs pevent)
{
    // Don't paint background
}

protected override void OnPaint(PaintEventArgs e)
{
    // Update the private member so we can use it in the OnDraw method
    this.graphics = e.Graphics;

    // Set the best settings possible (quality-wise)
    this.graphics.TextRenderingHint =
        System.Drawing.Text.TextRenderingHint.AntiAlias;
    this.graphics.InterpolationMode =
        System.Drawing.Drawing2D.InterpolationMode.HighQualityBilinear;
    this.graphics.PixelOffsetMode =
        System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;
    this.graphics.SmoothingMode =
        System.Drawing.Drawing2D.SmoothingMode.HighQuality;

    // Calls the OnDraw subclass method
    OnDraw();
}

I also defined a DrawText method and some variations so it would be easy to write text. It's a little lengthy so I'll leave it off the tutorial, but you can find it in the project's source code.

Using the Control to Draw Images and Text with Transparency

Now, how do we use this control? We need to make a new class and inherit from DrawingArea. This is very simple and easy to do. Here I provide an example:

C#
class BroculosDrawing : DrawingArea
{
    protected override void OnDraw()
    {
        // Gets the image from the global resources
        Image broculoImage = global::WindowsApplication1.Properties.Resources.broculo;

        // Sets the images' sizes and positions
        int width = broculoImage.Size.Width;
        int height = broculoImage.Size.Height;
        Rectangle big = new Rectangle(0, 0, width, height);
        Rectangle small = new Rectangle(50, 50, (int)(0.75 * width), 
                (int)(0.75 * height));

        // Draws the two images
        this.graphics.DrawImage(broculoImage, big);
        this.graphics.DrawImage(broculoImage, small);

        // Sets the text's font and style and draws it
        float fontSize = 8.25f;
        Point textPosition = new Point(50, 100);
        DrawText("http://www.broculos.net", "Microsoft Sans Serif", fontSize
            , FontStyle.Underline, Brushes.Blue, textPosition);
    }
} 

This will draw two images and text (similar to the previous ones), but now with true transparency!

We can use this control like a normal one. Compile the solution. Create a new form. The new control should appear in the toolbox. Drag it to the form and voila! You can see the outcome in the following image:

Images_Text_Full_Transparency.gif

Conclusion

Now you know how to draw images with transparency. The big drawback is that it isn't as easy to use as .NET built-in Windows Forms controls. The default controls are very limited for more advanced image usage and manipulation, so we used GDI+ to overcome this.

With this knowledge and a little more work, it should be possible to make a TransparentPictureBox. Hope you found it useful.

Resources

History

  • 8th April, 2008: Initial post

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Web Developer
Portugal Portugal
Find more of my tutorials at Broculos.net.

Comments and Discussions

 
QuestionHow do you add an Image property to the control? Pin
Marie Iv3-Mar-22 1:04
Marie Iv3-Mar-22 1:04 
Questionhere is a much easier way, haha Pin
Member 1168328430-Mar-18 2:32
Member 1168328430-Mar-18 2:32 
AnswerRe: here is a much easier way, haha Pin
tarco6-Jul-23 12:45
professionaltarco6-Jul-23 12:45 
AnswerRe: here is a much easier way, haha Pin
Jek Alviar26-Sep-23 15:17
Jek Alviar26-Sep-23 15:17 
QuestionExcellent Pin
Kristian Sogaard5-Mar-17 10:59
Kristian Sogaard5-Mar-17 10:59 
GeneralTeşekkürler :) Pin
Member 1144929722-Jan-16 1:04
Member 1144929722-Jan-16 1:04 
QuestionHow to "animate" images in the panel? Pin
Vlad Katkov16-Sep-14 9:26
Vlad Katkov16-Sep-14 9:26 
Questionthank you bhai Pin
Member 1031296520-Dec-13 1:01
Member 1031296520-Dec-13 1:01 
QuestionHow the "broculo" component added into toolbox? Pin
YDLU5-Jun-13 4:55
YDLU5-Jun-13 4:55 
AnswerRe: How the "broculo" component added into toolbox? Pin
Nuno Freitas5-Jun-13 5:25
Nuno Freitas5-Jun-13 5:25 
GeneralThanks! Pin
XHUNTYX24-Apr-12 8:56
XHUNTYX24-Apr-12 8:56 
GeneralRe: Thanks! Pin
Nuno Freitas24-Apr-12 9:31
Nuno Freitas24-Apr-12 9:31 
GeneralTransparent Images Pin
PRMan!!!4-Aug-10 15:28
PRMan!!!4-Aug-10 15:28 
Jokethank you~ Pin
yuhua112-Dec-09 18:28
yuhua112-Dec-09 18:28 
GeneralRe: thank you~ Pin
Nor Sal31-Aug-11 6:08
Nor Sal31-Aug-11 6:08 
GeneralCalling Graphics.Clear() before drawing images Pin
remarkpk116-Aug-08 23:16
remarkpk116-Aug-08 23:16 
GeneralRe: Calling Graphics.Clear() before drawing images Pin
Nuno Freitas7-Aug-08 22:45
Nuno Freitas7-Aug-08 22:45 
GeneralRe: Calling Graphics.Clear() before drawing images Pin
remarkpk117-Aug-08 23:13
remarkpk117-Aug-08 23:13 
GeneralRe: Calling Graphics.Clear() before drawing images Pin
Nuno Freitas8-Aug-08 0:01
Nuno Freitas8-Aug-08 0:01 
GeneralThis is just wrong :P Pin
nopecio26-Jun-08 11:19
nopecio26-Jun-08 11:19 
GeneralRe: This is just wrong :P Pin
Nuno Freitas26-Jun-08 11:38
Nuno Freitas26-Jun-08 11:38 
GeneralGood article Pin
J Sullivan29-Apr-08 17:11
J Sullivan29-Apr-08 17:11 
QuestionHow do i add the drog event for broculo? Pin
kyyang17-Apr-08 23:24
kyyang17-Apr-08 23:24 
GeneralRe: How do i add the drog event for broculo? Pin
Nuno Freitas18-Apr-08 0:44
Nuno Freitas18-Apr-08 0:44 
GeneralNIce work! Pin
Nuri Ismail15-Apr-08 11:11
Nuri Ismail15-Apr-08 11:11 

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.