Rotate SVG – C# Examples

How to Rotate SVG – C# Code

Using Aspose.SVG for .NET library, you can perform a rotate transformation programmatically. This article covers C# examples for SVG rotation. It considers cases of using the rotate() function in the transform attribute and the transformation matrix – matrix(a,b,c,d,e,f).

Rotate() Function

The following C# code snippet demonstrates how to create an SVG <rect> element, set its attributes, and apply a transformation using the rotate() function for transform attribute.

  1. Create an instance of the SVGDocument class. The RootElement property points to the document’s root <svg> element.
  2. Create a <rect> element with attributes and add it to the <svg> element:
    • You can use the CreateElementNS() method to create an instance of the SVGRectElement class.
    • Call the SetAttribute() method to set attributes specifying position, size, fill, and transformation. Use the rotate() function for the transform attribute, which takes the angle to be rotated and the coordinates of the point to be rotated around. If coordinates are not specified, then the rotation will be performed around the point (0, 0) of the initial coordinate system.
    • To add the rectElement to svgElement, you can use the AppendChild() method.
  3. Call the Save() method to save the resulting SVG image to a local file specified by path.
 1using Aspose.Svg;
 2using System.IO;
 3...
 4
 5    // Create a new SVG document
 6    using (var document = new SVGDocument())
 7    {
 8        var svgElement = document.RootElement;
 9
10        // Create a rect element and set its attributes
11        var rectElement = (SVGRectElement)document.CreateElementNS("http://www.w3.org/2000/svg", "rect");
12        rectElement.X.BaseVal.Value = 150;
13        rectElement.Y.BaseVal.Value = 50;
14        rectElement.Width.BaseVal.Value = 100;
15        rectElement.Height.BaseVal.Value = 100;
16        rectElement.SetAttribute("fill", "purple");
17
18        // Apply rotate() function to the SVG
19        rectElement.SetAttribute("transform", "rotate(45)");
20
21        // Append the rect element to the SVG
22        svgElement.AppendChild(rectElement);
23
24        // Save the document
25        string outputPath = "rotate-svg-rect.svg";
26        document.Save(Path.Combine(OutputDir, outputPath));
27    }

The transformation rotates the rectangle 45 degrees around the point (0, 0) of the original coordinate system since the coordinates of the point around which the element needs to be rotated were not passed to the rotate() function. For clarity, the Figure shows the coordinate systems before and after rotation. This illustrates that the rotation transformation is done by rotating the coordinate system.

Text “Original rectangle (a) and image with the rotated rectangle (b).”

Rotate SVG Element – SVG Rotate around Center

The following C# code snippet demonstrates how to find a required SVG element in an existing SVG file and rotate it. You should follow a few steps:

  1. Load a source SVG file using one of the SVGDocument() constructors.
  2. Get root <svg> element of the document.
  3. Use the QuerySelector() method to find the first rectangle element to rotate. The QuerySelector(selector) method of the Element class allows you to get the first element within the document that matches the specified selector.
  4. Set a transform attribute with rotate(45, 100, 140) value for the rectangle element. This transformation rotates the element by an angle of 45 degrees (clockwise) around a specified point (center of selected rectangle) with coordinates (100, 140).
  5. Call the Save() method to save the resulting SVG image to a local file.
 1using Aspose.Svg;
 2using System.IO;
 3...
 4    // Load an SVG document from a file
 5    var document = new SVGDocument(Path.Combine(DataDir, "shapes.svg"));
 6
 7    // Get root <svg> element of the document
 8    var svgElement = document.RootElement;
 9
10    // Get <rect> element to rotate
11    var rectElement = svgElement.QuerySelector("rect") as SVGRectElement;
12
13    // Set a new "transform" attribute using rotate() function for the rectangle element
14    rectElement.SetAttribute("transform", "rotate(45, 100, 140)");
15
16    // Save the document
17    document.Save(Path.Combine(OutputDir, "rotate-element.svg"));

The following Figure shows the original SVG (a) and image with the rotated first rectangle element (b). This transformation changed the appearance of the rectangle relative to other elements. The rectangle’s position, width, and height remain the same, but it will be visually rotated around the specified point – in this case, the rectangle’s center.

Text “Original svg image (a) and image with the rotated first rectangle element (b).”

Note: To rotate an SVG element around its center or some other point, you must use the rotate(angle, cx, cy) function, which rotates the element by an angle around the point with coordinates (cx, cy). Determine (calculate) the position of the image center – its coordinates – and perform rotation.

