Element Builders – Create and Edit SVG Elements – C#
Element Builders in Aspose.SVG
Element Builders are software constructs or classes designed to make it easier to create or modify SVG elements. These builders typically follow design patterns, such as the Fluent Builder Pattern, which provide a fluent and expressive syntax when defining the attributes and structure of SVG elements.
In the Aspose.SVG Builder API, all element builders, such as SVGSVGElementBuilder, SVGGElementBuilder, and others, inherit from the core SVGElementBuilder class. This inheritance structure streamlines the process of creating and modifying SVG elements, ensuring consistency and efficiency across different types of elements.
Element builders provide the
Build(Document document
) method, enabling the creation of new SVG elements and their addition to an SVG document and the
Build(T element
) method for updating existing SVG elements.
This article delves into the Element Builders used in Aspose.SVG Builder API. You will see their efficiency in SVG manipulation. You will learn about the SVGSVGElementBuilder class, its specialized builders, and how they simplify SVG programming.
Creating New Elements
Aspose.SVG SVG Builder API employs the Fluent Builder Pattern, a design methodology that aligns perfectly with the need for simplicity, clarity, and versatility in SVG manipulation.
Fluent Builder Pattern
In the SVG Builder API the Fluent Builder Pattern is used to simplify the creation and updating of SVG elements, making the process intuitive and less error-prone. The essence of this pattern is methods that configure an SVG element and then return a builder object. This design provides a consistent and coherent way to link methods, which is especially effective at reducing the complexity associated with creating and managing SVG elements.
In this context, lambda expressions are used to improve the clarity and conciseness of the builder’s configuration methods. Lambda expressions allow you to define the attributes and styles of SVG elements in a detailed yet compact way. For example, when adding a circle element, the lambda expression provides an inline readable configuration:
1 var svgElement = new SVGSVGElementBuilder()
2 .AddCircle(circle => circle
3 .Cx(100).Cy(100).R(50)
4 .Fill(Color.Red).Stroke(Paint.None)
5 .StrokeWidth(2))
6 .Build();
Here, circle => circle.Cx(100).Cy(100).R(50).Fill(Color.Red).Stroke(Paint.None).StrokeWidth(2)
is a succinct way to configure the circle’s properties, such as its center, radius, fill, and stroke. This approach not only simplifies the element configuration but also enhances the code’s readability and maintainability.
Create SVG from Scratch
Here, we will explore a concise and elegant approach to crafting SVGs from scratch using C#.
1using Aspose.Svg.Builder;
2using System.Drawing;
3using System.IO;
4...
5 using (var document = new SVGDocument())
6 {
7 // Create an <svg> element with specified width, height and viewBox, and add into it other required elements
8 var svg = new SVGSVGElementBuilder()
9 .Width(700).Height(300)
10 .ViewBox(0, 0, 700, 300)
11
12 .AddG(g => g
13 .AddCircle(circle => circle.Cx(130).Cy(130).R(60).Fill(Paint.None).Stroke(Color.FromArgb(200, 0, 0)).StrokeWidth(70).StrokeDashArray(2,14))
14 .AddText("I can create SVG from scratch!", x: 270, y: 140, fontSize: 30, fill: Color.Teal)
15 )
16 .Build(document.FirstChild as SVGSVGElement);
17
18 // Save the document
19 document.Save(Path.Combine(OutputDir, "svg-from-scratch.svg"));
20 }
The example utilizes a Fluent Builder Pattern within SVGSVGElementBuilder to construct the SVG elements. This pattern provides an expressive and maintainable way to generate SVG documents compared to the approach described in the Edit SVG File article, which relies more on low-level DOM manipulation and explicit attribute setting.
So, SVG Builder API offers a flexible and efficient way to generate vector graphics in C#. By leveraging the Element Builders and Builder Pattern, you can streamline the process of creating SVGs from scratch. This approach:
- provides a more fluent and readable way to create complex structures, making the code easier to understand and maintain.
- reduces boilerplate code, as seen in the example where setting attributes like
cx
,cy
,r
,fill
, etc., are achieved with method calls directly on the builder.
Editing SVG
One powerful technique for programmatically editing SVGs is through the use of Element Builders.
Adding New Elements
Editing SVGs using element builders provides a powerful and flexible approach to manipulating vector graphics programmatically. In the following example, we take an existing SVG file, add some elements to it, and save it:
1using Aspose.Svg.Builder;
2using System.Drawing;
3using System.IO;
4...
5 string documentPath = Path.Combine(DataDir, "circles.svg");
6
7 using (var document = new SVGDocument(documentPath))
8 {
9 // Create a new <g> (group) element using SVGGElementBuilder and set attributes
10 var gElement = new SVGGElementBuilder()
11 .Fill(Paint.None).Stroke(Color.FromArgb(80, 132, 132)).StrokeWidth(10)
12
13 // Add <circle> and <polyline> element configurations
14 .AddCircle(c => c.Cx(350).Cy(70).R(50))
15 .AddPolyline(points: new double[] { 125, 130, 275, 180, 425, 130 })
16 .Build(document);
17
18 // Append the newly created <g> element to the root <svg> element
19 document.RootElement.AppendChild(gElement);
20
21 // Save the document
22 document.Save(Path.Combine(OutputDir, "circles-edited.svg"));
23 }
In this example:
- a new
<g>
(group) element is created using the SVGGElementBuilder. Attributes such asfill
,stroke
, andstroke-width
are set for this group element. - within the
<g>
element, the<circle>
and the<polyline>
element are configured using the Fluent Builder Pattern. - once the child elements are configured, the
Build(
Document document
) method is called on theSVGGElementBuilder
to construct the<g>
element with its child elements. - the newly created
<g>
element is added as a child to the root<svg>
element of the SVG document.
Figure (a) shows a visualization of the original circles.svg file, and figure (b) shows an image of the edited circles-edited.svg file with added circle and polyline elements.
Modifying Existing Elements
In the following C# example, we update an existing SVG document by changing the fill and stroke color of the first SVG <circle>
element in the document:
1using Aspose.Svg.Builder;
2using System.Drawing;
3using System.Linq;
4using System.IO;
5...
6 string documentPath = Path.Combine(DataDir, "circles.svg");
7
8 using (var document = new SVGDocument(documentPath))
9 {
10 // Find the first <circle> element in the document
11 var circle = document.GetElementsByTagName("circle").First() as SVGCircleElement;
12
13 // Modify the first <circle> element using SVGCircleElementBuilder
14 new SVGCircleElementBuilder()
15 .Stroke(Color.DarkRed).Fill(Color.LightGray)
16
17 // The first <circle> element is now updated with new configurations
18 .Build(circle);
19
20 // Save the document
21 document.Save(Path.Combine(OutputDir, "circles-modified.svg"));
22 }
Element builders offer the
Build(T element
) method for updating existing SVG elements, allowing modifications to their attributes or styles. Figure (a) shows the original circles.svg file, and figure (b) shows an image of the modified circles-modified.svg file with the recolored first circle element.
Example of Using Element Builders
The following code snippet shows how to use element builders to create an SVG document with various SVG shape elements.
1using Aspose.Svg.Builder;
2using System.Drawing;
3using System.IO;
4...
5 var svgContent = "<svg xmlns=\"http://www.w3.org/2000/svg\"></svg>";
6 using (var document = new SVGDocument(svgContent, "."))
7 {
8 var svg = new SVGSVGElementBuilder()
9 .Width(100, LengthType.Percentage).Height(100, LengthType.Percentage)
10 .ViewBox(0, 0, 800, 800)
11
12 .AddG(g => g.FontSize(20).TextAnchor(TextAnchor.End)
13 .AddText("<rect>", y: 30)
14 .AddText("<circle>", y: 70)
15 .AddText("<ellipse>", y: 110)
16 .AddText("<line>", y: 150)
17 .AddText("<polyline>", x: 300, y: 30)
18 .AddText("<polygon>", x: 300, y: 70)
19 .AddText("<path>", x: 300, y: 110)
20 )
21
22 .AddG(gg => gg.Fill(Color.Teal).StrokeWidth(3)
23 .AddRect(r => r.X(35).Y(5).Width(30).Height(30))
24 .AddCircle(c => c.Cx(50).Cy(60).R(17))
25 .AddEllipse(e => e.Cx(50).Cy(100).Rx(25).Ry(12))
26 .AddLine(l => l.X1(30).X2(70).Y1(140).Y2(140).Stroke(Color.Teal))
27 )
28 .AddG(ggg => ggg.Fill(Paint.None).StrokeWidth(3).Stroke(Color.Teal).Transform(t => t.Translate(300, -160))
29 .AddPolygon(points: new double[] { 30, 215, 90, 215, 120, 230, 70, 240, 30, 215 }, fill: Color.Teal)
30 .AddPolyline(points: new double[] { 30, 200, 65, 170, 90, 190, 120, 180 })
31 .AddPath(d: path => path.M(30, 275).Q(55, 250, 70, 250).T(80, 275).T(120,260))
32 )
33
34 .Build(document.FirstChild as SVGSVGElement);
35 document.Save(Path.Combine(OutputDir, "svg-elements.svg"));
36 }
Element builders provide a fluent and expressive syntax for constructing SVG elements, enhancing code readability and maintainability. In this example, the Element builder, such as SVGSVGElementBuilder,
is employed to construct an SVG element with width
, height
, and viewBox
attributes. The Fluent Builder Pattern is then used to create shapes like rectangles, circles, ellipses, lines, polylines, polygons, and paths, each positioned and styled accordingly within <g>
elements.
See also
- In the Edit SVG File article, you cam learn how to edit SVG using Aspose.SVG for .NET library and consider detailed C# examples of how to add elements to an SVG document and edit them.
- Please visit the Path Builder article to learn how to use Path Builder to programmatically create SVG paths, a group of commands for drawing various outlines or shapes by combining SVG lines, SVG arcs, and Bezier curves.
- The Rule Builder article is about the RuleBuilder class, which is a builder class for constructing CSS style rules in an SVG document.
- The
Paint Builder article is about PaintBuilder, a builder class for creating paint values for SVG elements. This class is used to specify the value of the
stroke
orfill
attributes for various SVG shapes and elements when filling them with paint, pattern, or gradient.