更改 SVG 背景颜色 – C# 示例

SVG 背景颜色对于提供视觉清晰度和对比度、提高内容的可见性和美观度至关重要。它对于保持设计一致性、通过提供可读文本来提高可访问性以及定义多层组合中的边界至关重要。您可以通过直接修改 SVG 或使用 CSS 或 JavaScript 应用样式来更改 SVG 的背景颜色。

Aspose.SVG for .NET API 允许您编辑 SVG 文档并更改其内容。

在本文中,您将了解如何使用 Aspose.SVG for .NET 将背景颜色应用于 SVG 文件,以及如何使用 Aspose.HTML C# 库在 HTML 文档中处理 SVG 图像的背景颜色。

直接修改SVG

要设置 SVG 图像的背景颜色,您应该插入一个新的 SVG 元素(例如矩形或圆形)作为 SVG 文档中的第一个子元素。此方法采用有关 SVG 元素顺序的规则 - SVG 代码中较晚出现的元素出现在较早出现的元素之上。通过在 SVG 的开头放置一个矩形或圆形,您可以有效地创建一个位于所有其他图形元素下方的背景层。

向 SVG 添加背景

在 SVG 中设置背景颜色的最常见方法是创建一个覆盖整个 SVG 画布的<rect>元素。这种方法确保背景是 SVG 内容本身的一部分。以下代码片段说明了如何向 SVG 添加背景 - 在 SVG 中创建一个新的矩形元素作为背景。为此,矩形被赋予 width="100%"height="100%"fill="#ebf3f6" 属性,并放置在所有其他 SVG 内容后面:

1using Aspose.Svg;
2using System.IO;
 1// Add background color rectangle to existing SVG using C#
 2
 3// Load an SVG document from a file
 4SVGDocument document = new SVGDocument(Path.Combine(DataDir, "tree.svg"));
 5
 6// Get the root SVG element of the document
 7SVGSVGElement svgElement = document.RootElement;
 8
 9// Create a rectangle element and set attributes values
10SVGRectElement rectElement = (SVGRectElement)document.CreateElementNS("http://www.w3.org/2000/svg", "rect");
11rectElement.X.BaseVal.Value = 3;
12rectElement.Y.BaseVal.Value = 3;            
13rectElement.SetAttribute("width", "100%");
14rectElement.SetAttribute("height", "100%");
15rectElement.SetAttribute("fill", "#ebf3f6");
16
17// Add the rectangle element as the first child to <svg> element
18svgElement.InsertBefore(rectElement, svgElement.FirstChild);
19
20// Save the SVG document
21document.Save(Path.Combine(OutputDir, "add-background-color.svg"));

更改 SVG 背景颜色

如果您的 SVG 文档有一个用作背景的元素(例如上例中的矩形),则更改背景颜色涉及几个步骤:

1using Aspose.Svg;
2using System.IO;
 1// Change background rectangle fill color in SVG using C#
 2
 3// Load an SVG document from a file
 4SVGDocument document = new SVGDocument(Path.Combine(DataDir, "add-background-color.svg"));
 5
 6// Get the root SVG element of the document
 7SVGSVGElement svgElement = document.RootElement;
 8
 9// Get the first <rect> element to change color
10SVGRectElement rectElement = svgElement.QuerySelector("rect") as SVGRectElement;
11
12// Set a new "fill" attribute value for the <rect> element
13rectElement.SetAttribute("fill", "#fef4fd");
14
15// Save the SVG document
16document.Save(Path.Combine(OutputDir, "change-background-color-in.svg"));

注意: 这种方式(<rect> 方法)在各个浏览器中最为一致,并确保背景颜色是 SVG 的一部分,即使 SVG 导出或在不同的上下文中使用时也是如此。

下图显示了原始 SVG 图像 (a)、添加背景的图像 (b) 和更改 SVG 背景颜色的图像 (c):

文本“原始 svg 图像 (a) 和添加 (b) 和更改 (c) 背景颜色的 svg 图像”

使用 CSS 更改背景颜色

使用 CSS 更改 SVG 背景颜色是一项常见任务,可增强网页中 SVG 图像的视觉呈现效果。虽然 SVG 元素不支持本机background-color属性,但您可以通过使用 CSS 设置其他 SVG 元素(如<rect>)的样式或通过外部、内部或内联 CSS 应用样式来实现此效果。

内联 CSS – 了解陷阱

您可以直观地尝试直接在 <svg> 元素上使用 style="background-color" 属性,期望它的工作方式与对 <div><p> 等 HTML 元素的工作方式相同。然而,这种方法充满了陷阱和误解。但有时它确实有效!在以下示例中,我们在<svg>元素的style属性中使用background-color属性:

