【发布时间】:2010-10-17 01:39:54
【问题描述】:
我正在尝试创建具有透明背景的图像以显示在网页上。
我尝试了几种技术,但背景总是黑色。
如何创建透明图像,然后在其上绘制一些线条?
【问题讨论】:
我正在尝试创建具有透明背景的图像以显示在网页上。
我尝试了几种技术,但背景总是黑色。
如何创建透明图像,然后在其上绘制一些线条?
【问题讨论】:
这可能会有所帮助(我将 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;
}
【讨论】:
致电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 通道创建图像就会创建一个空白(完全透明)图像。
【讨论】:
image.MakeTransparent();。