Alpha Blending
In GDI+, every color is a combination of ARGB components; each of the alpha, red, green, and blue components is represented by 8 bits. The alpha component in a color structure represents the transparency of the color, which varies from 0 to 255. The value 0 represents full transparency, and 255 represents full opacity.
The final color of an ARGB color structure is calculated by the following formula:
Final Color = (Source Color x alpha / 255) +
[Background Color x (255 alpha) / 255]
This formula is applied on each component of the source color and background color.
In alpha blending, an application creates a color with an alpha component and uses this color to create a pen or a brush. This pen or brush is used to draw and fill graphics shapes, and it calculates the final color. Alpha blending may sound unfamiliar, but programmatically it is simply a method of setting the alpha component (transparency) of a color, and using it to fill and draw graphics shapes.
9.6.1 Brushes, Pens, and Alpha Blending
The process of alpha blending involves three simple steps. First an application creates a color with transparency (the alpha component). The following line creates a Color object with alpha component value 40:
Color clr = Color.FromArgb(40, 255, 255, 255);
The second step is to create a brush or pen using that color. The following lines create a transparent pen and a brush:
Pen transPen = new Pen(clr, 10); SolidBrush semiTransBrush = new SolidBrush(clr);
Finally, the application uses the transparent brush or pen to fill and draw graphics shapes, lines, and curves. The following code uses the Pen and Brush objects we created in the previous steps to draw a line and to draw and fill a rectangle:
g.DrawLine(transPen, 10, 30, 200, 30); g.FillRectangle(semiTransBrush, rect);
Listing 9.31 uses this approach to draw lines, a rectangle, an ellipse, and text objects with varying transparency. You can add this code to a menu item or a button click event handler.
Listing 9.31 Using alpha blending to draw non-opaque or semi-opaque graphics shapes
private void AlphaBPensBrushes_Click(object sender, System.EventArgs e) { Graphics g = this.CreateGraphics(); g.Clear(this.BackColor); // Create pens with semitransparent colors Rectangle rect = new Rectangle(220, 30, 100, 50); Pen transPen = new Pen(Color.FromArgb(128, 255, 255, 255), 10); Pen totTransPen = new Pen(Color.FromArgb(40, 0, 255, 0), 10); // Draw line, rectangle, ellipse, and string using // semitransparent colored pens g.DrawLine(transPen, 10, 30, 200, 30); g.DrawLine(totTransPen, 10, 50, 200, 50); g.FillRectangle(new SolidBrush( Color.FromArgb(40, 0, 0, 255)), rect); rect.Y += 60; g.FillEllipse(new SolidBrush( Color.FromArgb(20, 255, 255, 0)), rect); SolidBrush semiTransBrush = new SolidBrush(Color.FromArgb(90, 0, 50, 255)); g.DrawString("Some Photo Date: 04/09/2001", new Font("Verdana", 14), semiTransBrush, new RectangleF(20, 100, 300, 100) ); // Dispose of object g.Dispose(); }
Figure 9.42 shows the output from Listing 9.31. The lines, rectangle, ellipse, and text on this form are semitransparent.
Figure 9.42. Drawing semitransparent graphics shapes
9.6.2 Alpha Blending and Images
We often see a semitransparent date and place name on a photo. You can draw transparent graphics shapes on images using the same method: Create a graphics shape using semi- or non-opaque colors, and then draw on the image.
Listing 9.32 draws graphics shapes on an image. First we create an Image object and call DrawImage to draw an image. Then we create transparent pens and brushes and call fill and draw methods to draw graphics shapes. You can add the code in Listing 9.32 to any menu item or button click event handler.
Listing 9.32 Drawing semitransparent graphics shapes on an image
private void AlphaBImages_Click(object sender, System.EventArgs e) { Graphics g = this.CreateGraphics(); g.Clear(this.BackColor); // Draw an image Image curImage = Image.FromFile("Neel3.jpg"); g.DrawImage(curImage, 0, 0, curImage.Width, curImage.Height); // Create pens and a rectangle Rectangle rect = new Rectangle(220, 30, 100, 50); Pen opqPen = new Pen(Color.FromArgb(255, 0, 255, 0), 10); Pen transPen = new Pen(Color.FromArgb(128, 255, 255, 255), 10); Pen totTransPen = new Pen(Color.FromArgb(40, 0, 255, 0), 10); // Draw lines, rectangle, ellipse, and string g.DrawLine(opqPen, 10, 10, 200, 10); g.DrawLine(transPen, 10, 30, 200, 30); g.DrawLine(totTransPen, 10, 50, 200, 50); g.FillRectangle(new SolidBrush( Color.FromArgb(140, 0, 0, 255)), rect); rect.Y += 60; g.FillEllipse(new SolidBrush( Color.FromArgb(150, 255, 255, 255)), rect); SolidBrush semiTransBrush = new SolidBrush(Color.FromArgb(90, 255, 255, 50)); g.DrawString("Some Photo Date: 04/09/2001", new Font("Verdana", 14), semiTransBrush, new RectangleF(20, 100, 300, 100) ); // Dispose of object g.Dispose(); }
Figure 9.43 shows the output from Listing 9.32. Lines, text, a rectangle, and an ellipse are drawn on top of the image, but you can see through them because these shapes are semitransparent.
Figure 9.43. Drawing semitransparent shapes on an image
9.6.3 Compositing Mode and Blending
As mentioned earlier, blending is a process of combining two colors: a source color and a background color. The compositing mode specifies how source colors are combined with background colors.
The CompositingMode property of the Graphics class represents the compositing mode of a graphics surface, which applies to all graphics shapes for that surface. The CompositingMode enumeration has two members: SourceCopy and SourceOver. SourceCopy specifies that when a color is rendered, it overwrites the background color, and SourceOver specifies that when a color is rendered, it is blended with the background color using the alpha component.
The following code snippet shows how to set the CompositingMode property of a Graphics object.
Graphics g = this.CreateGraphics(); g.Clear(this.BackColor); g.CompositingMode = CompositingMode.SourceCopy; g.CompositingMode = CompositingMode.SourceOver; // Dispose of object g.Dispose();
CompositingMode may be helpful in scenarios where you need to draw overlapped images. Suppose you draw one rectangle and one ellipse, and an area of the ellipse overlaps a small area of the rectangle. You may or may not want to show the overlapped area of the rectangle. The compositing mode provides you the option of doing either.
Instead of applying CompositingMode to all of the graphics, you can apply it to selected shapes. One way to do this is to create a temporary Graphics object (a new surface), draw all the shapes you need and apply the compositing mode on this object. You can also create graphics containers and apply the necessary settings to each graphics container.
The quality of compositing is inversely proportional to the rendering speed: The higher the quality, the slower the rendering. The CompositingQuality property of the Graphics object represents the quality of a composition process, which takes a value of type CompositingQuality enumeration. The CompositingQuality enumeration is defined in Table 9.12.
Listing 9.33 draws two sets of shapes. Each set has a rectangle and an ellipse. First we create a Bitmap object, and then we create a temporary Graphics object using the FromImage method by passing the Bitmap object. We set the CompositingMode property of this Graphics object to SourceOver, which means that the color rendered overwrites the background color. Then we draw a rectangle and an ellipse.
Member |
Description |
---|---|
AssumeLinear |
Assume linear values. Better than the default quality. |
Default |
Default quality. |
GammaCorrected |
Gamma correction is used. |
HighQuality |
High quality, low speed. |
HighSpeed |
High speed, low quality. |
Invalid |
Invalid quality. |
Listing 9.33 Using CompositingMode to draw graphics shapes
private void AlphaBCompGammaCorr_Click(object sender, System.EventArgs e) { Graphics g = this.CreateGraphics(); g.Clear(this.BackColor); // Create two rectangles Rectangle rect1 = new Rectangle(20, 20, 100, 100); Rectangle rect2 = new Rectangle(200, 20, 100, 100); // Create two SolidBrush objects SolidBrush redBrush = new SolidBrush(Color.FromArgb(150, 255, 0, 0)); SolidBrush greenBrush = new SolidBrush(Color.FromArgb(180, 0, 255, 0)); // Create a Bitmap object Bitmap tempBmp = new Bitmap(200, 150); // Create a Graphics object Graphics tempGraphics = Graphics.FromImage(tempBmp); // Set compositing mode and compositing // quality of Graphics object tempGraphics.CompositingMode = CompositingMode.SourceOver; tempGraphics.CompositingQuality = CompositingQuality.GammaCorrected; // Fill rectangle tempGraphics.FillRectangle(redBrush, rect1); rect1.X += 30; rect1.Y += 30; // Fill ellipse tempGraphics.FillEllipse(greenBrush, rect1); g.CompositingQuality = CompositingQuality.GammaCorrected; // Draw image g.DrawImage(tempBmp, 0, 0); // Fill rectangle g.FillRectangle(Brushes.Red, rect2); rect2.X += 30; rect2.Y += 30; // Fill ellipse g.FillEllipse(Brushes.Green, rect2); // Dispose of objects greenBrush.Dispose(); redBrush.Dispose(); tempBmp.Dispose(); g.Dispose(); }
Figure 9.44 shows the output from Listing 9.33. You can clearly see that an ellipse copies over the color of a rectangle.
Figure 9.44. Using CompositingMode.SourceOver
Now we change the value of CompositingMode to SourceCopy by using the following code snippet:
tempGraphics.CompositingMode = CompositingMode.SourceCopy;
Figure 9.45 shows the new output. The color of the rectangle and the color of ellipse do not overlap now, but the color of the rectangle is gone and that area is overridden by the ellipse.
Figure 9.45. Blending with CompositingMode.SourceCopy
9.6.4 Mixed Blending
Mixed blending is a combination of both alpha blending and color blending. It is useful when you need to draw transparent and blended graphics shapesfor example, drawing a transparent image with transparent shapes using a blended linear gradient brush.
Listing 9.34 shows how to mix these two types of blending. Using the InterpolationColors property, we create a LinearGradientBrush object and set its Colors and Positions properties to specify the blending colors and positions. After that we create a Bitmap object and apply a color matrix using SetColorMatrix. Then we draw a rectangle and an ellipse, and we call DrawImage.
Listing 9.34 Mixed blending example
private void MixedBlending_Click(object sender, System.EventArgs e) { Graphics g = this.CreateGraphics(); g.Clear(this.BackColor); // Create a LinearGradientBrush object LinearGradientBrush brBrush = new LinearGradientBrush( new Point(0, 0), new Point(50, 20), Color.Blue, Color.Red); Rectangle rect = new Rectangle(20, 20, 200, 100); // Create color and points arrays Color[] clrArray = { Color.Red, Color.Blue, Color.Green, Color.Pink, Color.Yellow, Color.DarkTurquoise }; float[] posArray = { 0.0f, 0.2f, 0.4f, 0.6f, 0.8f, 1.0f }; // Create a ColorBlend object and // set its Colors and Positions properties ColorBlend colorBlend = new ColorBlend(); colorBlend.Colors = clrArray; colorBlend.Positions = posArray; // Set InterpolationColors property brBrush.InterpolationColors = colorBlend; // Create a Bitmap object from a file Bitmap bitmap = new Bitmap("MyPhoto.jpg"); // Create a points array float[][] ptsArray = { new float[] {1, 0, 0, 0, 0}, new float[] {0, 1, 0, 0, 0}, new float[] {0, 0, 1, 0, 0}, new float[] {0, 0, 0, 0.5f, 0}, new float[] {0, 0, 0, 0, 1} }; // Create a ColorMatrix object using pts array ColorMatrix clrMatrix = new ColorMatrix(ptsArray); // Create an ImageAttributes object ImageAttributes imgAttributes = new ImageAttributes(); // Set color matrix of ImageAttributes imgAttributes.SetColorMatrix(clrMatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap); // Fill rectangle g.FillRectangle(brBrush, rect); rect.Y += 120; // Fill ellipse g.FillEllipse(brBrush, rect); // Draw image using ImageAttributes g.DrawImage(bitmap, new Rectangle(0, 0, bitmap.Width, bitmap.Height), 0, 0, bitmap.Width, bitmap.Height, GraphicsUnit.Pixel, imgAttributes); // Dispose of objects brBrush.Dispose(); bitmap.Dispose(); g.Dispose(); }
Figure 9.46 shows the output from Listing 9.34. The rectangle and ellipse are blended (multicolor) and translucent (alpha-blended).
Figure 9.46. A mixed blending example