安裝
先使用 NuGet 安裝 Svg 套件,或是使用 .NET CLI 執行以下指令安裝
dotnet add package Svg
C# 繪製 svg 向量圖片
產生長寬 100x100 的 svg 圖片:
var svgDocument = new SvgDocument
{
Width = 100, // 指定圖片寬度
Height = 100, // 指定圖片高度
};
svgDocument.Write("output.svg");
矩形
var svgDocument = new SvgDocument
{
Width = 100, // 指定圖片寬度
Height = 100, // 指定圖片高度
};
// 產生矩形
var rectangle = new SvgRectangle
{
X = 0, // 左上角 X 座標
Y = 0, // 左上角 Y 座標
Width = 100, // 寬度
Height = 100, // 高度
Fill = new SvgColourServer(Color.Red), // 填滿顏色
Stroke = new SvgColourServer(Color.Black), // 邊框顏色
StrokeWidth = 1, // 邊框寬度
};
svgDocument.Children.Add(rectangle); // 加入矩形
svgDocument.Write("output.svg");
圓形
var circle = new SvgCircle
{
CenterX = 50, // 圓心 X 座標
CenterY = 50, // 圓心 Y 座標
Radius = 40, // 半徑
Fill = new SvgColourServer(Color.Blue), // 填滿顏色
Stroke = new SvgColourServer(Color.Black), // 邊框顏色
StrokeWidth = 1, // 邊框寬度
};
svgDocument.Children.Add(circle); // 加入圓形
橢圓形
var ellipse = new SvgEllipse
{
CenterX = 50, // 圓心 X 座標
CenterY = 50, // 圓心 Y 座標
RadiusX = 40, // X 軸半徑
RadiusY = 20, // Y 軸半徑
Fill = new SvgColourServer(Color.Green), // 填滿顏色
Stroke = new SvgColourServer(Color.Black), // 邊框顏色
StrokeWidth = 1, // 邊框寬度
};
svgDocument.Children.Add(ellipse); // 加入橢圓
橢圓形
var line = new SvgLine
{
StartX = 0, // 起點 X 座標
StartY = 0, // 起點 Y 座標
EndX = 100, // 終點 X 座標
EndY = 100, // 終點 Y 座標
Stroke = new SvgColourServer(Color.Black), // 顏色
StrokeWidth = 1, // 寬度
};
svgDocument.Children.Add(line); // 加入直線
多邊形
var polygon = new SvgPolygon
{
Points = new SvgPointCollection // 多邊形的頂點
{
new SvgUnit(0), new SvgUnit(0),
new SvgUnit(50), new SvgUnit(0),
new SvgUnit(100), new SvgUnit(50),
new SvgUnit(50), new SvgUnit(100),
new SvgUnit(0), new SvgUnit(100),
new SvgUnit(50), new SvgUnit(50),
},
Fill = new SvgColourServer(Color.Yellow), // 填滿顏色
Stroke = new SvgColourServer(Color.Black), // 邊框顏色
StrokeWidth = 1, // 邊框寬度
};
svgDocument.Children.Add(polygon); // 加入多邊形
文字
var text = new SvgText
{
X = new SvgUnitCollection { new SvgUnit(0) }, // 文字左上角 X
Y = new SvgUnitCollection { new SvgUnit(20) }, // 文字左上角 Y
FontSize = 12, // 字體大小
Fill = new SvgColourServer(Color.Black), // 文字顏色
Text = "Hello World!", // 文字內容
FontFamily = "Arial", // 字體
FontWeight = SvgFontWeight.Bold, // 粗體
FontStyle = SvgFontStyle.Italic, // 斜體
TextDecoration = SvgTextDecoration.Underline, // 底線
TextAnchor = SvgTextAnchor.Start, // 文字對齊
};
svgDocument.Children.Add(text); // 加入文字
圖片
var image = new SvgImage
{
X = 36, // 左上角 X 座標
Y = 36, // 左上角 Y 座標
Width = 24, // 寬度
Height = 24, // 高度
Href = "C:\\Users\\ruyut\\Pictures\\ico.ico", // 圖片路徑或是網址
};
svgDocument.Children.Add(image); // 加入圖片
參考資料:
SVG.NET Documentation
留言
張貼留言
如果有任何問題、建議、想說的話或文章題目推薦,都歡迎留言或來信: a@ruyut.com