在 C# 中创建 SVG、加载和读取 SVG

要执行任何任务,您必须创建或加载文档。 Aspose.SVG for .NET API 允许您从头开始构建 SVG 文档以及从不同来源加载现有的 SVG。 API 提供的 SVGDocument 类具有多个构造函数,允许您生成新的类实例。 SVGDocument 是 SVG DOM 层次结构的根,包含整个内容,并且完全基于 W3C SVG 2.0 WHATWG DOM 规范。

可以创建和加载 SVG 文件:

本文提供了一些使用 Aspose.SVG for .NET API 创建和加载 SVG 文件的示例。 SVGDocument 有一组广泛的重载构造函数,允许您创建空白文档或从文件、URL、流等加载它。

创建一个空的 SVG 文档

Aspose.SVG for .NET API 提供了 SVGDocument 类,可用于使用其默认构造函数创建空文档。创建文档对象后,稍后可以用 SVG 元素填充它。以下 C# 代码片段显示了如何使用默认的 SVGDocument() 构造函数来创建 SVG 文档。

1using Aspose.Svg;
2...
3
4    // Initialize an empty SVG document
5    using (var document = new SVGDocument())
6    {
7        // Work with the SVG document here...
8    }

如果要将创建的空 SVG 文档保存到文件中,请使用以下 C# 代码片段:

1using Aspose.Svg;
2using System.IO;
 1// Create an empty SVG document using C#
 2
 3// Prepare an output path to save a document
 4string documentPath = Path.Combine(OutputDir, "empty.svg");
 5
 6// Initialize an empty SVG document
 7using (SVGDocument document = new SVGDocument())
 8{
 9    // Work with the SVG document here...
10
11    // Save the document to a file
12    document.Save(documentPath);
13}

有关 SVG 文件保存的更多详细信息,请参阅 保存 SVG 文档 部分。在文章 编辑 SVG 文件 中,您将了解如何使用 Aspose.SVG for .NET 库编辑 SVG,并找到如何向 SVG 文档添加新元素以及将 SVG 滤镜应用于位图的详细示例。

从内存字符串创建 SVG

您可以使用 SVGDocument (string, string) 构造函数从字符串内容创建 SVG。如果您的情况是直接在代码中根据用户字符串生成文档,并且不需要将其保存到文件中,则以下示例可以帮助您:我们生成一个 SVG 文档,其中包含半径为 40 的圆像素。

 1using Aspose.Svg;
 2...
 3
 4    // Prepare SVG code
 5    var documentContent = "<svg xmlns=\"http://www.w3.org/2000/svg\"><circle cx=\"50\" cy=\"50\" r=\"40\" /></svg>";	
 6
 7	// Initialize an SVG document from a string content
 8	using (var document = new SVGDocument(documentContent, "."))
 9	{
10	    // Work with the document here...
11	}

从流创建 SVG

要从流创建 SVG,请使用 SVGDocument() 构造函数之一:

 1using Aspose.Svg;
 2using System.IO;
 3...
 4
 5    //Prepare a path to a file required for a FileStream object creating
 6    string documentPath = Path.Combine(DataDir, "bezier-curves.svg");
 7
 8	// Create a FileStream object
 9	using (var stream = new FileStream(documentPath, FileMode.Open, FileAccess.Read))
10	{
11	    // Initialize an SVG document from the stream
12		using (var document = new SVGDocument(stream, "."))
13	    {
14	        // Work with the document
15	    }
16	}

使用 SVG Builder API 创建自定义 SVG 文档

SVG Builder API 提供了一种强大且灵活的方式来以编程方式构建 SVG 文档。 通过利用SVGSVGElementBuilder类,开发人员可以轻松创建具有详细自定义选项的复杂 SVG 图形。 有关使用 SVG Builder API 的更多信息,请参阅文档文章 使用 Aspose.SVG Builder API 进行高级 SVG 创建和修改

以下示例演示了如何创建具有各种图形元素的自定义 SVG 文档:

1using System.IO;
2using Aspose.Svg;
3using Aspose.Svg.Builder;
4using System.Drawing;
 1// Create SVG using Builder API
 2
 3// Initialize an SVG document
 4using (SVGDocument document = new SVGDocument())
 5{
 6    // Create an <svg> element with specified width, height and viewBox, and add into it other required elements
 7    SVGSVGElement svg = new SVGSVGElementBuilder()
 8        .Width(100).Height(100)
 9        .ViewBox(-21, -21, 42, 42)
10        .AddDefs(def => def
11            .AddRadialGradient(id: "b", cx: .2, cy: .2, r: .5, fx: .2, fy: .2, extend: ev => ev
12                .AddStop(offset: 0, stopColor: Color.FromArgb(0xff, 0xff, 0xFF), stopOpacity: .7)
13                .AddStop(offset: 1, stopColor: Color.FromArgb(0xff, 0xff, 0xFF), stopOpacity: 0)
14            )
15            .AddRadialGradient(id: "a", cx: .5, cy: .5, r: .5, extend: ev => ev
16                .AddStop(offset: 0, stopColor: Color.FromArgb(0xff, 0xff, 0x00))
17                .AddStop(offset: .75, stopColor: Color.FromArgb(0xff, 0xff, 0x00))
18                .AddStop(offset: .95, stopColor: Color.FromArgb(0xee, 0xee, 0x00))
19                .AddStop(offset: 1, stopColor: Color.FromArgb(0xe8, 0xe8, 0x00))
20            )
21        )
22        .AddCircle(r: 20, fill: "url(#a)", stroke: Color.FromArgb(0, 0, 0), extend: c => c.StrokeWidth(.15))
23        .AddCircle(r: 20, fill: "b")
24        .AddG(g => g.Id("c")
25            .AddEllipse(cx: -6, cy: -7, rx: 2.5, ry: 4)
26            .AddPath(fill: Paint.None, stroke: Color.FromArgb(0, 0, 0), d: "M10.6 2.7a4 4 0 0 0 4 3", extend: e => e.StrokeWidth(.5).StrokeLineCap(StrokeLineCap.Round))
27        )
28        .AddUse(href: "#c", extend: e => e.Transform(t => t.Scale(-1, 1)))
29        .AddPath(d: "M-12 5a13.5 13.5 0 0 0 24 0 13 13 0 0 1-24 0", fill: Paint.None, stroke: Color.FromArgb(0, 0, 0), extend: e => e.StrokeWidth(.75))
30        .Build(document.FirstChild as SVGSVGElement);
31
32    // Save the SVG document
33    document.Save(Path.Combine(OutputDir, "face.svg"));
34}

此代码片段创建了一个具有复杂设计的 SVG 文档,展示了 SVG Builder API 以编程方式生成自定义 SVG 图形的灵活性和强大功能。 在上面的 C# 代码中,我们创建了一个包含圆形、椭圆、路径和渐变等元素的 SVG 文档。生成的 SVG 图像代表一张微笑的脸(笑脸ы:

文本 “笑脸 - 一张微笑的脸 - Face.svg 文件的渲染”

从文件加载 SVG

要从文件 bezier-curves.svg 加载 SVG,请使用 SVGDocument 类的默认构造函数,并将文件路径作为输入参数传递给它。

 1using Aspose.Svg;
 2using System.IO;
 3...
 4    
 5    // Prepare a path to a file loading
 6    string documentPath = Path.Combine(DataDir, "bezier-curves.svg"); 
 7	
 8	// Load an SVG document from the file
 9	using (var document = new SVGDocument(documentPath))
10	{
11	    // Work with the document 
12	}

从 Web 加载 SVG

以下示例可以帮助您从引用 XML 文件的 URL 创建文档:

1using Aspose.Svg;
2...
3
4    // Load SVG from the Web at its URL
5    var documentUrl = new Url("https://docs.aspose.com/svg/files/owl.svg");
6    using (var document = new SVGDocument(documentUrl))
7    {
8        // Work with the SVG document here...
9    }
1using Aspose.Svg;
2...
3
4    // Load SVG from the Web at its URL
5    using (var document = new SVGDocument(new Url("https://docs.aspose.com/svg/files/basic-shapes.svg")))
6    {
7        // Work with the SVG document here...
8    }

如果您设置了此时无法正确访问的错误 URL,则库会抛出带有专门代码 NetworkError 的 DOMException,以通知您无法找到所选资源。

使用资源异步读取 SVG

如果 SVG 包含外部资源,则可能需要一些时间才能完全加载所有资源,从而导致主应用程序线程阻塞。在异步模型中,可以订阅 Load 和 ReadyStateChange 事件以通知加载应用程序完成 SVG 文件的加载,如以下代码示例所示。 SVGDocument 类的 Navigate(Url) 方法用于将指定 URL 处的文档加载到当前实例中。

1using Aspose.Svg;
2using System.Threading;
 1// Load SVG asynchronously using C#
 2
 3Url documentUrl = new Url("https://docs.aspose.com/svg/files/owl.svg");
 4ManualResetEvent documentEvent = new ManualResetEvent(false);
 5
 6SVGDocument document = new SVGDocument();
 7
 8// Subscribe to the event 'OnReadyStateChange' that will be fired once the document is completely loaded
 9document.OnReadyStateChange += (sender, ev) =>
10{
11    if (document.ReadyState == "complete")
12    {
13        // Sets the state of the event to signaled to unblock the main thread
14        documentEvent.Set();
15    }
16};
17
18// Load an SVG document Async
19document.Navigate(documentUrl);
20
21// Blocks the current thread while the document is loading
22documentEvent.WaitOne();
23
24// Work with the document

您可以从 GitHub 下载完整的示例和数据文件。您可以从 如何运行示例 部分了解如何从 GitHub 下载并运行示例。

Close
Loading

Analyzing your prompt, please hold on...

An error occurred while retrieving the results. Please refresh the page and try again.

Subscribe to Aspose Product Updates

Get monthly newsletters & offers directly delivered to your mailbox.