1using Aspose.Svg;
2using System.IO;
 1// Set SVG background color using style attribute on root element in C#
 2
 3// Prepare a path to a source SVG file
 4string documentPath = Path.Combine(DataDir, "tulips.svg");
 5
 6// Load an SVG document from the file
 7SVGDocument document = new SVGDocument(documentPath);
 8
 9// Get the root SVG element of the document
10SVGSVGElement svgElement = document.RootElement;
11
12// Create a style attribute for the <svg> element
13svgElement.SetAttribute("style", "background: grey");
14
15// Save the SVG document
16document.Save(Path.Combine(OutputDir, "with-background-color.svg"));

为什么它看起来有效?

在某些浏览器或渲染上下文中,将background-color应用于 SVG 元素可能看起来可行,因为浏览器可能会使用指定的颜色填充分配给 SVG 的空间。但是,这种效果不会发生,因为 SVG 本身有背景,而是因为 SVG 内容周围或后面的区域是彩色的。这可能是一种意外行为,而不是 SVG 规范 定义的功能。

这种方法的问题

在 SVG style 属性中使用 background-color 的主要问题是它不是 SVG 规范的一部分。 SVG 标准不将background-color识别为 SVG 元素的有效样式属性。这意味着:

  1. 在一种浏览器中有效的内容可能在另一种浏览器中无效。
  2. 背景实际上并不是 SVG 内容的一部分,因此您对其行为和外观的控制较少,尤其是在导出、打印或在其他上下文中处理 SVG 时。

内部CSS

内部 CSS 是指直接嵌入到 HTML 或 SVG 文档中的样式,通常位于<style>标记中。这允许您定义仅适用于当前文档的特定样式,而不会影响其他文档或需要外部样式表。

在下面的示例中,

1using Aspose.Svg;
2using System.IO;
 1// Add SVG background color using CSS style element and rectangle with class in C#
 2
 3// Set SVG Namespace URL
 4string SvgNamespace = "http://www.w3.org/2000/svg";
 5
 6// Load an SVG document from a file
 7SVGDocument document = new SVGDocument(Path.Combine(DataDir, "tulips.svg"));
 8
 9// Get the root <svg> element of the document
10SVGSVGElement svgElement = document.RootElement;
11
12// Create a <style> element
13SVGStyleElement styleElement = (SVGStyleElement)document.CreateElementNS(SvgNamespace, "style");
14
15// Set the CSS content to define a background color class
16styleElement.TextContent = @".background {fill: grey;}";
17
18// Insert the <style> element at the beginning of the <svg> element
19svgElement.InsertBefore(styleElement, svgElement.FirstChild);
20
21// Create a rectangle element and set the class to "background"
22SVGRectElement rectElement = (SVGRectElement)document.CreateElementNS(SvgNamespace, "rect");
23rectElement.X.BaseVal.Value = -120;
24rectElement.Y.BaseVal.Value = 0;
25rectElement.SetAttribute("width", "100%");
26rectElement.SetAttribute("height", "100%");
27rectElement.SetAttribute("class", "background");
28
29// Add the rectangle element as the first child to the <svg> element, after the <style> element
30svgElement.InsertBefore(rectElement, svgElement.ChildNodes[1]);
31
32// Save the SVG document
33document.Save(Path.Combine(OutputDir, "add-background-color-with-css.svg"));

这种方法可以将样式和结构完全分离,利用 CSS 来简化管理以及 SVG 背景颜色的潜在未来更改。所有现代浏览器都广泛支持内部 CSS,确保 SVG 图像的渲染一致。

该图显示了原始 SVG 文件 (a) 和添加背景颜色的同一文件 (b) 的可视化效果:

文本“原始 svg 图像和具有新背景颜色的 svg 图像”

使用 SVG Builder 更改背景颜色

在以下代码中, SVG Builder 以编程方式将背景颜色添加到现有 SVG 文档(对于前面的情况中的 tulips.svg 文件)。

