Skip to content

Instantly share code, notes, and snippets.

@aspose-com-gists
Last active March 29, 2022 21:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aspose-com-gists/55edf4d98d11685e003d8694df3d4e4f to your computer and use it in GitHub Desktop.
Save aspose-com-gists/55edf4d98d11685e003d8694df3d4e4f to your computer and use it in GitHub Desktop.
Change the Color of SVG Elements or Background Color Programmatically in C# .NET
// Set SVG Namespace Url
string SvgNamespace = "http://www.w3.org/2000/svg";
// Load an SVG document from the file
SVGDocument document = new SVGDocument("basic-shapes.svg");
// Get root svg element of the document
SVGSVGElement svgElement = document.RootElement;
// Create a rectangle element and set the "fill" attribute value to change background color
SVGRectElement rectElement = (SVGRectElement)document.CreateElementNS(SvgNamespace, "rect");
rectElement.X.BaseVal.Value = 3;
rectElement.Y.BaseVal.Value = 3;
rectElement.Width.BaseVal.Value = 400;
rectElement.Height.BaseVal.Value = 400;
rectElement.SetAttribute("fill", "Salmon");
// Add the rectangle element as the first child to SVG element
svgElement.InsertBefore(rectElement, svgElement.FirstChild);
// Save the SVG document
document.Save("background-color.svg");
// Load an SVG document from the file
SVGDocument document = new SVGDocument("shapes.svg");
// Get root svg element of the document
SVGElement svgElement = document.RootElement;
// Get circle element to change color
SVGCircleElement circleElement = svgElement.QuerySelector("circle") as SVGCircleElement;
// Set a new "fill" attribute value for the circle element
circleElement.SetAttribute("fill", "blue");
// Save the SVG document
document.Save("circle-color.svg");
// Load an SVG document from the file
SVGDocument document = new SVGDocument("basic-shapes.svg");
// Get root svg element of the document
SVGSVGElement svgElement = document.RootElement;
// Get line element to change color
SVGLineElement lineElement = svgElement.QuerySelector("line") as SVGLineElement;
// Set a new "stroke" attribute value for the line element
lineElement.SetAttribute("stroke", "blue");
// Save the SVG document
document.Save("line-color.svg");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment