Skip to content

Instantly share code, notes, and snippets.

@aspose-com-gists
Last active August 12, 2022 20:09
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/ee2b9d6a20c6fb63667e7cd8f6eddaac to your computer and use it in GitHub Desktop.
Save aspose-com-gists/ee2b9d6a20c6fb63667e7cd8f6eddaac to your computer and use it in GitHub Desktop.
Fill and Stroke in SVG using C# | SVG Fill and SVG Stroke in C#
// This code example demonstrates how to set fill and stroke attributes for a circle element of SVG in C#.
// Load an existing SVG image
var document = new SVGDocument(@"C:\Files\SVG\Circle.svg");
// Get root SVG element of the document
var svgElement = document.RootElement;
// Find all circle elements in g element
NodeList circleNodes = svgElement.QuerySelectorAll("circle");
// Get the first circle element
SVGCircleElement circleElement = circleNodes[0] as SVGCircleElement;
// Set fill attributes
circleElement.SetAttribute("fill", "#0F0");
circleElement.SetAttribute("fill-opacity", "0.3");
// Set stroke attributes
circleElement.SetAttribute("stroke", "#508484");
circleElement.SetAttribute("stroke-width", "10");
// Save the SVG
document.Save(@"C:\Files\SVG\Fill-Circle.svg");
// This code example demonstrates how to set fill and stroke attributes for a path element of SVG in C#.
// Load an existing SVG image
var document = new SVGDocument(@"C:\Files\SVG\Sample-Path.svg");
// Get root SVG element of the document
var svgElement = document.RootElement;
// Get the first path element
SVGPathElement lineElement = svgElement.QuerySelector("path:nth-child(1)") as SVGPathElement;
// Set fill attributes
lineElement.SetAttribute("fill", "orange");
lineElement.SetAttribute("fill-opacity", "0.6");
// Set stroke attributes
lineElement.SetAttribute("stroke", "#508484");
lineElement.SetAttribute("stroke-width", "10");
// Save the SVG
document.Save(@"C:\Files\SVG\Fill-Path.svg");
// This code example demonstrates how to apply the fill and stroke attributes using the CSS style in C#.
// Create a new SVG
using (var document = new SVGDocument())
{
// Get root SVG element of the document
var svgElement = document.RootElement;
const string @namespace = "http://www.w3.org/2000/svg";
// Add Circle
var circle = (SVGCircleElement)document.CreateElementNS(@namespace, "circle");
circle.Cx.BaseVal.Value = 50;
circle.Cy.BaseVal.Value = 50;
circle.R.BaseVal.Value = 40;
// Set style attribute
circle.SetAttribute("style", "fill:blue; stroke:#fb6796; stroke-width:5");
// Add circle to the root element
svgElement.AppendChild(circle);
// Save the SVG
document.Save(@"C:\Files\SVG\ApplyStyle.svg");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment