1. 介绍
一些参考博客:
C#生成SVG涉及文字、线段、椭圆的示例
用C#解析渲染显示SVG矢量图转化格式保存
C#操作SVG矢量图-nuget库svg
开源库:https://github.com/svg-net/SVG
在NuGet上搜索SVG并安装:
2. 示例
引入的命名空间:
using Svg;
using Svg.Pathing;
using Svg.Transforms;
using System.Drawing;
下面分别给出示例代码和示意图。
2.1 文字
public static void DrawText()
{
SvgDocument doc = new SvgDocument();
var text = new SvgText
{
Text = "Hello Svg",
FontSize = 20,
Transforms = new SvgTransformCollection
{
new SvgTranslate(100, 100),//位置
new SvgRotate(10),//顺时针旋转10度
new SvgScale(2)//缩放
},
Fill = new SvgColourServer(Color.Blue)//颜色
};
doc.Children.Add(text);
var text2 = new SvgText
{
Text = "Hello World!",
FontSize = 15,
Transforms = new SvgTransformCollection
{
new SvgTranslate(0, 0),//位置
new SvgRotate(90),//顺时针旋转90度
new SvgScale(2)//缩放
},
Fill = new SvgColourServer(Color.Red)//颜色
};
doc.Children.Add(text2);
doc.Write(@"./文本.svg");
}
2.2 线段
public static void DrawLine()
{
SvgDocument doc = new SvgDocument();
var line = new SvgLine
{
StartX = new SvgUnit(0),
StartY = new SvgUnit(0),
EndX = new SvgUnit(100),
EndY = new SvgUnit(200),
StrokeWidth = 1,
Stroke = new SvgColourServer(Color.Black)
};
doc.Children.Add(line);
var line2 = new SvgLine
{
StartX = new SvgUnit(100),
StartY = new SvgUnit(0),
EndX = new SvgUnit(100),
EndY = new SvgUnit(100),
StrokeWidth = 1,
Stroke = new SvgColourServer(Color.Black)
};
doc.Children.Add(line2);
doc.Write(@"./线.svg");
}
2.3 圆
public static void DrawCircle()
{
SvgDocument doc = new SvgDocument();
var circle = new SvgCircle
{
Color = new SvgColourServer(Color.Blue),
CenterX = new SvgUnit(100),
CenterY = new SvgUnit(100),
StrokeWidth = 1,
Stroke = new SvgColourServer(Color.Black),
Radius = 50,
Opacity = 0.6f,
Fill = new SvgColourServer(Color.Green),
};
doc.Children.Add(circle);
doc.Write(@"./圆.svg");
}
2.4 椭圆
public static void DrawEllipse()
{
SvgDocument doc = new SvgDocument();
var ellipse = new SvgEllipse
{
Color = new SvgColourServer(Color.Blue),
CenterX = new SvgUnit(100),
CenterY = new SvgUnit(100),
StrokeWidth = 1,
Stroke = new SvgColourServer(Color.Black),
RadiusX = 80,
RadiusY = 50,
Opacity = 0.6f,
Fill = new SvgColourServer(Color.Green),
};
doc.Children.Add(ellipse);
doc.Write(@"./椭圆.svg");
}
2.5 多边形
public static void DrawPolygon()
{
//要绘制的图形的点坐标序列
var pts = new PointF[]
{
new PointF(100, 100),
new PointF(60, 150),
new PointF(150, 200),
new PointF(100, 300),
new PointF(300, 300),
new PointF(200, 100),
new PointF(100, 100),//和起点坐标相同,确保闭合
};
var pathData = new SvgPathSegmentList();
//按绝对坐标设置笔触起笔位置
var svgMove = new SvgMoveToSegment(false, pts[0]);
pathData.Add(svgMove);
//按绝对坐标添加线段
for (int i = 0; i < pts.Length; i++)
{
var line = new SvgLineSegment(false, pts[i]);
pathData.Add(line);
}
SvgPath path = new SvgPath
{
PathData = pathData,
StrokeWidth = 1,
Stroke = new SvgColourServer(Color.Black),
Opacity = 0.6f,
Fill = new SvgColourServer(Color.Green),
};
SvgDocument doc = new SvgDocument();
doc.Children.Add(path);
doc.Write(@"./多边形.svg");//保存
}