Drop Shadow – SVG Filters – C# Code

SVG Filters

Aspose.SVG for .NET lets you open, create, or edit an SVG document and make changes to its content. You can apply many available SVG filters for SVG elements or bitmaps to get the desired result. The Aspose.Svg.Filters namespace contains classes and interfaces related to filter effects in SVG specification. To create a drop shadow effect, you can use a few filter primitives:

In this article, you will learn how to write SVG code to create a drop shadow filter and consider detailed C# examples of using the Aspose.Svg.Filters namespace to apply the drop shadow effect to SVG elements or bitmaps.

Drop Shadow – SVG Code

The shadow effect in SVG is a common visual effect used to create the illusion of a shadow behind an SVG element. It provides depth and realism to SVG content by making it look like the element is floating above the background. Also, a drop shadow effect can be used to make an image stand out. There are several ways to implement the shadow effect in SVG. Let’s look at two of them.

Note: In SVG, filter defines by <filter> element, which sets within a <defs> element. It is never rendered itself and is conceptually described as the element that includes its children – filter primitives. The <filter> element has a set of attributes. Required attributes for filter primitive are x, y, width, height, and id. They set the area of the picture to which the filter will be applied. And the attribute id gives a unique identifier to an SVG element and identifies an element within an SVG document.

feOffset + feGaussianBlur + feBlend filter primitives

In our opinion, the most effective is to use three filters to achieve the shadow effect. This will allow you to fine-tune the effect even though it requires more code:

 1<svg height="200" width="200" xmlns="http://www.w3.org/2000/svg">
 2    <defs>
 3        <filter id="shadow" x="-20" y="-20" height="150" width="150" >
 4            <feOffset result="offset" in="SourceAlpha" dx="10" dy="10" />
 5            <feGaussianBlur result="blur" in="offset" stdDeviation="3" />
 6            <feBlend in="SourceGraphic" in2="blur" mode="normal" />
 7        </filter>
 8    </defs>
 9    <rect x="40" y="40" width="100" height="100" fill="orange" filter="url(#shadow)" />
10</svg>

Three filters are used to create a drop shadow effect (figure c):

  1. The <feOffset> filter primitive is used to offset a layer in SVG. It takes in="SourceAlpha", and shifts the result 10 px to the right and 10px to the bottom, and stores the result in the buffer as "offset". Note that the alpha channel of the shape is used as input. The value SourceAlpha leads to a black-color result (figure a).
  2. <feGaussianBlur> takes in="offset", applies a blur of stdDeviation="3", and stores the result in a temporary buffer named "blur".
  3. The <feBlend> filter blends two objects; it takes two inputs in="SourceGraphic" and in2="blur" then blends the SourceGraphic on top of the offset black blurred image (figure b). Its mode attribute specifies the blending mode.

The following Figure illustrates step-by-step the drop shadow creation:

Text “Drop shadow effect for orange rectangle – step by step illustration”

feDropShadow filter primitive

In SVG, the shadow effect can be achieved using the feDropShadow filter primitive on the <filter> element. The <feDropShadow> element has the attributes needed to create the drop shadow, such as dx, dy, and stdDeviation, plus it allows you to add color and transparency to the drop shadow! This is achieved using attributes flood-color and flood-opacity. Let’s see how to create a shadow effect using the feDropShadow filter primitive:

1<svg height="200" width="200" xmlns="http://www.w3.org/2000/svg">
2	<defs>
3        <filter id="shadow-red" x="-20" y="-20" height="100" width="100" >
4			<feDropShadow dx="10" dy="10" stdDeviation="3"  flood-color="CornflowerBlue" />
5		</filter>
6	</defs>
7    <rect x="40" y="40" width="100" height="100" fill="orange" filter="url(#shadow-red)" />
8</svg>

Text “Drop shadow effect for orange rectangle with a color shadow”

Note: if the flood-color attribute is not specified or specified incorrectly, then the default shadow will be black.

Drop Shadow – C# Code

Here we will write the С# code to create a drop shadow effect for an orange rectangle using three filter primitives.