1using Aspose.Svg.Builder;
2using System.Drawing;
3using System.IO;
 1// Change a background color for an SVG document using SVG Builder
 2
 3//  Initialize an SVG document
 4using (SVGDocument document = new SVGDocument(Path.Combine(DataDir, "tulips.svg")))
 5{
 6    SVGSVGElement svg = new SVGSVGElementBuilder()
 7        .Width(100, LengthType.Percentage)
 8        .Height(100, LengthType.Percentage)
 9        .Build(document.FirstChild as SVGSVGElement);
10
11    // Create a new <g> element using SVGGElementBuilder and add <style> and <rect> elements to it
12    SVGElement g = new SVGGElementBuilder()
13        .Id("backgound")
14        .AddStyle(style => style
15            .Type("text/css")
16            .AddRule(".background", r => r.Fill(Color.Gray)
17        )
18        .AddRect(rect => rect
19            .X(-120).Y(0).Width(100, LengthType.Percentage).Height(100, LengthType.Percentage)
20            .Class("background")
21        ).BuildElement(document));
22    svg.InsertBefore(g, svg.FirstElementChild);
23
24    // Save the document
25    document.Save(Path.Combine(OutputDir, "add-background-color-with-builder.svg"));
26}

代码中的关键步骤涉及使用 SVGGElementBuilder 定义一个组元素 (<g>),其中包含具有内部 CSS 的<style>元素。此 CSS 通过.background类定义背景颜色。然后添加一个<rect>元素以使用此类应用背景。该组插入到 SVG 的开头,有效设置背景颜色。

在章节 SVG Builder – 高级 SVG 创建和修改 中,您将找到使用 Aspose.SVG Builder API 有效操作 SVG 的指南,涵盖从创建基本元素到高级技术 例如 mixins 和语法糖。

为 HTML 内的 SVG 图像添加背景颜色

要继续学习本教程,您应该在 C# 项目中安装并配置 Aspose.HTML for .NET 库。

处理包含 SVG 图像的 HTML 文档时,您可能需要向 SVG 元素添加背景颜色。尽管 SVG 通常是透明的,但添加背景可以提高可视性和美观性。以下 C# 示例演示如何使用 C# 和适用于 .NET 的 Aspose.HTML 库以编程方式向 HTML 文档中的所有 SVG 元素添加背景颜色。

  1. 使用 HTMLDocument() 构造函数之一加载 HTML 文件。
  2. 使用 QuerySelector() 方法在 HTML 文档中查找<style>元素,您将在其中添加新的 CSS 规则。
  3. 使用 InnerHTML 属性输出 <style> 元素的当前内容,以确保不会覆盖重要规则。
  4. 更新 <style> 元素的 TextContent 属性以附加用于设置 SVG 元素背景颜色的 CSS 规则。
  5. 使用 Save() 方法将更新的 HTML 文档导出到新文件。

源 HTML 文件 aspose-svg.html 包含内部 CSS。要为所有 SVG 图像添加彩色背景,我们将检查 <style> 元素的当前内容,并向 SVG 元素添加样式规则,指定将应用于 HTML 文件中所有 SVG 图像的背景颜色。

 1using System.IO;
 2using Aspose.Html;
 3...
 4
 5    // Prepare a path to a source HTML file with SVG image
 6    string documentPath = Path.Combine(DataDir, "aspose-svg.html");
 7
 8    // Load an HTML document from the file
 9    var document = new HTMLDocument(documentPath);
10
11    // Find a <style> element and assign a background color value for all svg elements
12    var styleElement = document.QuerySelector("style");
13
14    // Print content of the <style>
15    Console.WriteLine(styleElement.InnerHTML);
16
17    // Assign a text content for the style element
18    styleElement.TextContent = styleElement.InnerHTML + "svg {background-color: #fef4fd;}";
19
20    // Save the HTML document
21    document.Save(Path.Combine(OutputDir, "with-background-color.html"));

该图显示了原始 HTML 文件和添加了 SVG 图像背景颜色的同一文件的可视化效果:

文本“原始 HTML 页面和添加了 SVG 图像背景颜色的同一文件”

使用 JavaScript 更改背景颜色

SVG 文档

要使用 JavaScript 向 SVG 文件动态添加背景颜色,您可以将 <script> 元素直接嵌入到 SVG 中。以下是有关如何实现此目标的分步指南:

  1. 使用 SVGDocument 类加载 SVG 文件。
  2. 从加载的文档中访问根<svg>元素。这是您要添加背景的元素。
  3. 使用 CreateElementNS() 方法创建一个新的 <script> 元素。该脚本将包含用于添加 SVG 背景颜色的 JavaScript 代码。
  4. 定义 JavaScript 代码。选择 SVG 元素,创建一个具有完整尺寸和背景颜色的<rect>,并将其作为第一个子元素插入以设置背景。
  5. 将新创建的<script>元素添加到 SVG 文档中。
  6. 使用嵌入的 JavaScript 代码保存更新的 SVG 文档,其中现在包含背景颜色逻辑。
