C# 使用 GDI+ 创建具有透明背景的图像?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/708860/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Create image with transparent background using GDI+?
提问by Julien Poulin
I'm trying to create an image with a transparent background to display on a web page.
I've tried several techniques but the background is always black.
How can I create a transparent image and then draw some lines on it ?
我正在尝试创建一个具有透明背景的图像以显示在网页上。
我尝试了几种技术,但背景总是黑色。
如何创建透明图像,然后在其上绘制一些线条?
采纳答案by OregonGhost
Call Graphics.Clear(Color.Transparent)
to, well, clear the image. Don't forget to create it with a pixel format that has an alpha channel, e.g. PixelFormat.Format32bppArgb
. Like this:
打电话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);
}
Assumes you're using
System.Drawing
and System.Drawing.Imaging
.
假设您是using
System.Drawing
和System.Drawing.Imaging
。
Edit: Seems like you don't actually need the Clear()
. Just creating the image with an alpha channel creates a blank (fully transparent) image.
编辑:似乎您实际上并不需要Clear()
. 只需使用 Alpha 通道创建图像即可创建空白(完全透明)图像。
回答by Erling Paulsen
This might help(something I threw together which sets the background of a Windows form to a transparent image:
这可能会有所帮助(我把一些东西放在一起,将 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;
}