使用GDI +创建具有透明背景的图像?

我正在尝试创建一个透明背景的图像,以显示在网页上。
我尝试了几种技术,但背景总是黑色的。
如何创建透明图像然后在其上绘制一些线条?

调用Graphics.Clear(Color.Transparent)来清除图像。 不要忘记使用具有alpha通道的像素格式创建它,例如PixelFormat.Format32bppArgb 。 像这样:

 var image = new Bitmap(135, 135, PixelFormat.Format32bppArgb); using (var g = Graphics.FromImage(image)) { g.Clear(Color.Transparent); g.DrawLine(Pens.Red, 0, 0, 135, 135); } 

假设您正在using System.DrawingSystem.Drawing.Imaging

编辑:好像你实际上并不需要Clear() 。 只需使用Alpha通道创建图像即可创建一个空白(完全透明)图像。

这可能有所帮助(我把一些东西放在一起,将Windows窗体的背景设置为透明图像:

 private void TestBackGround() { // Create a red and black bitmap to demonstrate transparency. Bitmap tempBMP = new Bitmap(this.Width, this.Height); Graphics g = Graphics.FromImage(tempBMP); g.FillEllipse(new SolidBrush(Color.Red), 0, 0, tempBMP.Width, tempBMP.Width); g.DrawLine(new Pen(Color.Black), 0, 0, tempBMP.Width, tempBMP.Width); g.DrawLine(new Pen(Color.Black), tempBMP.Width, 0, 0, tempBMP.Width); g.Dispose(); // Set the transparancy key attributes,at current it is set to the // color of the pixel in top left corner(0,0) ImageAttributes attr = new ImageAttributes(); attr.SetColorKey(tempBMP.GetPixel(0, 0), tempBMP.GetPixel(0, 0)); // Draw the image to your output using the transparancy key attributes Bitmap outputImage = new Bitmap(this.Width,this.Height); g = Graphics.FromImage(outputImage); Rectangle destRect = new Rectangle(0, 0, tempBMP.Width, tempBMP.Height); g.DrawImage(tempBMP, destRect, 0, 0, tempBMP.Width, tempBMP.Height,GraphicsUnit.Pixel, attr); g.Dispose(); tempBMP.Dispose(); this.BackgroundImage = outputImage; }