Path Builder – SVG Paths in C# erstellen

SVG Path mit Aspose.SVG erstellen

SVG paths gehören zu den leistungsstärksten SVG-Funktionen für benutzerdefinierte Vektorgrafiken, Kurven, Konturen und komplexe Formen. Mit Aspose.SVG Builder API können Entwickler SVG path elements in C# mit lesbarer fluent syntax erstellen, statt SVG path data strings manuell zu schreiben.

Dieser Artikel erklärt, wie Sie SVG paths in C# erstellen, komplexe Vektorgrafiken programmgesteuert aufbauen und SVG text paths mit Aspose.SVG for .NET verwenden.

Path Builder

Die Klasse PathBuilder vereinfacht das Erstellen von SVG paths durch Methoden für gängige SVG path commands wie M (move to), L (line to), C (cubic Bézier curve), Q (quadratic Bézier curve), A (arc) und Z (close path).

Die Aspose.SVG Builder API stellt SVGPathElementBuilder zum programmgesteuerten Erstellen von SVG-<path>-Elementen bereit. Mit PathBuilder lassen sich SVG path commands über fluent chained methods definieren.

SVG paths werden häufig verwendet für:

Builders within Builders

SVG Builder API verwendet verschachtelte builders, um komplexe SVG-Strukturen intuitiv zu definieren. Im folgenden Beispiel ist PathBuilder ein builder within a builder: SVGSVGElementBuilder erstellt das <svg>-Element, während PathBuilder das innere <path>-Element konstruiert.

1using Aspose.Svg.Builder;
2using System.Drawing;
3using System.IO;
 1// Create an SVG path element with line commands using SVG Path Builder in C#
 2
 3// Initialize an SVG document
 4using (SVGDocument document = new SVGDocument())
 5{
 6    // Create an <svg> element with specified width, height and viewBox, and add a <path> element to it
 7    SVGSVGElement svg = new SVGSVGElementBuilder()
 8        .Width(200).Height(200)
 9        .ViewBox(0, 0, 150, 150)
10
11        .AddPath(p => p
12        // 'D' method defines the 'd' attribute, which contains the path data
13        .D(d => d
14        // 'M' sets the starting point of the path (Move to x=50, y=50)
15        .M(50, 50)
16        // 'L' draws a line from the current point to the new point (Line to x=100, y=50)
17        .L(100, 50)
18        // Another 'L' to draw a line to a new point (Line to x=100, y=100)
19        .L(100, 100)
20        // 'Z' closes the path by drawing a line to the starting point
21        .Z())
22        // Sets the fill color of the path to teal
23        .Fill(Color.Teal))
24        .Build(document.FirstChild as SVGSVGElement);
25
26    // Save the SVG document
27    document.Save(Path.Combine(OutputDir, "path.svg"));
28}

Funktionsweise des Paths

In diesem Beispiel definiert AddPath() ein <path>-Element. Die Methode D() definiert SVG path data mit SVG path commands:

Die fluent syntax macht SVG path definitions leichter lesbar und wartbar.

Von PathBuilder unterstützte SVG Path Commands

PathBuilder unterstützt absolute und relative SVG path commands zum Erstellen von Linien, Kurven, Bögen und komplexen Vektorgrafiken.

CommandRelative CommandBeschreibung
MmAktuellen Punkt verschieben
LlGerade Linie zu einem Punkt zeichnen
HhHorizontale Linie zeichnen
VvVertikale Linie zeichnen
CcKubische Bézier-Kurve zeichnen
SsGlatte kubische Bézier-Kurve zeichnen
QqQuadratische Bézier-Kurve zeichnen
TtGlatte quadratische Bézier-Kurve zeichnen
AaElliptischen Bogen zeichnen
ZzAktuellen Path schließen

Benutzerdefinierte SVG Path Data hinzufügen

Path data kann auch direkt als String mit AddPathSegment() hinzugefügt werden.

1.D(d => d.AddPathSegment(
2    "M199 89 C206 66 235 25 270 30 286 38 298 59 310 73"
3))

Dieser Ansatz ist hilfreich, wenn vorhandene SVG path data importiert oder extern erzeugte SVG-Grafiken verwendet werden.

SVG Curves und Bézier Paths erstellen

SVG paths unterstützen quadratische und kubische Bézier curves für glatte Vektorgrafiken und komplexe Konturen.

 1using Aspose.Svg.Builder;
 2using System.Drawing;
 3using System.IO;
 4
 5using (SVGDocument document = new SVGDocument())
 6{
 7    // Create an <svg> element with specified width, height and viewBox, and add a <path> element to it
 8    SVGSVGElement svg = new SVGSVGElementBuilder()
 9        .Width(500).Height(500)
10        .ViewBox(0, 0, 400, 400)
11
12        .AddPath(p => p
13            .D(d => d
14            .M(80, 210)
15            .Q(95, 110, 200, 200)
16            .T(350, 200)
17        )
18        // Sets the fill color of the path to red
19        .Fill(Color.Red))
20        .Build(document.FirstChild as SVGSVGElement);
21
22    // Save the SVG document
23    document.Save(Path.Combine(OutputDir, "curve-path.svg"));
24}

In diesem Beispiel:

Curve commands werden häufig für Illustrationen, Diagramme, Signaturen und dekorative SVG-Grafiken verwendet.

SVG TextPath

SVG kann Text entlang eines durch <path> definierten Pfads platzieren. Dafür wird ein <textPath>-Element mit dem Attribut href verwendet.

