public void MakeTransparent(Color transparentColor) { if (RawFormat.Guid == ImageFormat.Icon.Guid) { throw new InvalidOperationException(SR.GetString(SR.CantMakeIconTransparent)); } Size size = Size; // The new bitmap must be in 32bppARGB format, because that's the only // thing that supports alpha. (And that's what the image is initialized to -- transparent) Bitmap result = null; Graphics graphics = null; try { result = new Bitmap(size.Width, size.Height, PixelFormat.Format32bppArgb); try { graphics = Graphics.FromImage(result); graphics.Clear(Color.Transparent); Rectangle rectangle = new Rectangle(0, 0, size.Width, size.Height); ImageAttributes attributes = null; try { attributes = new ImageAttributes(); attributes.SetColorKey(transparentColor, transparentColor); graphics.DrawImage(this, rectangle, 0, 0, size.Width, size.Height, GraphicsUnit.Pixel, attributes, null, IntPtr.Zero); } finally { if (attributes != null) { attributes.Dispose(); } } } finally { if (graphics != null) { graphics.Dispose(); } } // Swap nativeImage pointers to make it look like we modified the image in place IntPtr temp = this.nativeImage; this.nativeImage = result.nativeImage; result.nativeImage = temp; } finally { if (result != null) { result.Dispose(); } } }
public void MakeTransparent(Color transparentColor) { // We have to draw always over a 32-bitmap surface that supports alpha channel Bitmap bmp = new Bitmap(Width, Height, PixelFormat.Format32bppArgb); Graphics gr = Graphics.FromImage(bmp); Rectangle destRect = new Rectangle(0, 0, Width, Height); ImageAttributes imageAttr = new ImageAttributes(); imageAttr.SetColorKey(transparentColor, transparentColor); gr.DrawImage(this, destRect, 0, 0, Width, Height, GraphicsUnit.Pixel, imageAttr); IntPtr oldBmp = nativeObject; nativeObject = bmp.nativeObject; bmp.nativeObject = oldBmp; gr.Dispose(); bmp.Dispose(); imageAttr.Dispose(); }