How to Change SVG Color – C# Examples with Aspose.SVG

Aspose.SVG for .NET API allows you to programmatically edit SVG documents. Coloring is a key part of SVG design: you can colorize SVG shapes, lines, paths, and text, as well as set the fill color of interior areas, the stroke color of outlines, and even add background shapes. This guide provides C# examples that demonstrate:

All examples use the Aspose.SVG for .NET library and follow best practices for clean, maintainable code.

How to add new SVG elements and set their color properties, we covered in detail C# examples in the article Edit SVG Files.

The article SVG Color looks at how SVG text and shapes can be colorized. You’ll find an overview of how color is defined, including the various ways you can control the transparency of SVG content.

Change SVG Color

Filling and stroking are the two primary ways to apply color to SVG elements. All graphical elements such as shapes, paths and text – are rendered by being filled. The SVG stroke and SVG fill are some of the main CSS properties that can be set for any lines, text and shapes. For more information on style attributes’ properties, please see the article Fills and Strokes in SVG.

Aspose.SVG API allows you to change color of various SVG elements in an SVG document. First, you would load an existing SVG document and then, you can change color of required element:

  1. Use one of the SVGDocument() constructors of the SVGDocument class to load an existing SVG document.

  2. Use the QuerySelector(selector) to find the desired element in the SVG document. The QuerySelector(selector) method of the Element class allows you to get the first element within the document that matches the specified selector. With the resulting elements, you can make various manipulations: change its attributes, CSS styles, and so on.

  3. Use the SetAttribute(name, value) method of the Element class to specify element attributes fill or stroke.

Change Circle Color

To change circle color, you should follow a few steps:

The following code snippet shows how to change the circle color for the first SVG circle element in the basic-shapes.svg file shown in Figure (a) below:

1using Aspose.Svg;
2using System.IO;
3using Aspose.Svg.Dom;
 1// Change the fill color of an SVG circle in C#
 2
 3// Prepare a path to a file loading
 4string documentPath = Path.Combine(DataDir, "basic-shapes.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// Get a <circle> element to change a color
13SVGCircleElement circleElement = svgElement.QuerySelector("circle") as SVGCircleElement;
14
15// Set a new "fill" attribute value for the circle element
16circleElement.SetAttribute("fill", "green");
17
18// Save the SVG document to a file
19document.Save(Path.Combine(OutputDir, "circle-color.svg"));

Change Line Color

To change line color, you should follow similar steps. The C# example below shows how to change line color for the first SVG line element in basic-shapes.svg file:

1using Aspose.Svg;
2using System.IO;
3using Aspose.Svg.Dom;
 1// Change the stroke color of an SVG line using QuerySelector and SetAttribute in C#
 2
 3// Prepare a path to a file loading
 4string documentPath = Path.Combine(DataDir, "basic-shapes.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// Get a <line> element to change color
13SVGLineElement lineElement = svgElement.QuerySelector("line") as SVGLineElement;
14
15// Set a new "stroke" attribute value for the <line> element
16lineElement.SetAttribute("stroke", "green");
17
18// Save the SVG document
19document.Save(Path.Combine(OutputDir, "line-color.svg"));

The following Figure shows the original image (a) and images with SVG color changes for the circle (b) and the line (c).

Original svg image (a) and svg image with changed color for circle (b) and line (c) elements

The fill attribute sets the color of the SVG circle (Figure b). In the resulting circle-color.svg file, the circle color changes from red (in the original) to green. The stroke attribute sets the color of the SVG line. In the resulting line-color.svg file (Figure c), the line color changes from grey to green. Similarly, you can change color for various SVG graphic elements such as shapes, paths, and text using the fill or stroke attribute.

Change Background Color

To set the background color to SVG image, you should add a new SVG element such as circle or rectangle as the first child in an SVG document. Because the rule about the order of SVG elements showing is: later elements in the code are displayed on top of the previous ones.

The following code snippet shows how to create a new SVG rectangle as a background for SVG image and colorize it:

1using Aspose.Svg;
2using System.IO;
3using Aspose.Svg.Dom;
 1// Change the background color of an SVG image by adding a rectangle in C#
 2
 3// Load an SVG document from a file
 4SVGDocument document = new SVGDocument(Path.Combine(DataDir, "basic-shapes.svg"));
 5
 6// Get the root SVG element of the document
 7SVGSVGElement svgElement = document.RootElement;
 8
 9// Create a rectangle element and set the "fill" attribute value to change background color
10SVGRectElement rectElement = (SVGRectElement)document.CreateElementNS("http://www.w3.org/2000/svg", "rect");
11rectElement.X.BaseVal.Value = 3;
12rectElement.Y.BaseVal.Value = 3;
13rectElement.Width.BaseVal.Value = 400;
14rectElement.Height.BaseVal.Value = 400;
15rectElement.SetAttribute("fill", "Salmon");
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, "change-background-color.svg"));

