Analyzing your prompt, please hold on...
An error occurred while retrieving the results. Please refresh the page and try again.
Los SVG paths son una de las funciones SVG más potentes para crear gráficos vectoriales personalizados, curvas, contornos y formas complejas. Con Aspose.SVG Builder API, puede crear SVG path elements en C# con sintaxis fluida, sin escribir manualmente cadenas SVG path data.
Este artículo explica cómo crear SVG paths en C#, construir gráficos vectoriales complejos mediante programación y usar SVG text paths con Aspose.SVG for .NET.
La clase
PathBuilder simplifica la creación de SVG paths mediante métodos para comandos comunes como M, L, C, Q, A y Z.
Aspose.SVG Builder API proporciona
SVGPathElementBuilder para construir elementos SVG <path> mediante programación. Con PathBuilder, los comandos SVG path se definen mediante métodos encadenados.
Los SVG paths se usan para:
SVG Builder API usa builders anidados para definir estructuras SVG complejas. En el siguiente ejemplo, PathBuilder es un builder dentro de otro builder:
SVGSVGElementBuilder crea el elemento <svg> y PathBuilder construye el elemento <path> interno.
1using Aspose.Svg.Builder;
2using System.Drawing;
3using System.IO; 1// Create an SVG path element with line commands programmatically in C# using SVG Path Builder
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}En este ejemplo,
AddPath() define un elemento <path>. El método
D() define SVG path data con comandos SVG path:
La sintaxis fluida facilita leer y mantener definiciones SVG path.
PathBuilder admite comandos SVG path absolutos y relativos para crear líneas, curvas, arcos y gráficos vectoriales complejos.
| Command | Relative Command | Descripción |
|---|---|---|
M | m | Mover el punto actual |
L | l | Dibujar una línea recta |
H | h | Dibujar una línea horizontal |
V | v | Dibujar una línea vertical |
C | c | Dibujar una curva Bézier cúbica |
S | s | Dibujar una curva cúbica suave |
Q | q | Dibujar una curva Bézier cuadrática |
T | t | Dibujar una curva cuadrática suave |
A | a | Dibujar un arco elíptico |
Z | z | Cerrar el path actual |
Path data también puede agregarse directamente como cadena con AddPathSegment().
1.D(d => d.AddPathSegment(
2 "M199 89 C206 66 235 25 270 30 286 38 298 59 310 73"
3))Este enfoque es útil al importar SVG path data existente o trabajar con gráficos SVG generados externamente.
Los SVG paths admiten curvas Bézier cuadráticas y cúbicas para gráficos vectoriales suaves y contornos complejos.
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}En este ejemplo:
Q() crea una curva Bézier cuadrática;T() continúa automáticamente la curva suave.Los comandos de curva se usan en ilustraciones, gráficos, firmas y SVG decorativos.
SVG puede colocar texto a lo largo de un path definido por <path>. Esto se realiza con un elemento <textPath> y el atributo href.
1using Aspose.Svg.Builder;
2using System.Drawing;
3using System.IO; 1// Create SVG text path in C# using SVG Builder
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}En el ejemplo se crean dos paths con distintos atributos id. El primero usa AddPathSegment(), y el segundo usa M(), Q() y T(). El elemento SVG <textPath> referencia el id del <path> y muestra texto a lo largo de ese path:

También se usan builders within builders: SVGSVGElementBuilder crea <svg>, mientras builders anidados agregan <path>, <text> y <textPath>.
| Problema | Posible causa | Solución recomendada |
|---|---|---|
| El SVG path no es visible | Faltan estilos fill o stroke | Aplique Fill() o Stroke() |
| La forma del path parece incompleta | El path no está cerrado | Use Z() |
| El texto no sigue la curva | Referencia de path incorrecta | Asegure que Href() coincida con Id() |
| Las curvas aparecen distorsionadas | Puntos de control incorrectos | Ajuste los puntos de control Bézier |
| Path data importada no se renderiza bien | Sintaxis SVG path no válida | Valide la cadena SVG path antes de importar |
1. Crear un triángulo simple
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. Agregar un path segment
1 .AddPath(p => p
2 .Fill(Color.IndianRed)
3 .D(d => d.AddPathSegment("M10 75 Q150 0 290 75"))
4 )3. Combinar varios segmentos
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: La primera receta es un ejemplo completo si se usa con las directivas using mostradas antes. Las demás recetas son fragmentos para integrar en un flujo completo de creación SVG.
1. ¿PathBuilder es mejor que escribir SVG path strings manualmente?
Para gráficos SVG complejos, PathBuilder suele ser más fácil de mantener y depurar que concatenar cadenas path manualmente.
2. ¿Por qué usar SVG paths en lugar de shapes básicas?
SVG paths son más flexibles que <rect> o <circle> y pueden representar gráficos vectoriales complejos, curvas y formas compuestas.
3. ¿Puedo convertir SVG path data existente a comandos PathBuilder?
Sí. Los valores existentes del atributo d pueden traducirse a comandos PathBuilder o insertarse con AddPathSegment().
4. ¿Los SVG paths son independientes de la resolución?
Sí. Son vectoriales y escalan sin pérdida de calidad.
5. ¿Puede un SVG path contener varias formas desconectadas?
Sí. Un path puede contener varios subpaths usando varios comandos M.
6. ¿Cuál es la diferencia entre comandos relativos y absolutos?
Los comandos absolutos usan coordenadas fijas; los relativos calculan posiciones respecto al punto actual.
stroke y fill.Analyzing your prompt, please hold on...
An error occurred while retrieving the results. Please refresh the page and try again.