1using Aspose.Svg;
2using System.IO;
 1// Add SVG background color using embedded JavaScript <script> element in C#
 2
 3// Load an SVG document from a file
 4SVGDocument document = new SVGDocument(Path.Combine(DataDir, "tree.svg"));
 5
 6// Get the root <svg> element of the document
 7SVGSVGElement svgElement = document.RootElement;
 8
 9// Create a new <script> element
10Element scriptElement = document.CreateElementNS("http://www.w3.org/2000/svg", "script");
11
12// Define JavaScript code to add a <rect> element as the background
13scriptElement.TextContent = @"
14    var svgElement = document.getElementsByTagName('svg')[0];
15    if (svgElement) {
16        var rectElement = document.createElementNS('http://www.w3.org/2000/svg', 'rect');
17        rectElement.setAttribute('x', '0');
18        rectElement.setAttribute('y', '0');
19        rectElement.setAttribute('width', '100%');
20        rectElement.setAttribute('height', '100%');
21        rectElement.setAttribute('fill', '#fef4fd');
22        svgElement.insertBefore(rectElement, svgElement.firstChild);
23    };
24";
25
26// Append the <script> element to the SVG document
27svgElement.AppendChild(scriptElement);
28
29// Save the modified SVG document
30document.Save(Path.Combine(OutputDir, "svg-background-color-using-script.svg"));

HTML 文档中的 SVG

要继续学习本教程,您应该在 C# 项目中安装并配置 Aspose.HTML for .NET 库。

要使用 JavaScript 和 Aspose.HTML for .NET 更改 HTML 文档中 SVG 图像的背景颜色,您可以将 JavaScript 直接嵌入到 SVG 代码中,然后使用 Aspose.HTML 执行脚本。以下是实现这一目标的方法:

  1. 使用 HTMLDocument() 构造函数加载 HTML 文档。
  2. 使用 QuerySelector() 通过 ID 或其他属性查找 SVG 元素。
  3. 使用 CreateElement() 方法创建一个新的 <script> 元素。将其 TextContent 设置为修改 SVG 背景颜色的 JavaScript 代码。
  4. 使用AppendChild()方法将新的<script>元素附加到文档主体,确保执行 JavaScript 代码。
  5. 包括条件检查以处理未找到 SVG 元素的情况,并在必要时输出相关消息。
  6. 使用 Save() 方法将更新后的包含嵌入脚本的 HTML 文档导出到新文件。
 1using Aspose.Html;
 2using System.IO;
 3...
 4
 5    // Prepare a path to a source HTML file with SVG image
 6    string documentPath = Path.Combine(DataDir, "aspose-svg.html");
 7
 8    // Load an HTML document from the file
 9    var document = new HTMLDocument(documentPath);
10
11    // Find the SVG element by its ID (or any other attribute)
12    var svgElement = document.QuerySelector("svg[id='mySvg']");
13
14    if (svgElement != null)
15    {
16        // Create a new <script> element
17        var scriptElement = document.CreateElement("script");
18
19        // Define JavaScript code to add a <rect> element as the background
20        scriptElement.TextContent = @"
21            var svgElement = document.getElementById('mySvg');
22            if (svgElement) {
23                var rectElement = document.createElementNS('http://www.w3.org/2000/svg', 'rect');
24                rectElement.setAttribute('x', '0');
25                rectElement.setAttribute('y', '0');
26                rectElement.setAttribute('width', '100%');
27                rectElement.setAttribute('height', '100%');
28                rectElement.setAttribute('fill', '#fef4fd');
29                svgElement.insertBefore(rectElement, svgElement.firstChild);
30            };
31        ";
32
33        // Append the <script> element to the HTML document's body
34        document.Body.AppendChild(scriptElement);
35    }
36    else
37    {
38        // Handle the case where the svgElement was not found
39        Console.WriteLine("SVG element not found.");
40    }
41
42    // Save the SVG document
43    document.Save(Path.Combine(OutputDir, "svg-background-color-html-script.html"));

结论

在本文中,我们研究了使用 Aspose.SVG for .NET 和 Aspose.HTML for .NET 库应用和更改 SVG 图像背景颜色的几种方法:

总之,您选择的方法应取决于使用 SVG 的上下文以及所需的控制和一致性级别。直接修改 SVG 通常是最可靠的方法,尤其是对于独立的 SVG 文件。在 HTML 文档中使用 SVG 时,CSS 和 JavaScript 提供了灵活性,但也存在潜在的限制。

参见

文本“颜色转换器”

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.