Rotate SVG Element – Using SVG Builder

Here, we will look at the same example: rotating the first <rect> element within the shapes.svg file around its center. However, this time, we will accomplish this task using the SVG Builder. SVG Builder API offers developers a powerful tool for creating and updating SVG elements in a streamlined manner. In this code snippet:

 1using Aspose.Svg.Builder;
 2using System.Linq;
 3using System.IO;
 4...
 5    // Load an SVG document
 6    using (var document = new SVGDocument(Path.Combine(DataDir, "shapes.svg")))
 7    {
 8        // Find the first <rect> element for rotation
 9        var rect = document.GetElementsByTagName("rect").First() as SVGRectElement;
10
11        // Rotate the first <rect> element around its center using the SVGRectElementBuilder
12        new SVGRectElementBuilder()
13            .Transform(t => t.Rotate(45, 100, 140))
14            .Build(rect);
15        
16        // Save the document
17        document.Save(Path.Combine(OutputDir, "rotate-element-using-builder.svg"));
18    }

The Transform() method is part of the SVG Builder API, which allows developers to programmatically apply transformations to SVG elements. Transformations in SVG enable developers to modify SVG elements’ position, rotation, scale, and skew. The Transform() method typically takes one or more transformation functions as arguments, each specifying a particular type of transformation. These functions include:

The Transform() method allows for the chaining of multiple transformation functions to apply more complex transformations.

The article SVG Builder API explores the capabilities of the Aspose.SVG Builder API to create and modify SVG elements in C#. SVG Builder API is designed to streamline the creation and updating of SVG elements in C#. You will see the efficiency of Fluent Builder Pattern and mixins in SVG manipulation. You will learn about the classes and methods, specialized builders, and how they simplify SVG programming.

SVG Transform Matrix – Rotate Matrix

Here, we will look at the C# example for rotating an entire SVG image rather than a single its element and implement the transformation using a rotate matrix. Let’s look closer at the C# code for applying the rotate matrix.

  1. Load a source SVG file using one of the SVGDocument() constructors.
  2. Get root <svg> element of the document.
  1. Use the GetCTM() method of the SVGGraphicsElement class that returns the current transformation matrix (CTM) associated with the <svg> element. The CTM represents the cumulative transformations applied to the element and includes information about translation, rotation, scaling, and skewing that can be applied to the element.
  2. After obtaining the CTM, use the Rotate() method that post-multiplies a rotate transformation on the current matrix and returns the resulting matrix. The Rotate(angle) method takes only one argument – angle. This parameter is mandatory and represents the amount of rotation you want to apply.
  3. Construct a transformAttribute – a string representation of a 2D transformation matrix using the values from the modified transformation matrix transformationMatrix. The matrix notation is matrix(a, b, c, d, e, f).
  4. Call the SetAttribute() method to set the transform attribute of the <svg> element using the transformAttribute string.
  5. Call the Save() method to save the resulting SVG image to a local file.
 1using Aspose.Svg;
 2using System.IO;
 3...
 4
 5	// Load an SVG document
 6    using (var document = new SVGDocument(Path.Combine(DataDir, "shapes.svg")))
 7    {
 8        var svgElement = document.RootElement;
 9
10        // Get the transformation matrix associated with the svgElement
11        var transformationMatrix = svgElement.GetCTM();
12        transformationMatrix = transformationMatrix.Rotate(45);
13
14        // Apply the transformation matrix to the svgElement
15        var transformAttribute = "matrix(" + transformationMatrix.A + "," + transformationMatrix.B + ","
16            + transformationMatrix.C + "," + transformationMatrix.D + "," + transformationMatrix.E + ","
17            + transformationMatrix.F + ")";
18        svgElement.SetAttribute("transform", transformAttribute);
19
20        // Save the document
21        document.Save(Path.Combine(OutputDir, "rotate.svg"));
22    }

The following Figure shows the original SVG (a) and the rotated image (b).

Text “The Figure shows the original SVG (a) and the rotated image (b).”

See Also

  • 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.
  • To learn how to use a transformation matrix to rotate, scale, translate, and skew SVG graphics and consider SVG code examples, please go to the Transformation Matrix – SVG Code Examples article.
  • Read the SVG Transformation article to learn more and get SVG code examples for rotating, scaling, moving, and skewing SVG graphics using the SVG transform attribute.
Subscribe to Aspose Product Updates

Get monthly newsletters & offers directly delivered to your mailbox.