我有一个应用程序,允许用户创建不超过带有所需背景色的文本的简单图像。用户可以从System.Windows.Forms.ColorDialog
中选择一种颜色,并用它来设置文本颜色和背景颜色。如何保存带有透明背景的gif?
背景颜色可以设置为透明(我使用Color.Transparent
作为透明度的参考),选择之后,我更新预览图像,以正确显示文本和透明度。但是,当我去保存图像时,我无法获得用图像作为gif保存的透明度。
我发现this article其中规定我应该使用MakeTransparent
方法来设置透明度颜色。
在我调用保存操作之前,我将内存中的图像作为背景/透明颜色使用黑色重新绘制,然后在保存图像之前,在内存图像上调用MakeTransperent
方法。尽管如此,图像仍以黑色作为背景进行保存。
我会做什么错?
编辑:这里是相关的代码。
这是创建图像的方法。 overrideBG
变量用于指定是否应将透明度颜色设置为gif的非alpha颜色。
void ReDrawImage(bool overrideBG = false) //My method that draws the image in memory.
{
//My In Memory Image creation
img = new Bitmap(sz.Width, sz.Height);
Graphics gfx = Graphics.FromImage(img);
...
//This portion of code sets the BG color to what should be the transparency color, if the BG is transparent
if (overrideBG)
{
gfx.Clear(TransparentColor); //TransparentColor = Black, unless Text Color is Black. If so, it equals White.
}
else
{
gfx.Clear(BackColorPreview.BackColor);
}
//Followed by code that writes the text.
}
//This is the save method (Assume we are always drawing a transparent background.)
Save()
{
ReDrawImage(true);
img.MakeTransparent(TransparentColor); //I've also tried moving this line before the ReDrawImage call
img.Save(SaveFile.FileName, ImageFormat.Gif);
ReDrawImage();
}
发布您的代码。 – lincolnk