The following code snippet shows how to create a drop shadow effect using the Aspose.SVG for .NET API.

  1. Use the SVGDocument() constructor to create an empty SVG document.
  2. The RootElement property of the SVGDocument class points to the document’s root <svg> element.
  3. Create a <defs> element and add it to the <svg> element:
  4. Create a <filter> element, set attributes, and add it to the <defs> element:
    • Use the CreateElementNS() method of the SVGDocument class to create an instance of the SVGFilterElement class.
    • Call the SetAttribute(name, value) method to set x, y, height, and width attributes.
    • Don’t forget to set the id attribute.
    • Use the AppendChild() method to add the <filter> to the <defs> element.
  5. Create a <feOffset> element, set attributes, and add it to the <filter> element:
    • Use the CreateElementNS() method of the SVGDocument class to create an instance of the SVGFEOffsetElement class.
    • Call the SetAttribute() method to set dx, dy, and result attributes.
    • Don’t forget to set in1 attribute. Use the property of the SVGAnimatedLength type, the static data for which can be set or read through the construction feOffsetElement.In1.BaseVal = "SourceAlpha".
    • Use the AppendChild() method to add the <feOffset> to the <filter> element.
  6. In a similar way create, set attributes, and add to the <filter> element such elements as <feGaussianBlur> and <feBlend>.
  7. Create a rectangle <rect> element that will be an SVG shape with a drop shadow effect. It is given a fill color (#ffa500 – orange), and the filter attribute is set to "url(#shadow)," referencing the previously defined filter with the Id = "shadow".
  8. Call the Save() method to save the document with the drop shadow filter to a local file specified by path.
 1using Aspose.Svg;
 2using System.IO;
 3using Aspose.Svg.Filters;
 4...
 5    // Set SVG Namespace Url
 6    string SvgNamespace = "http://www.w3.org/2000/svg";
 7
 8    using (var document = new SVGDocument())
 9    {
10        var svgElement = document.RootElement;
11
12        // Create a <defs> element and add to the svgElement
13        var defsElement = (SVGDefsElement)document.CreateElementNS(SvgNamespace, "defs");
14        svgElement.AppendChild(defsElement);
15
16        // Creating a <filter> element and add to the defsElement
17        var filterElement = (SVGFilterElement)document.CreateElementNS(SvgNamespace, "filter");
18        filterElement.Id = "shadow";
19        filterElement.SetAttribute("x", "-20px");
20        filterElement.SetAttribute("y", "-20px");
21        filterElement.SetAttribute("height", "150px");
22        filterElement.SetAttribute("width", "150px");
23        defsElement.AppendChild(filterElement);
24
25        // Create a <feOffset> filter primitive and add it to the filterElement
26        var feOffsetElement = (SVGFEOffsetElement)document.CreateElementNS(SvgNamespace, "feOffset");
27        feOffsetElement.In1.BaseVal = "SourceAlpha";
28        feOffsetElement.SetAttribute("result", "offset");
29        feOffsetElement.SetAttribute("dx", "10");
30        feOffsetElement.SetAttribute("dy", "10");
31        filterElement.AppendChild(feOffsetElement);
32
33        // Create a <feGaussianBlur> filter primitive and add it to the filterElement
34        var feGaussianBlurElement = (SVGFEGaussianBlurElement)document.CreateElementNS(SvgNamespace, "feGaussianBlur");
35        feGaussianBlurElement.In1.BaseVal = "offset";
36        feGaussianBlurElement.StdDeviationX.BaseVal = 3;
37        feGaussianBlurElement.StdDeviationY.BaseVal = 3;
38        feGaussianBlurElement.SetAttribute("result", "blur");
39        filterElement.AppendChild(feGaussianBlurElement);
40
41        // Create a <feBlend> filter primitive and add it to the filterElement
42        var feBlendElement = (SVGFEBlendElement)document.CreateElementNS(SvgNamespace, "feBlend");
43        feBlendElement.In1.BaseVal = "SourceGraphic";
44        feBlendElement.In2.BaseVal = "blur";
45        feBlendElement.SetAttribute("mode", "normal");
46        filterElement.AppendChild(feBlendElement);
47
48        // Create a <rect> element and set the "fill" and "filter" attributes
49        var rectElement = (SVGRectElement)document.CreateElementNS(SvgNamespace, "rect");
50        rectElement.X.BaseVal.Value = 40;
51        rectElement.Y.BaseVal.Value = 40;
52        rectElement.Width.BaseVal.Value = 100;
53        rectElement.Height.BaseVal.Value = 100;
54        rectElement.SetAttribute("fill", "#ffa500");
55        rectElement.SetAttribute("filter", "url(#shadow)");
56        svgElement.InsertBefore(rectElement, svgElement.FirstChild);
57
58        // Save the document
59        document.Save(Path.Combine(OutputDir, "drop-shadow-effect.svg"));
60    }

When you run this C# code, it will generate an SVG file with a drop shadow effect for an orange rectangle. The shadow will be black-colored, offset by 10 units horizontally and 10 units vertically from the source rectangle. The resulting drop-shadow-effect.svg file looks like figure c – an orange rectangle with a black shadow.

Drop Shadow Effect Using SVG Builder API

Aspose.SVG Builder API is designed for streamlined creation and updating of SVG elements in C#. Let’s look at a С# example for implementing drop shadow effect (exactly the same example as in the previous paragraph) using SVG Builder API. This code showcases the use of a fluent builder pattern to create concise and readable SVG documents, leveraging the capabilities of Aspose.SVG library:

 1using Aspose.Svg.Builder;
 2using System.Drawing;
 3using System.IO;
 4...
 5
 6    using (var document = new SVGDocument())
 7    {
 8        // Create an instance of SVGSVGElementBuilder to facilitate the construction of the <svg> element and its child elements using a fluent builder pattern
 9        var svg = new SVGSVGElementBuilder()
10            .Width(400).Height(400)
11            .AddDefs(d => d
12                .AddFilter(f => f.Id("shadow").Width(150).Height(150)
13                    .AddFeDropShadow(sh => sh
14                        .Dx(10).Dy(10)
15                        .StdDeviation(3)
16                    )
17                )
18            )
19            .AddRect(r => r
20                .Rect(40, 40, 100, 100)
21                .Filter(f => f.FilterId("shadow"))
22                .Style(s => s.Fill(Color.Orange))
23            )
24            //Call the Build() method on the SVGSVGElementBuilder to construct the <svg> element with its child elements
25            .Build(document.FirstChild as SVGSVGElement);
26        document.Save(Path.Combine(OutputDir, "drop-shadow-builder.svg"));
27    }

The fluent builder pattern allows you to create SVG elements and apply filters in a more concise and readable way. Each method call, such as .AddFilter or .AddRect, clearly states its purpose, allowing you to understand the structure of the SVG document at a glance. This example demonstrates a more expressive approach to creating SVG documents using SVG Builder, providing improved readability, maintainability, and flexibility compared to the manual approach of creating elements shown in the previous example. As a result of the code running, we get the same orange rectangle with a black shadow:

Text “Drop shadow effect for orange rectangle – visualization of the file drop-shadow-builder.svg”

Text Drop Shadow

This C# example creates an SVG file similar to the one we saw earlier in the feDropShadow filter primitive section. Only here, we use the feDropShadow filter primitive to create a colored shadow for an SVG text, not for the orange rectangle.

The following code snippet shows how to create a text drop shadow using the Aspose.SVG for .NET API:

 1using Aspose.Svg;
 2using System.IO;
 3using Aspose.Svg.Filters;
 4...
 5
 6    // Set SVG Namespace Url
 7    string SvgNamespace = "http://www.w3.org/2000/svg";
 8
 9    using (var document = new SVGDocument())
10    {
11        var svgElement = document.RootElement;
12
13        // Create a <defs> element and add to the svgElement
14        var defsElement = (SVGDefsElement)document.CreateElementNS(SvgNamespace, "defs");
15        svgElement.AppendChild(defsElement);
16
17        // Creating a <filter> element and add to the defsElement
18        var filterElement = (SVGFilterElement)document.CreateElementNS(SvgNamespace, "filter");
19        filterElement.Id = "text-shadow";
20        filterElement.SetAttribute("x", "-20px");
21        filterElement.SetAttribute("y", "-20px");
22        filterElement.SetAttribute("height", "150px");
23        filterElement.SetAttribute("width", "150px");
24        defsElement.AppendChild(filterElement);
25
26        // Create a <feDropShadow> filter primitive and add it to the filterElement
27        var feDropShadowElement = (SVGFEDropShadowElement)document.CreateElementNS(SvgNamespace, "feDropShadow");
28        feDropShadowElement.StdDeviationX.BaseVal = 3;
29        feDropShadowElement.StdDeviationY.BaseVal = 3;
30        feDropShadowElement.SetAttribute("dx", "3");
31        feDropShadowElement.SetAttribute("dy", "3");
32        feDropShadowElement.SetAttribute("flood-color", "LightCoral");
33        filterElement.AppendChild(feDropShadowElement);
34
35        // Create a <text> element and add it to the svgElement
36        var textElement = (SVGTextElement)document.CreateElementNS(SvgNamespace, "text");
37        textElement.Style.FontSize = "4em";
38        textElement.SetAttribute("x", "20px");
39        textElement.SetAttribute("fill", "CornflowerBlue");
40        textElement.SetAttribute("y", "100px");
41        textElement.TextContent = "Drop Shadow Effect";
42        textElement.SetAttribute("filter", "url(#text-shadow)");
43        svgElement.InsertBefore(textElement, svgElement.FirstChild);
44
45        // Save the document
46        document.Save(Path.Combine(OutputDir, "text-drop-shadow.svg"));
47    }

Text Drop Shadow – Using SVG Builder

Exactly the same example for text with a colored shadow, but we implement it using Aspose.SVG Builder:

 1using Aspose.Svg.Builder;
 2using System.Drawing;
 3using System.IO;
 4...
 5
 6    using (var document = new SVGDocument())
 7    {
 8        // Create an instance of SVGSVGElementBuilder to facilitate the construction of the <svg> element and its child elements using a fluent builder pattern
 9        var svg = new SVGSVGElementBuilder()
10            .AddDefs(d => d
11                .AddFilter(f => f.Id("shadow").Width(150).Height(150)
12                    .AddFeDropShadow(sh => sh
13                        .Dx(3).Dy(3)
14                        .StdDeviation(3)
15                        .FloodColor(Color.LightCoral)
16                    )
17                )
18            )
19            .AddText(t => t.X(20).Y(100).Fill(Color.CornflowerBlue).FontSize(48, LengthType.Pt)
20                .Filter(f => f.FilterId("shadow"))
21                .AddContent("Drop Shadow Effect")
22            )
23            
24            // Call the Build() method on the SVGSVGElementBuilder to construct the <svg> element with its child elements
25            .Build(document.FirstChild as SVGSVGElement);
26        document.Save(Path.Combine(OutputDir, "text-drop-shadow-builder.svg"));
27    }

The resulting text-drop-shadow.svg and text-drop-shadow-builder.svg images look like this:

Text “A drop shadow effect is applied to the text – Drop Shadow Effect”

The text has a drop shadow with a LightCoral fill color and a blur radius of 3 units. The shadow will be offset by 3 units horizontally and 3 units vertically from the text, creating a visually appealing drop shadow effect.

See also

  • More information about filter primitives, see the W3C Filter Effects Module.
  • If you’re wondering how to write SVG code to create SVG filters, Gaussian blur, shadow effects, lighting effects, or linear gradient and radial gradient, please visit the SVG Filters and Gradients article.
  • You can download the complete examples and data files from GitHub.
  • About downloading from GitHub and running examples, you find out from the How to Run the Examples section.
Subscribe to Aspose Product Updates

Get monthly newsletters & offers directly delivered to your mailbox.