In this article we explore GDI+ drawing operations implementing opacity, also known as alpha blending.
Sample source code
This article is accompanied by a sample source code Visual Studio project which is available for download here
Using the Sample Application
The following image is a screenshot of the included sample application:
The screenshot illustrates drawing text and a rectangle onto a Windows Form in Color.SteelBlue with an alpha component of 100.
In C# it is possible and relatively easy to draw text and two dimensional shapes in GDI+ that support a level of opacity or transparency. The well known abbreviation RGB abbreviates the term Red, Green and Blue. C# supports RGB colours but also what is known as ARGB colours. In the case of ARGB the A abbreviates the word Alpha, in other words an RGB colour with a specified alpha component.
An alpha component specifies a colour’s opacity or transparency. Possible values range from 0 to 255 inclusive, where 0 would represent full transparency and 255 no level of transparency. If a byte consists of 8 bits and an ARGB colour is composed of 4 components ranging from 0 to 255 each representing a byte or 8 bits, then an ARGB colour is therefore a 32 bit colour.
The Color structure
The Paint Event Handler
The bulk of this example’s functionality occurs within the main Form’s Paint event handler, as detailed by the following code snippet:
The main Form defines two member variables used in the paint event handler:
In the paint event handler an instance of the Color structure is created implementing an alpha component defined by the form’s member variable. The Color object declaration is followed by an ARGB Color Pen and SolidBrush declaration.