The figure shows the visualization of the original SVG file basic-shapes.svg and the same file with the added background color.

Original svg image and svg image with new background color

Recolor SVG

Let’s draw a snowflake! The following C# example shows how to draw SVG snowflake and recolor it. You can use this approach for any SVG image: change the color of the required SVG element and change the background color:

1using Aspose.Svg;
2using System.IO;
3using Aspose.Svg.Dom;
 1// Add a colored background and recolor SVG path strokes using C# DOM methods
 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, "snowflake-blue.svg"));
 8
 9// Get the root SVG element of the document
10SVGSVGElement svgElement = document.RootElement;
11
12// Create a <circle> element and set attributes values
13SVGCircleElement circleElement = (SVGCircleElement)document.CreateElementNS(SvgNamespace, "circle");
14circleElement.Cx.BaseVal.Value = 150F;
15circleElement.Cy.BaseVal.Value = 100F;
16circleElement.R.BaseVal.Value = 150F;
17circleElement.SetAttribute("fill", "#03b6fd");
18
19// Add the <circle> element (background) as the first child to <svg> element
20svgElement.InsertBefore(circleElement, svgElement.FirstChild);
21
22// Get the first <path> element to change color
23SVGPathElement snowflakePath = svgElement.QuerySelector("path") as SVGPathElement;
24
25// Set a new "stroke" attribute value for the <path> element
26snowflakePath.SetAttribute("stroke", "white");
27
28// Save the SVG document
29document.Save(Path.Combine(OutputDir, "recolor-svg.svg"));

The figure shows the visualization of the original SVG file snowflake-blue.svg and the recolored file.

Original snowflake svg image and recolored snowflake svg image

Common Mistakes and Fixes

ProblemCauseSolution
Color does not change after updateThe selected SVG element does not exist or the CSS selector is incorrectVerify that the selector used in QuerySelector() matches the SVG markup and that the element exists before modifying attributes
Background color is not visibleThe background rectangle is added after other SVG elementsInsert the background <rect> as the first child of the <svg> element so it renders behind other shapes
Fill or stroke color is ignoredInline style attributes override fill or stroke valuesRemove or update the style attribute before setting new fill or stroke values
SVG renders incorrectly after modificationNew elements were created without the correct SVG namespaceAlways create elements using the SVG namespace (http://www.w3.org/2000/svg)
Only part of the SVG changes colorSome elements use stroke instead of fill (or vice versa)Check whether the element uses fill, stroke, or both, and update the correct attribute
Changes apply only to one elementMultiple SVG elements require recoloringUse QuerySelectorAll() and iterate over all matching elements to apply color changes consistently
Color values are ignored in browsersColor string is not in a recognized format (e.g., missing #).Use proper hex (#RRGGBB) or named color strings.

Quick Recipes

TaskDescriptionExample
Change fill color of an SVG shapeUpdates the fill attribute of a specific SVG element such as <circle>, <rect>, or <path>circleElement.SetAttribute("fill", "green");
Change stroke color of an elementModifies the stroke attribute to change line or outline colorlineElement.SetAttribute("stroke", "#FF0000");
Change background color of an SVGAdds a <rect> element that covers the SVG canvas and acts as a backgroundrectElement.SetAttribute("fill", "Salmon");
Recolor multiple SVG elementsApplies the same color to several elements using a CSS selectorQuerySelectorAll("circle")
Remove inline styles before recoloringEnsures fill and stroke attributes are not overridden by inline styles, for example for <rect>rectElement.RemoveAttribute("style");
Apply color using hexadecimal valuesSets precise colors using hex notation instead of named colorsrectElement.SetAttribute("fill", "#03b6fd");

Conclusion

Changing colors in SVG files with Aspose.SVG for .NET is straightforward. By manipulating the fill and stroke attributes – or by inserting background shapes – you can fully customize the visual appearance of any SVG graphic. The provided C# snippets cover the most common scenarios, from simple shape recoloring to complete image redesign.

Related Resources

  • Edit SVG Files – Detailed guide on adding, removing, and modifying SVG elements.
  • Change SVG Background Color – Learn how to change SVG background color in C# – by modifying the SVG directly, using inline and internal CSS, and using JavaScript.
  • Convert Color Codes – Study of color codes and learn how to programmatically convert color formats – RGB, HEX, HSL, HSV, CMYK, LAB, XYZ, etc.
  • You can download the complete examples and data files from GitHub.

Color Converter is a free online application for transforming colors between color formats. Just enter color code and get the result at once! You don’t need any additional software. Try our forceful Color Converter just now!

Text “Color Converter”

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.