本快速指南涵盖了使用 C# 将文本转换为 SVG 的详细信息。它包括使用 C#** 从文本制作 SVG 的分步过程和可运行的示例代码。此外,您还将了解如何根据您的要求自定义包含文本的输出 SVG 文件。
使用 C# 从文本创建 SVG 的步骤
- 设置 IDE 以使用 Aspose.SVG for .NET 将文本转换为 SVG 图像
- 创建 SVGDocument 类的实例并访问根 SVG 元素
- 使用 CreateElementNS 方法定义 SVG 文本元素
- 指定文本内容并设置不同的外观属性
- 将文本附加到根并渲染输出 SVG 图像
这些步骤解释了*使用 C# 创建 SVG 文本的过程。作为先决条件,请先准备好环境来开始该过程。随后,在渲染输出矢量图像之前指定文本字符串和不同的外观参数,例如颜色和位置坐标。
使用 C# 创建文本 SVG 的代码
using Aspose.Svg; | |
using System; | |
class Program | |
{ | |
static void Main(string[] args) // Text to SVG in C# | |
{ | |
new License().SetLicense("License.lic"); | |
// Create SVGDocument class object | |
var document = new Aspose.Svg.SVGDocument(); | |
// Get root svg element | |
var svgElement = document.RootElement; | |
const string @namespace = "http://www.w3.org/2000/svg"; | |
// Define SVG Text element | |
var text = (Aspose.Svg.SVGTextElement)document.CreateElementNS(@namespace, "text"); | |
// Define text to show | |
text.TextContent = "Sample Text in SVG"; | |
// Set various attributes | |
text.SetAttribute("fill", "blue"); text.SetAttribute("x", "10"); | |
text.SetAttribute("y", "30"); | |
// Append text to the root | |
svgElement.AppendChild(text); | |
// Save output SVG | |
document.Save("svg-text.svg"); | |
Console.WriteLine("Text converted to SVG successfully"); | |
} | |
} |
此示例代码演示了使用 C# 从文本创建 SVG 的基本版本。首先,启动 SVGDocument 类对象,并使用 RootElement 属性访问根元素。接下来,在导出输出 SVG 图像之前,使用 AppendChild 方法定义 SVG 文本元素并将其附加到根。但是,您可以通过设置文本路径、文本样式和 TSpan 来进一步增强此代码,以将不同的外观应用于 SVG 图像中的文本。
本文教我们使用 C# 创建文本 SVG。此外,如果您想更改 SVG 的背景颜色,请阅读 如何在C#中更改SVG的背景颜色 上的文章。