How to: Draw Images with Transparency

The .NET Compact Framework supports transparency, but with only one transparency color. The SetColorKey(Color, Color) method must have the same color specified for the low color and high color range.

Example


This example creates a Bitmap of a rectangle with red and black designs and demonstrates two techniques for setting the transparency:

  • Use the SetColorKey(Color, Color) method based on a pixel in the image. This example sets the transparency using the upper-left pixel of the image. Because this pixel is black, all the originally black pixels will be transparent.

  • Use the SetColorKey(Color, Color) method with an explicit color setting. This example sets it to red, so that all the originally red pixels will be transparent.

To demonstrate, run the application first with both transparency techniques commented out to see how the image appears with no transparency set. Then uncomment the code for either of the transparency techniques.

// The .NET Compact Framework supports transparency,
// but with only one transparency color.
// The SetColorKey method must have the same color
// specified for the low color and high color range.

// Note that you must uncomment lines of code
// as indicated for the desired transparency effect.

protected override void OnPaint(PaintEventArgs e)
{
// Create a red and black bitmap to demonstrate transparency.
Bitmap bmp = new Bitmap(75,75);
Graphics g = Graphics.FromImage(bmp);

g.FillEllipse(new SolidBrush(Color.Red), 0, 0, bmp.Width, bmp.Width);
g.DrawLine(new Pen(Color.Black), 0, 0, bmp.Width, bmp.Width);
g.DrawLine(new Pen(Color.Black), bmp.Width, 0, 0, bmp.Width);
g.Dispose();

ImageAttributes attr = new ImageAttributes();

// Set the transparency color key based on the upper-left pixel
// of the image.
// Uncomment the following line to make all black pixels transparent:
// attr.SetColorKey(bmp.GetPixel(0, 0), bmp.GetPixel(0, 0));

// Set the transparency color key based on a specified value.
// Uncomment the following line to make all red pixels transparent:
// attr.SetColorKey(Color.Red, Color.Red);

// Draw the image using the image attributes.
Rectangle dstRect = new Rectangle(0, 0, bmp.Width, bmp.Height);
e.Graphics.DrawImage(bmp, dstRect, 0, 0, bmp.Width, bmp.Height,
GraphicsUnit.Pixel, attr);
}
转载自:http://msdn.microsoft.com/en-us/library/ms172507.aspx

posted @ 2010-12-07 11:31  古韵古风  阅读(246)  评论(0编辑  收藏  举报