本文将指导您如何在 C# 中创建透明图像。它包含设置 IDE 的详细信息、步骤列表以及在 C# 中绘制具有透明背景的图片的示例代码。您将学习如何通过添加多个对象并根据要求自定义输出 PNG 图像来创建复杂形状。
在 C# 中创建透明 PNG 的步骤
- 设置环境以使用 Aspose.Drawing for .NET 创建透明图像
- 创建 bitmap 并使用它来创建 Graphics 对象以实现绘图
- 清除位图并将其背景设置为透明
- 实例化 GraphicsPath 对象以绘制复杂形状
- 在路径中添加圆、线、多边形等
- 创建一个彩色画笔并用它来填充所有形状
- 将整个位图设置为透明并将图像保存在磁盘上
这些步骤描述了如何在 C# 中使图片透明。创建一个位图,从位图生成一个 Graphics 对象以启用绘图,将位图设置为透明,并实例化 GraphicsPath 以创建复杂形状。向路径添加所需的对象,包括圆、线、椭圆、弧等,创建画笔并用它填充形状,最后使整个位图透明,然后将其放在磁盘上。
在 C# 中使图像透明的代码
using Aspose.Drawing; // For graphics and drawing features. | |
using Aspose.Drawing.Drawing2D; // For advanced 2D graphics and drawing tools. | |
class TransparentImageCreator // Class named "TransparentImageCreator" | |
{ | |
static void Main() // The entry point of the program | |
{ | |
new License().SetLicense("license.lic");// Avoid evaluation watermarks or limitations | |
using (Bitmap bmp = new Bitmap(340, 340)) // Create a 340x340 pixel bitmap | |
{ | |
using (Graphics g = Graphics.FromImage(bmp)) // Create a Graphics object from the bitmap | |
{ | |
g.Clear(Color.Transparent);// Clear the bitmap and set its background to transparent | |
GraphicsPath path = new GraphicsPath(); // Create a GraphicsPath object for complex shapes | |
path.AddEllipse(new RectangleF(20, 20, 100, 100));// Add a circle to the path | |
path.AddEllipse(new RectangleF(200, 200, 100, 100));// Add another circle to the path | |
using (Brush brush = new SolidBrush(Color.Blue)) // Create a SolidBrush object with blue color | |
{ | |
g.FillPath(brush, path);// Fill the defined path (both ellipses) with the blue brush | |
} | |
} | |
bmp.MakeTransparent();// Make the entire bitmap transparent | |
bmp.Save("pentagonImage.png");// Save the bitmap to a file | |
} | |
} | |
} |
此代码演示了如何使用 C# 开发 透明图像生成器。您可以向路径添加多种形状,例如弧线、贝塞尔曲线、闭合曲线、直线、饼图、矩形和字符串。如果您不想使图像透明并设置某些特定颜色,请使用 Graphics.Clear() 方法和所需的颜色。
本文教我们绘制复杂的透明图像。若要向 PNG 添加文本,请参阅文章 如何使用 C# 向 PNG 文件添加文本。