Analyzing your prompt, please hold on...
An error occurred while retrieving the results. Please refresh the page and try again.
To change SVG gradient colors in C#, load the file with
SVGDocument, select a <linearGradient> or <radialGradient> with
QuerySelector(), update its <stop> elements with
SetAttribute(), and save the edited SVG. If a shape should use another gradient, set fill or stroke to url(#gradientId). To export the result, pass the edited document to
Converter.ConvertSVG().
This article shows how to edit gradient colors in an existing SVG file using
Aspose.SVG for .NET. It focuses on applied recoloring workflows: finding <linearGradient> and <radialGradient> definitions, changing stop-color values, replacing fill="url(#id)" references, saving the updated SVG, and rendering the result to PNG.
This page is about changing gradients that already exist in an SVG document. If you need to create gradients from scratch, see SVG Gradients – SVG Code and C# Examples.
You will learn how to:
<stop> colors by offset or position.stop-color values stored in a style attribute.fill="url(#id)" or stroke="url(#id)".The examples use the Aspose.SVG DOM API to edit SVG markup and the converter API to render the edited result:
| API | Used for |
|---|---|
| SVGDocument | Loads and saves the SVG document |
| Element | Represents selected gradients, stops, and painted shapes |
| QuerySelector() | Selects one gradient or shape by CSS selector |
| QuerySelectorAll() | Selects all gradient stops or all elements that reference a gradient |
| GetAttribute() | Reads id, offset, stop-color, fill, stroke, or style values |
| SetAttribute() | Updates gradient stops and paint server references |
| ImageSaveOptions | Configures PNG, JPG, WebP, BMP, TIFF, or GIF output |
| Converter.ConvertSVG() | Exports the edited SVG document to an image file |
SVG gradients are reusable paint servers. A <linearGradient> or <radialGradient> element usually lives inside <defs>, has an id, and contains child <stop> elements:
1<linearGradient id="grad1" x1="0%" y1="0%" x2="100%" y2="0%">
2 <stop offset="10%" stop-color="lightsalmon" />
3 <stop offset="50%" stop-color="teal" />
4 <stop offset="90%" stop-color="lightpink" />
5</linearGradient>A visible shape does not store the actual gradient colors. It references the gradient by ID:
1<ellipse fill="url(#grad1)" />This means that a gradient recoloring workflow usually has two separate tasks:
| Task | What to edit |
|---|---|
| Change the colors inside a gradient | Update <stop> elements inside <linearGradient> or <radialGradient> |
| Make a shape use another gradient | Update the shape’s fill or stroke attribute to url(#newGradientId) |
The examples use
linear-gradient.svg and
radial-gradient.svg. The linear sample stores stop colors in the style attribute:
1<linearGradient id="grad1" x1="0%" y1="0%" x2="100%" y2="0%">
2 <stop offset="10%" style="stop-color:LIGHTSALMON" />
3 <stop offset="50%" style="stop-color:TEAL" />
4 <stop offset="90%" style="stop-color:LIGHTPINK" />
5</linearGradient>The radial sample stores stop colors as stop-color attributes:
1<radialGradient id="myRG" cx="0.5" cy="0.5" r="0.9" fx="0.5" fy="0.5" spreadMethod="pad">
2 <stop offset="0%" stop-color="BISQUE" />
3 <stop offset="60%" stop-color="CADETBLUE" />
4</radialGradient>Both forms are valid SVG. The examples below show how to handle each one.
The following example loads an SVG file, finds a <linearGradient> by ID, and assigns new colors to its stops. It uses the stop order because the sample has three fixed stops. For generated or design-tool SVG files, you can also match stops by their offset values.
1using Aspose.Svg;
2using Aspose.Svg.Dom;
3using System;
4using System.IO; 1// Change linear gradient stop colors in an SVG file using C#
2
3// Load an SVG file that contains a linear gradient
4using (SVGDocument document = new SVGDocument(Path.Combine(DataDir, "linear-gradient.svg")))
5{
6 // Find the linearGradient element by ID
7 Element gradient = document.QuerySelector("linearGradient#grad1");
8
9 if (gradient == null)
10 {
11 throw new InvalidOperationException("Gradient 'grad1' was not found.");
12 }
13
14 // Define replacement colors for the linear gradient stops
15 string[] newColors =
16 {
17 "#1565c0",
18 "#00acc1",
19 "#f9a825"
20 };
21
22 int index = 0;
23
24 // Update each stop in the selected linear gradient
25 foreach (Element stop in gradient.QuerySelectorAll("stop"))
26 {
27 if (index >= newColors.Length)
28 {
29 break;
30 }
31
32 // Write stop-color as a presentation attribute
33 stop.SetAttribute("stop-color", newColors[index]);
34
35 // Remove a conflicting inline stop-color declaration if the source SVG used style
36 string style = stop.GetAttribute("style");
37 if (!string.IsNullOrWhiteSpace(style) &&
38 style.IndexOf("stop-color", StringComparison.OrdinalIgnoreCase) >= 0)
39 {
40 stop.RemoveAttribute("style");
41 }
42
43 index++;
44 }
45
46 // Save the SVG file with changed linear gradient colors
47 document.Save(Path.Combine(OutputDir, "linear-gradient-recolored.svg"));
48}This approach keeps the gradient geometry unchanged. Only the colors of the transition are changed.
The figure shows the original linear gradient (a) and the same SVG after changing the <linearGradient> stop colors (b).

Radial gradients use the same stop structure as linear gradients. The difference is in the gradient geometry: a radial gradient transitions from a center or focal point outward. To recolor it, find the <radialGradient> and update its child <stop> elements.
1using Aspose.Svg;
2using Aspose.Svg.Dom;
3using System;
4using System.Collections.Generic;
5using System.IO; 1// Change radial gradient stop colors in an SVG file using C#
2
3// Load an SVG file that contains a radial gradient
4using (SVGDocument document = new SVGDocument(Path.Combine(DataDir, "radial-gradient.svg")))
5{
6 // Find the radialGradient element by ID
7 Element gradient = document.QuerySelector("radialGradient#myRG");
8
9 if (gradient == null)
10 {
11 throw new InvalidOperationException("Gradient 'myRG' was not found.");
12 }
13
14 // Map gradient offsets to new stop colors
15 Dictionary<string, string> colorsByOffset = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
16 {
17 ["0%"] = "#fce1ff",
18 ["60%"] = "#690058"
19 };
20
21 // Update only the gradient stops whose offsets are listed in the palette
22 foreach (Element stop in gradient.QuerySelectorAll("stop"))
23 {
24 string offset = stop.GetAttribute("offset").Trim();
25
26 if (colorsByOffset.TryGetValue(offset, out string newColor))
27 {
28 stop.SetAttribute("stop-color", newColor);
29 }
30 }
31
32 // Save the SVG file with changed radial gradient colors
33 document.Save(Path.Combine(OutputDir, "radial-gradient-recolored.svg"));
34}Matching by offset is useful when the number of stops can change or when you only want to recolor specific positions in the gradient.
The figure shows the original radial gradient (a) and the same SVG after changing radial gradient stop colors by offset (b).

For bulk editing, scan all gradient stops and replace only the stop colors that match a source value. This is useful for brand refreshes, template processing, or recoloring assets exported from design tools.
Some SVG files store gradient colors directly on <stop> elements, for example stop-color="BISQUE". In this case, read the stop-color attribute, compare it with the source palette, and write the replacement value back with SetAttribute().
Other SVG files store the same value inside the style attribute, for example style="stop-color:TEAL". In this case, parse the inline CSS declarations and update only the stop-color declaration, leaving other style properties unchanged.
The following complete example handles both forms: stop-color attributes and inline style declarations.
1using Aspose.Svg;
2using Aspose.Svg.Dom;
3using System;
4using System.Collections.Generic;
5using System.IO; 1// Replace stop colors in all SVG gradients using C#
2
3// Load an SVG file that contains gradient stop colors
4using (SVGDocument document = new SVGDocument(Path.Combine(DataDir, "linear-gradient.svg")))
5{
6 // Define the source stop colors and their replacements
7 Dictionary<string, string> palette = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
8 {
9 ["LIGHTSALMON"] = "#ff7043",
10 ["TEAL"] = "#0277bd",
11 ["LIGHTPINK"] = "#f06292"
12 };
13
14 // Select stops inside both linear and radial gradients
15 foreach (Element stop in document.QuerySelectorAll("linearGradient stop, radialGradient stop"))
16 {
17 string stopColor = stop.GetAttribute("stop-color");
18
19 // Replace stop-color written as an SVG attribute
20 if (!string.IsNullOrWhiteSpace(stopColor) &&
21 palette.TryGetValue(stopColor.Trim(), out string replacement))
22 {
23 stop.SetAttribute("stop-color", replacement);
24 }
25
26 string style = stop.GetAttribute("style");
27 if (string.IsNullOrWhiteSpace(style))
28 {
29 continue;
30 }
31
32 List<string> updatedDeclarations = new List<string>();
33
34 // Replace stop-color written inside an inline style declaration
35 foreach (string declaration in style.Split(';', StringSplitOptions.RemoveEmptyEntries))
36 {
37 string[] parts = declaration.Split(':', 2);
38
39 if (parts.Length != 2)
40 {
41 updatedDeclarations.Add(declaration.Trim());
42 continue;
43 }
44
45 string property = parts[0].Trim();
46 string value = parts[1].Trim();
47
48 if (property.Equals("stop-color", StringComparison.OrdinalIgnoreCase) &&
49 palette.TryGetValue(value, out replacement))
50 {
51 value = replacement;
52 }
53
54 updatedDeclarations.Add($"{property}: {value}");
55 }
56
57 stop.SetAttribute("style", string.Join("; ", updatedDeclarations));
58 }
59
60 // Save the SVG file after replacing gradient stop colors
61 document.Save(Path.Combine(OutputDir, "gradient-stops-replaced.svg"));
62}Use this pattern when you know the old colors and want to replace them wherever they appear in gradient stops. If you need to inspect the palette first, see Extract SVG Colors in C#.
Sometimes the gradient colors are correct, but a shape references the wrong gradient. In that case, change the paint server reference on the shape instead of editing the stops.
First, create a new <linearGradient> element, assign it a unique id, add <stop> elements, and append the gradient to <defs>. The new gradient becomes available as a reusable paint server.
Then find shapes that use the old paint server reference and set their fill attribute to the new url(#id) value. The following complete example changes every element that uses fill="url(#grad1)" so it uses fill="url(#newBrandGradient)" instead:
1using Aspose.Svg;
2using Aspose.Svg.Dom;
3using System.IO; 1// Replace an SVG fill gradient reference with another gradient in C#
2
3// Load an SVG file that uses a gradient as a fill paint server
4using (SVGDocument document = new SVGDocument(Path.Combine(DataDir, "linear-gradient.svg")))
5{
6 string oldGradientRef = "url(#grad1)";
7 string newGradientRef = "url(#newBrandGradient)";
8
9 // Create a new gradient definition
10 const string SvgNamespace = "http://www.w3.org/2000/svg";
11
12 Element defs = document.QuerySelector("defs");
13 Element newGradient = document.CreateElementNS(SvgNamespace, "linearGradient");
14 newGradient.SetAttribute("id", "newBrandGradient");
15 newGradient.SetAttribute("x1", "0%");
16 newGradient.SetAttribute("y1", "0%");
17 newGradient.SetAttribute("x2", "100%");
18 newGradient.SetAttribute("y2", "0%");
19
20 // Add the first color stop to the new gradient
21 Element firstStop = document.CreateElementNS(SvgNamespace, "stop");
22 firstStop.SetAttribute("offset", "0%");
23 firstStop.SetAttribute("stop-color", "#1a237e");
24
25 // Add the second color stop to the new gradient
26 Element secondStop = document.CreateElementNS(SvgNamespace, "stop");
27 secondStop.SetAttribute("offset", "100%");
28 secondStop.SetAttribute("stop-color", "#26c6da");
29
30 newGradient.AppendChild(firstStop);
31 newGradient.AppendChild(secondStop);
32 defs.AppendChild(newGradient);
33
34 // Repoint shapes from the old gradient to the new gradient
35 foreach (Element element in document.QuerySelectorAll("[fill]"))
36 {
37 if (element.GetAttribute("fill").Trim() == oldGradientRef)
38 {
39 element.SetAttribute("fill", newGradientRef);
40 }
41 }
42
43 // Save the SVG file with the updated gradient reference
44 document.Save(Path.Combine(OutputDir, "gradient-fill-reference-updated.svg"));
45}The same idea works for gradient strokes. Search [stroke] and set stroke="url(#newGradientId)".
The figure shows the original SVG using a three-stop gradient fill="url(#grad1)" (a) and the result after repointing the same shapes to a newly created two-stop gradient fill (b).

After editing the SVG document, you can save it as SVG and export the same in-memory document to PNG. The PNG output reflects the new gradient colors and updated paint references.
1using Aspose.Svg;
2using Aspose.Svg.Converters;
3using Aspose.Svg.Dom;
4using Aspose.Svg.Saving;
5using System.IO; 1// Save an edited SVG gradient and export it to PNG in C#
2
3// Load an SVG file that contains a radial gradient
4using (SVGDocument document = new SVGDocument(Path.Combine(DataDir, "radial-gradient.svg")))
5{
6 Element gradient = document.QuerySelector("radialGradient#myRG");
7
8 // Recolor selected radial gradient stops before saving and exporting
9 foreach (Element stop in gradient.QuerySelectorAll("stop"))
10 {
11 string offset = stop.GetAttribute("offset").Trim();
12
13 if (offset == "0%")
14 {
15 stop.SetAttribute("stop-color", "#fffde7");
16 }
17 else if (offset == "60%")
18 {
19 stop.SetAttribute("stop-color", "#283593");
20 }
21 }
22
23 string svgOutputPath = Path.Combine(OutputDir, "radial-gradient-edited.svg");
24 string pngOutputPath = Path.Combine(OutputDir, "radial-gradient-edited.png");
25
26 // Save the editable SVG result
27 document.Save(svgOutputPath);
28
29 // Export the edited SVG document to PNG
30 ImageSaveOptions options = new ImageSaveOptions();
31 Converter.ConvertSVG(document, options, pngOutputPath);
32}Use this workflow when your application needs both an editable vector output and a raster preview or thumbnail.
| Problem | Cause | Fix |
|---|---|---|
| The visible shape did not change | The code changed fill on a shape that uses fill="url(#id)" | Edit the referenced gradient stops, or replace the url(#id) reference |
| The stop color still looks unchanged | A style="stop-color:..." declaration overrides or duplicates the stop-color attribute | Update the style declaration or remove it after setting stop-color |
| Only one shape changed unexpectedly | Several shapes share the same gradient definition | Duplicate or create a new gradient and point only selected shapes to the new url(#id) |
| The new gradient is not applied | The id in url(#id) does not match the gradient’s id | Keep the reference and gradient ID exactly aligned |
| A gradient is not found by selector | The SVG uses a different ID or generated IDs from a design tool | Inspect the SVG first or query all linearGradient, radialGradient elements |
| Exported PNG does not show the latest colors | The file was converted before edits were applied or a different document instance was converted | Save or convert the edited SVGDocument instance after all updates |
How do I change SVG gradient colors in C#?
Load the SVG with SVGDocument, find the <linearGradient> or <radialGradient> element, select its child <stop> elements, and update their stop-color values with SetAttribute().
How do I edit linearGradient stops?
Select the gradient with a selector such as linearGradient#grad1, then iterate through gradient.QuerySelectorAll("stop"). You can update stops by order, by offset, or by matching the current color.
How do I replace stop-color in SVG?
For stop-color attributes, call stop.SetAttribute("stop-color", newColor). If the SVG stores the value in style="stop-color:...", parse the style attribute and update that declaration as well.
Why does changing fill not change the gradient colors?
When fill is url(#id), it points to a gradient definition. The actual colors are stored in the gradient’s <stop> elements, not in the shape’s fill attribute.
Can several shapes use the same gradient?
Yes. If you edit the shared gradient definition, every shape that references it changes. To recolor only one shape, create a new gradient or duplicate the existing one, then update that shape’s fill or stroke reference.
Can I export the edited gradient SVG to PNG?
Yes. After changing the SVGDocument, create ImageSaveOptions and call Converter.ConvertSVG(document, options, outputPath).
Analyzing your prompt, please hold on...
An error occurred while retrieving the results. Please refresh the page and try again.