代码之家  ›  专栏  ›  技术社区  ›  Julien Poulin

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

  •  22
  • Julien Poulin  · 技术社区  · 17 年前

    我正在尝试创建一个透明背景的图像以显示在网页上。

    如何创建一个透明图像,然后在其上绘制一些线?

    2 回复  |  直到 15 年前
        1
  •  39
  •   OregonGhost    17 年前

    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.Drawing System.Drawing.Imaging

    编辑:看起来你实际上并不需要 Clear() . 仅使用alpha通道创建图像即可创建空白(完全透明)图像。

        2
  •  0
  •   Erling Paulsen    17 年前

    这可能会有所帮助(我将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;
    
        }
    
    推荐文章