Compartir a través de


How to: Draw Opaque and Semitransparent Lines

When you draw a line, you must pass a Pen object to the DrawLine method of the Graphics class. One of the parameters of the Pen constructor is a Color object. To draw an opaque line, set the alpha component of the color to 255. To draw a semitransparent line, set the alpha component to any value from 1 through 254.

When you draw a semitransparent line over a background, the color of the line is blended with the colors of the background. The alpha component specifies how the line and background colors are mixed; alpha values near 0 place more weight on the background colors, and alpha values near 255 place more weight on the line color.

Example

The following example draws a bitmap and then draws three lines that use the bitmap as a background. The first line uses an alpha component of 255, so it is opaque. The second and third lines use an alpha component of 128, so they are semitransparent; you can see the background image through the lines. The statement that sets the CompositingQuality property causes the blending for the third line to be done in conjunction with gamma correction.

The following illustration shows the output of the following code.

Opaque and Semitransparent

Dim bitmap As New Bitmap("Texture1.jpg")
e.Graphics.DrawImage(bitmap, 10, 5, bitmap.Width, bitmap.Height)

Dim opaquePen As New Pen(Color.FromArgb(255, 0, 0, 255), 15)
Dim semiTransPen As New Pen(Color.FromArgb(128, 0, 0, 255), 15)

e.Graphics.DrawLine(opaquePen, 0, 20, 100, 20)
e.Graphics.DrawLine(semiTransPen, 0, 40, 100, 40)

e.Graphics.CompositingQuality = CompositingQuality.GammaCorrected
e.Graphics.DrawLine(semiTransPen, 0, 60, 100, 60)
Bitmap bitmap = new Bitmap("Texture1.jpg");
e.Graphics.DrawImage(bitmap, 10, 5, bitmap.Width, bitmap.Height);

Pen opaquePen = new Pen(Color.FromArgb(255, 0, 0, 255), 15);
Pen semiTransPen = new Pen(Color.FromArgb(128, 0, 0, 255), 15);

e.Graphics.DrawLine(opaquePen, 0, 20, 100, 20);
e.Graphics.DrawLine(semiTransPen, 0, 40, 100, 40);

e.Graphics.CompositingQuality = CompositingQuality.GammaCorrected;
e.Graphics.DrawLine(semiTransPen, 0, 60, 100, 60);

Compiling the Code

The preceding example is designed for use with Windows Forms, and it requires PaintEventArgs e, which is a parameter of the Paint event handler.

See Also

Tasks

How to: Give Your Control a Transparent Background
How to: Create Transparent Windows Forms
How to: Draw with Opaque and Semitransparent Brushes

Other Resources

Alpha Blending Lines and Fills