1using Aspose.Svg.Builder;
2using System.Drawing;
3using System.IO;
 1// Create SVG text along a path using SVG Builder in C#
 2
 3// Initialize an SVG document
 4using (SVGDocument document = new SVGDocument())
 5{
 6    // Create an <svg> element with specified width, height, and viewBox, and add into it <path> elements
 7    SVGSVGElement svg = new SVGSVGElementBuilder()
 8        .Width(1200).Height(300)
 9        .ViewBox(0, 0, 1200, 300)
10
11        .AddPath(p => p.Id("Path1")
12            .Fill(f => f.None()).Stroke(Color.IndianRed).Transform(t => t.Translate(-100, 40))
13            .D(d => d.AddPathSegment("M 199 89 C 206 66 235 25 270 30 286 38 298 59 310 73 321 87 338 99 356 103 387 111 396 90 410 85"))
14         )
15
16        .AddPath(p => p.Id("Path2")
17            .Fill(f => f.None()).Stroke(Paint.None).Transform(t => t.Translate(400, -100))
18            .D(d => d.M(80, 210).Q(95, 110, 200, 200).T(400, 200)))
19
20
21         .AddText(t => t.FontSize(30).Fill(Color.Teal)
22             .AddTextPath(tp => tp
23                 .Href("#Path1")
24                 .AddContent("SVG textPath element")
25              )
26             .AddTextPath(tp => tp
27                  .Href("#Path2")
28                  .AddContent("SVG can place text along a path")
29              )
30         )
31
32        .Build(document.FirstChild as SVGSVGElement);
33
34    // Save the SVG document
35    document.Save(Path.Combine(OutputDir, "text-path.svg"));
36}

Im Beispiel werden zwei paths mit unterschiedlichen id-Attributen erstellt. Der erste path verwendet AddPathSegment(), der zweite M(), Q() und T(). Das SVG-Element <textPath> verweist auf die id des <path>-Elements und zeigt Text entlang dieses Pfads an:

Visualisierung der Datei text-path.svg mit Text entlang SVG-Kurven.

Auch hier werden builders within builders verwendet: SVGSVGElementBuilder erstellt das <svg>-Element, während verschachtelte builders <path>, <text> und <textPath> hinzufügen.

Häufige Fehler und Lösungen

ProblemMögliche UrsacheEmpfohlene Lösung
SVG path ist nicht sichtbarFehlende fill- oder stroke-StileFill() oder Stroke() anwenden
Path wirkt unvollständigPath ist nicht geschlossenZ() verwenden
Text folgt der Kurve nichtFalsche path referenceSicherstellen, dass Href() zu Id() passt
Kurven wirken verzerrtFalsche KontrollpunkteBézier-Kontrollpunkte anpassen
Importierte path data rendert nicht korrektUngültige SVG path syntaxSVG path string vor dem Import validieren

Quick Recipes

1. Einfaches Dreieck erstellen

 1using (SVGDocument document = new SVGDocument())
 2{
 3    SVGSVGElement svg = new SVGSVGElementBuilder()
 4        .Width(200).Height(200)
 5        .ViewBox(0, 0, 150, 150)
 6        .AddPath(p => p
 7            .D(d => d
 8            .M(50, 150)
 9            .L(150, 150)
10            .L(100, 50)
11            .Z())
12        .Fill(Color.Teal))
13        .Build(document.FirstChild as SVGSVGElement);
14    document.Save("triangle.svg");
15}

2. Path segment hinzufügen

1    .AddPath(p => p
2        .Fill(Color.IndianRed)
3        .D(d => d.AddPathSegment("M10 75 Q150 0 290 75"))
4        )

3. Mehrere Segmente kombinieren

 1    .AddPath(p => p
 2    .Fill(Color.CadetBlue)
 3    .Stroke(Color.Red)
 4    .StrokeWidth(2)
 5    .D(d => d
 6        .AddPathSegment("M40 120")
 7        .AddPathSegment("C70 20 140 20 170 120")
 8        .AddPathSegment("S270 220 300 120")
 9        .AddPathSegment("Q250 180 170 170")
10        .AddPathSegment("Q90 160 40 120")
11        )
12    )

Note: Das erste Recipe ist mit den weiter oben gezeigten using directives ein vollständiges Beispiel. Die anderen Recipes sind Fragmente, die in einen vollständigen SVG-Erstellungsworkflow eingebunden werden sollten.

FAQ

1. Ist PathBuilder besser als manuelle SVG path strings?
Für komplexe SVG-Grafiken ist PathBuilder meist leichter zu warten und zu debuggen als manuell zusammengesetzte path strings.

2. Warum SVG paths statt einfacher shapes verwenden?
SVG paths sind flexibler als einfache Elemente wie <rect> oder <circle> und können komplexe Vektorgrafiken, Kurven und zusammengesetzte Formen darstellen.

3. Kann ich vorhandene SVG path data in PathBuilder commands umwandeln?
Ja. Vorhandene d-Attributwerte können in fluent PathBuilder commands übertragen oder mit AddPathSegment() direkt eingefügt werden.

4. Sind SVG paths auflösungsunabhängig?
Ja. SVG paths sind vektorbasiert und skalieren ohne Qualitätsverlust.

5. Können SVG paths mehrere getrennte Formen enthalten?
Ja. Ein path kann mehrere subpaths enthalten, indem mehrere M commands verwendet werden.

6. Was ist der Unterschied zwischen relativen und absoluten SVG path commands?
Absolute commands verwenden feste SVG-Koordinaten, relative commands berechnen Positionen relativ zum aktuellen Zeichenpunkt.

Verwandte Ressourcen

Close
Loading

Analyzing your prompt, please hold on...

An error occurred while retrieving the results. Please refresh the page and try again.

Subscribe to Aspose Product Updates

Get monthly newsletters & offers directly delivered to your mailbox.