使用C# GDI绘制图片时,设置背景透明,有几个地方需要注意的:
1、先绘制一个透明图片,再在这个基础上绘制需要的其它元素;
2、保存时保存为.png格式。
示例代码如下:
System.Drawing.Image bitmap = new System.Drawing.Bitmap(100, 100);
//新建一个画板
Graphics g = System.Drawing.Graphics.FromImage(bitmap);
//设置高质量插值法
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
//设置高质量,低速度呈现平滑程度
g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
#region Setp 1:绘制透明的图像
ImageAttributes vAttr = new ImageAttributes();
vAttr.SetColorKey(Color.Transparent, Color.Transparent);
g.DrawImage(bitmap, new Rectangle(0, 0, bitmap.Width, bitmap.Height), 0, 0, bitmap.Width, bitmap.Height, GraphicsUnit.Pixel, vAttr);
#endregion
//Setp 2:绘制其它内容
//......
#endregion
#region 保存图片
//Setp 3:以png格式保存
bitmap.Save(thumbnailPath, System.Drawing.Imaging.ImageFormat.Png);
这里的重点是,使用ImageAttributes
编制一个透明图片,效果如下:
