├── .gitattributes ├── .gitignore ├── README.md ├── Walterlv.Tools.SvgPathCombiner.sln ├── Walterlv.Tools.SvgPathCombiner ├── App.xaml ├── App.xaml.cs ├── AssemblyInfo.cs ├── MainWindow.xaml ├── MainWindow.xaml.cs ├── MiniLanguages │ ├── MiniLanguageParser.cs │ ├── Syntax │ │ ├── ASyntax.cs │ │ ├── CSyntax.cs │ │ ├── FSyntax.cs │ │ ├── HSyntax.cs │ │ ├── LSyntax.cs │ │ ├── MSyntax.cs │ │ ├── PathSyntax.cs │ │ ├── QSyntax.cs │ │ ├── SSyntax.cs │ │ ├── TSyntax.cs │ │ ├── VSyntax.cs │ │ └── ZSyntax.cs │ └── Visitors │ │ ├── CommandContext.cs │ │ ├── IPathSyntaxVisitor.cs │ │ └── PathSyntaxVisitor.cs ├── PathTransformVisitor.cs ├── SvgPathCombiner.cs └── Walterlv.Tools.SvgPathCombiner.csproj └── docs └── img └── main_screenshot.png /.gitattributes: -------------------------------------------------------------------------------- 1 | ############################################################################### 2 | # Set default behavior to automatically normalize line endings. 3 | ############################################################################### 4 | * text=auto 5 | 6 | ############################################################################### 7 | # Set default behavior for command prompt diff. 8 | # 9 | # This is need for earlier builds of msysgit that does not have it on by 10 | # default for csharp files. 11 | # Note: This is only used by command line 12 | ############################################################################### 13 | #*.cs diff=csharp 14 | 15 | ############################################################################### 16 | # Set the merge driver for project and solution files 17 | # 18 | # Merging from the command prompt will add diff markers to the files if there 19 | # are conflicts (Merging from VS is not affected by the settings below, in VS 20 | # the diff markers are never inserted). Diff markers may cause the following 21 | # file extensions to fail to load in VS. An alternative would be to treat 22 | # these files as binary and thus will always conflict and require user 23 | # intervention with every merge. To do so, just uncomment the entries below 24 | ############################################################################### 25 | #*.sln merge=binary 26 | #*.csproj merge=binary 27 | #*.vbproj merge=binary 28 | #*.vcxproj merge=binary 29 | #*.vcproj merge=binary 30 | #*.dbproj merge=binary 31 | #*.fsproj merge=binary 32 | #*.lsproj merge=binary 33 | #*.wixproj merge=binary 34 | #*.modelproj merge=binary 35 | #*.sqlproj merge=binary 36 | #*.wwaproj merge=binary 37 | 38 | ############################################################################### 39 | # behavior for image files 40 | # 41 | # image files are treated as binary by default. 42 | ############################################################################### 43 | #*.jpg binary 44 | #*.png binary 45 | #*.gif binary 46 | 47 | ############################################################################### 48 | # diff behavior for common document formats 49 | # 50 | # Convert binary document formats to text before diffing them. This feature 51 | # is only available from the command line. Turn it on by uncommenting the 52 | # entries below. 53 | ############################################################################### 54 | #*.doc diff=astextplain 55 | #*.DOC diff=astextplain 56 | #*.docx diff=astextplain 57 | #*.DOCX diff=astextplain 58 | #*.dot diff=astextplain 59 | #*.DOT diff=astextplain 60 | #*.pdf diff=astextplain 61 | #*.PDF diff=astextplain 62 | #*.rtf diff=astextplain 63 | #*.RTF diff=astextplain 64 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | ## 4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore 5 | 6 | # User-specific files 7 | *.rsuser 8 | *.suo 9 | *.user 10 | *.userosscache 11 | *.sln.docstates 12 | 13 | # User-specific files (MonoDevelop/Xamarin Studio) 14 | *.userprefs 15 | 16 | # Mono auto generated files 17 | mono_crash.* 18 | 19 | # Build results 20 | [Dd]ebug/ 21 | [Dd]ebugPublic/ 22 | [Rr]elease/ 23 | [Rr]eleases/ 24 | x64/ 25 | x86/ 26 | [Ww][Ii][Nn]32/ 27 | [Aa][Rr][Mm]/ 28 | [Aa][Rr][Mm]64/ 29 | bld/ 30 | [Bb]in/ 31 | [Oo]bj/ 32 | [Oo]ut/ 33 | [Ll]og/ 34 | [Ll]ogs/ 35 | 36 | # Visual Studio 2015/2017 cache/options directory 37 | .vs/ 38 | # Uncomment if you have tasks that create the project's static files in wwwroot 39 | #wwwroot/ 40 | 41 | # Visual Studio 2017 auto generated files 42 | Generated\ Files/ 43 | 44 | # MSTest test Results 45 | [Tt]est[Rr]esult*/ 46 | [Bb]uild[Ll]og.* 47 | 48 | # NUnit 49 | *.VisualState.xml 50 | TestResult.xml 51 | nunit-*.xml 52 | 53 | # Build Results of an ATL Project 54 | [Dd]ebugPS/ 55 | [Rr]eleasePS/ 56 | dlldata.c 57 | 58 | # Benchmark Results 59 | BenchmarkDotNet.Artifacts/ 60 | 61 | # .NET Core 62 | project.lock.json 63 | project.fragment.lock.json 64 | artifacts/ 65 | 66 | # ASP.NET Scaffolding 67 | ScaffoldingReadMe.txt 68 | 69 | # StyleCop 70 | StyleCopReport.xml 71 | 72 | # Files built by Visual Studio 73 | *_i.c 74 | *_p.c 75 | *_h.h 76 | *.ilk 77 | *.meta 78 | *.obj 79 | *.iobj 80 | *.pch 81 | *.pdb 82 | *.ipdb 83 | *.pgc 84 | *.pgd 85 | *.rsp 86 | *.sbr 87 | *.tlb 88 | *.tli 89 | *.tlh 90 | *.tmp 91 | *.tmp_proj 92 | *_wpftmp.csproj 93 | *.log 94 | *.vspscc 95 | *.vssscc 96 | .builds 97 | *.pidb 98 | *.svclog 99 | *.scc 100 | 101 | # Chutzpah Test files 102 | _Chutzpah* 103 | 104 | # Visual C++ cache files 105 | ipch/ 106 | *.aps 107 | *.ncb 108 | *.opendb 109 | *.opensdf 110 | *.sdf 111 | *.cachefile 112 | *.VC.db 113 | *.VC.VC.opendb 114 | 115 | # Visual Studio profiler 116 | *.psess 117 | *.vsp 118 | *.vspx 119 | *.sap 120 | 121 | # Visual Studio Trace Files 122 | *.e2e 123 | 124 | # TFS 2012 Local Workspace 125 | $tf/ 126 | 127 | # Guidance Automation Toolkit 128 | *.gpState 129 | 130 | # ReSharper is a .NET coding add-in 131 | _ReSharper*/ 132 | *.[Rr]e[Ss]harper 133 | *.DotSettings.user 134 | 135 | # TeamCity is a build add-in 136 | _TeamCity* 137 | 138 | # DotCover is a Code Coverage Tool 139 | *.dotCover 140 | 141 | # AxoCover is a Code Coverage Tool 142 | .axoCover/* 143 | !.axoCover/settings.json 144 | 145 | # Coverlet is a free, cross platform Code Coverage Tool 146 | coverage*.json 147 | coverage*.xml 148 | coverage*.info 149 | 150 | # Visual Studio code coverage results 151 | *.coverage 152 | *.coveragexml 153 | 154 | # NCrunch 155 | _NCrunch_* 156 | .*crunch*.local.xml 157 | nCrunchTemp_* 158 | 159 | # MightyMoose 160 | *.mm.* 161 | AutoTest.Net/ 162 | 163 | # Web workbench (sass) 164 | .sass-cache/ 165 | 166 | # Installshield output folder 167 | [Ee]xpress/ 168 | 169 | # DocProject is a documentation generator add-in 170 | DocProject/buildhelp/ 171 | DocProject/Help/*.HxT 172 | DocProject/Help/*.HxC 173 | DocProject/Help/*.hhc 174 | DocProject/Help/*.hhk 175 | DocProject/Help/*.hhp 176 | DocProject/Help/Html2 177 | DocProject/Help/html 178 | 179 | # Click-Once directory 180 | publish/ 181 | 182 | # Publish Web Output 183 | *.[Pp]ublish.xml 184 | *.azurePubxml 185 | # Note: Comment the next line if you want to checkin your web deploy settings, 186 | # but database connection strings (with potential passwords) will be unencrypted 187 | *.pubxml 188 | *.publishproj 189 | 190 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 191 | # checkin your Azure Web App publish settings, but sensitive information contained 192 | # in these scripts will be unencrypted 193 | PublishScripts/ 194 | 195 | # NuGet Packages 196 | *.nupkg 197 | # NuGet Symbol Packages 198 | *.snupkg 199 | # The packages folder can be ignored because of Package Restore 200 | **/[Pp]ackages/* 201 | # except build/, which is used as an MSBuild target. 202 | !**/[Pp]ackages/build/ 203 | # Uncomment if necessary however generally it will be regenerated when needed 204 | #!**/[Pp]ackages/repositories.config 205 | # NuGet v3's project.json files produces more ignorable files 206 | *.nuget.props 207 | *.nuget.targets 208 | 209 | # Microsoft Azure Build Output 210 | csx/ 211 | *.build.csdef 212 | 213 | # Microsoft Azure Emulator 214 | ecf/ 215 | rcf/ 216 | 217 | # Windows Store app package directories and files 218 | AppPackages/ 219 | BundleArtifacts/ 220 | Package.StoreAssociation.xml 221 | _pkginfo.txt 222 | *.appx 223 | *.appxbundle 224 | *.appxupload 225 | 226 | # Visual Studio cache files 227 | # files ending in .cache can be ignored 228 | *.[Cc]ache 229 | # but keep track of directories ending in .cache 230 | !?*.[Cc]ache/ 231 | 232 | # Others 233 | ClientBin/ 234 | ~$* 235 | *~ 236 | *.dbmdl 237 | *.dbproj.schemaview 238 | *.jfm 239 | *.pfx 240 | *.publishsettings 241 | orleans.codegen.cs 242 | 243 | # Including strong name files can present a security risk 244 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 245 | #*.snk 246 | 247 | # Since there are multiple workflows, uncomment next line to ignore bower_components 248 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 249 | #bower_components/ 250 | 251 | # RIA/Silverlight projects 252 | Generated_Code/ 253 | 254 | # Backup & report files from converting an old project file 255 | # to a newer Visual Studio version. Backup files are not needed, 256 | # because we have git ;-) 257 | _UpgradeReport_Files/ 258 | Backup*/ 259 | UpgradeLog*.XML 260 | UpgradeLog*.htm 261 | ServiceFabricBackup/ 262 | *.rptproj.bak 263 | 264 | # SQL Server files 265 | *.mdf 266 | *.ldf 267 | *.ndf 268 | 269 | # Business Intelligence projects 270 | *.rdl.data 271 | *.bim.layout 272 | *.bim_*.settings 273 | *.rptproj.rsuser 274 | *- [Bb]ackup.rdl 275 | *- [Bb]ackup ([0-9]).rdl 276 | *- [Bb]ackup ([0-9][0-9]).rdl 277 | 278 | # Microsoft Fakes 279 | FakesAssemblies/ 280 | 281 | # GhostDoc plugin setting file 282 | *.GhostDoc.xml 283 | 284 | # Node.js Tools for Visual Studio 285 | .ntvs_analysis.dat 286 | node_modules/ 287 | 288 | # Visual Studio 6 build log 289 | *.plg 290 | 291 | # Visual Studio 6 workspace options file 292 | *.opt 293 | 294 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 295 | *.vbw 296 | 297 | # Visual Studio LightSwitch build output 298 | **/*.HTMLClient/GeneratedArtifacts 299 | **/*.DesktopClient/GeneratedArtifacts 300 | **/*.DesktopClient/ModelManifest.xml 301 | **/*.Server/GeneratedArtifacts 302 | **/*.Server/ModelManifest.xml 303 | _Pvt_Extensions 304 | 305 | # Paket dependency manager 306 | .paket/paket.exe 307 | paket-files/ 308 | 309 | # FAKE - F# Make 310 | .fake/ 311 | 312 | # CodeRush personal settings 313 | .cr/personal 314 | 315 | # Python Tools for Visual Studio (PTVS) 316 | __pycache__/ 317 | *.pyc 318 | 319 | # Cake - Uncomment if you are using it 320 | # tools/** 321 | # !tools/packages.config 322 | 323 | # Tabs Studio 324 | *.tss 325 | 326 | # Telerik's JustMock configuration file 327 | *.jmconfig 328 | 329 | # BizTalk build output 330 | *.btp.cs 331 | *.btm.cs 332 | *.odx.cs 333 | *.xsd.cs 334 | 335 | # OpenCover UI analysis results 336 | OpenCover/ 337 | 338 | # Azure Stream Analytics local run output 339 | ASALocalRun/ 340 | 341 | # MSBuild Binary and Structured Log 342 | *.binlog 343 | 344 | # NVidia Nsight GPU debugger configuration file 345 | *.nvuser 346 | 347 | # MFractors (Xamarin productivity tool) working folder 348 | .mfractor/ 349 | 350 | # Local History for Visual Studio 351 | .localhistory/ 352 | 353 | # BeatPulse healthcheck temp database 354 | healthchecksdb 355 | 356 | # Backup folder for Package Reference Convert tool in Visual Studio 2017 357 | MigrationBackup/ 358 | 359 | # Ionide (cross platform F# VS Code tools) working folder 360 | .ionide/ 361 | 362 | # Fody - auto-generated XML schema 363 | FodyWeavers.xsd -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # SVG 路径化 2 | 3 | 当你有如下需求之一时,这个工具适合你: 4 | 5 | 1. 设计师给你一个 SVG 文件,你需要在 XAML 系的开发框架中使用; 6 | 2. 你需要生成一个 Geometry,以便自己组装图形。 7 | 8 | ![主界面截图](/docs/img/main_screenshot.png) 9 | 10 | 本工具基于 [ElinamLLC/SharpVectors](https://github.com/ElinamLLC/SharpVectors)。不过 SharpVectors 适用于 SVG 转 XAML 的全场景,在部分小场景下却效率不高。本工具旨在解决这一小部分问题。 11 | 12 | ## 相似的项目 13 | 14 | - [dotnet-campus/dotnetCampus.Svg2XamlTool: Svg to WPF XAML file. 拖入 SVG 文件,即可转换为 XAML 可用代码](https://github.com/dotnet-campus/dotnetCampus.Svg2XamlTool ) 15 | 16 | ## 第三方引用 17 | 18 | - SharpVectors https://github.com/ElinamLLC/SharpVectors 19 | -------------------------------------------------------------------------------- /Walterlv.Tools.SvgPathCombiner.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 16 4 | VisualStudioVersion = 16.0.31105.61 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Walterlv.Tools.SvgPathCombiner", "Walterlv.Tools.SvgPathCombiner\Walterlv.Tools.SvgPathCombiner.csproj", "{FF4FED3C-C3DE-413E-8135-79EAE7B6C4E6}" 7 | EndProject 8 | Global 9 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 10 | Debug|Any CPU = Debug|Any CPU 11 | Release|Any CPU = Release|Any CPU 12 | EndGlobalSection 13 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 14 | {FF4FED3C-C3DE-413E-8135-79EAE7B6C4E6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 15 | {FF4FED3C-C3DE-413E-8135-79EAE7B6C4E6}.Debug|Any CPU.Build.0 = Debug|Any CPU 16 | {FF4FED3C-C3DE-413E-8135-79EAE7B6C4E6}.Release|Any CPU.ActiveCfg = Release|Any CPU 17 | {FF4FED3C-C3DE-413E-8135-79EAE7B6C4E6}.Release|Any CPU.Build.0 = Release|Any CPU 18 | EndGlobalSection 19 | GlobalSection(SolutionProperties) = preSolution 20 | HideSolutionNode = FALSE 21 | EndGlobalSection 22 | GlobalSection(ExtensibilityGlobals) = postSolution 23 | SolutionGuid = {F69E2395-A509-48B3-ACB6-4410A8C418C0} 24 | EndGlobalSection 25 | EndGlobal 26 | -------------------------------------------------------------------------------- /Walterlv.Tools.SvgPathCombiner/App.xaml: -------------------------------------------------------------------------------- 1 |  6 | 7 | 8 | 9 | 10 | -------------------------------------------------------------------------------- /Walterlv.Tools.SvgPathCombiner/App.xaml.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Configuration; 4 | using System.Data; 5 | using System.Linq; 6 | using System.Threading.Tasks; 7 | using System.Windows; 8 | 9 | namespace Walterlv.Tools 10 | { 11 | public partial class App : Application 12 | { 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /Walterlv.Tools.SvgPathCombiner/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Windows; 2 | 3 | [assembly: ThemeInfo( 4 | ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located 5 | //(used if a resource is not found in the page, 6 | // or application resource dictionaries) 7 | ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located 8 | //(used if a resource is not found in the page, 9 | // app, or any theme specific resource dictionaries) 10 | )] 11 | -------------------------------------------------------------------------------- /Walterlv.Tools.SvgPathCombiner/MainWindow.xaml: -------------------------------------------------------------------------------- 1 |  11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 82 | 83 | 84 | 88 | 89 | 90 | 91 | 96 | 97 | 98 | 99 | 100 | -------------------------------------------------------------------------------- /Walterlv.Tools.SvgPathCombiner/MainWindow.xaml.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Diagnostics.CodeAnalysis; 4 | using System.Drawing.Drawing2D; 5 | using System.Globalization; 6 | using System.IO; 7 | using System.Linq; 8 | using System.Text; 9 | using System.Text.RegularExpressions; 10 | using System.Threading.Tasks; 11 | using System.Windows; 12 | using System.Windows.Controls; 13 | using System.Windows.Data; 14 | using System.Windows.Documents; 15 | using System.Windows.Input; 16 | using System.Windows.Media; 17 | using System.Windows.Media.Imaging; 18 | using System.Windows.Navigation; 19 | 20 | using ICSharpCode.AvalonEdit; 21 | using ICSharpCode.AvalonEdit.Folding; 22 | using ICSharpCode.AvalonEdit.Highlighting; 23 | using ICSharpCode.AvalonEdit.Indentation; 24 | using ICSharpCode.AvalonEdit.Search; 25 | 26 | using SharpVectors.Converters; 27 | using SharpVectors.Dom.Svg; 28 | using SharpVectors.Renderers.Wpf; 29 | 30 | namespace Walterlv.Tools 31 | { 32 | public partial class MainWindow : Window 33 | { 34 | public MainWindow() 35 | { 36 | InitializeComponent(); 37 | 38 | InitializeTextEditor(BeforeTextEditor); 39 | } 40 | 41 | private void BeforeBorder_DragOver(object sender, DragEventArgs e) 42 | { 43 | if (!TryGetSvgFileFromDataObject(e.Data, out _)) 44 | { 45 | e.Effects = DragDropEffects.None; 46 | e.Handled = true; 47 | } 48 | } 49 | 50 | private void BeforeBorder_Drop(object sender, DragEventArgs e) 51 | { 52 | if (TryGetSvgFileFromDataObject(e.Data, out var svgFile)) 53 | { 54 | var text = File.ReadAllText(svgFile.FullName); 55 | 56 | var rawReader = new FileSvgReader(new WpfDrawingSettings 57 | { 58 | EnsureViewboxSize = false, 59 | EnsureViewboxPosition = false, 60 | }) 61 | { 62 | SaveXaml = false, 63 | }; 64 | var reader = new FileSvgReader(new WpfDrawingSettings 65 | { 66 | TextAsGeometry = true, 67 | IncludeRuntime = false, 68 | IgnoreRootViewbox = true, 69 | EnsureViewboxSize = false, 70 | EnsureViewboxPosition = false, 71 | CultureInfo = CultureInfo.InvariantCulture, 72 | OptimizePath = true, 73 | }) 74 | { 75 | SaveXaml = true, 76 | }; 77 | var drawing = rawReader.Read(new StringReader(text)); 78 | reader.Read(new StringReader(text)); 79 | var xamlBuilder = new StringBuilder(); 80 | reader.Save(new StringWriter(xamlBuilder)); 81 | var xaml = Regex.Replace(xamlBuilder.ToString(), @" x:Name="".+?""", ""); 82 | 83 | BeforeDrawingImage.Drawing = drawing; 84 | BeforeTextEditor.Text = xaml; 85 | 86 | if (SvgPathCombiner.TryGuessSvgDrawingViewbox(drawing, out var viewbox)) 87 | { 88 | BeforePathBorder.Width = viewbox.Width; 89 | BeforePathBorder.Height = viewbox.Height; 90 | AfterPathBorder.Width = viewbox.Width; 91 | AfterPathBorder.Height = viewbox.Height; 92 | } 93 | else 94 | { 95 | BeforePathBorder.Width = double.NaN; 96 | BeforePathBorder.Height = double.NaN; 97 | AfterPathBorder.Width = double.NaN; 98 | AfterPathBorder.Height = double.NaN; 99 | } 100 | 101 | var pathData = SvgPathCombiner.Combine(drawing); 102 | if (pathData is not null) 103 | { 104 | AfterPath.Data = Geometry.Parse(pathData); 105 | AfterTextEditor.Text = pathData.ToString(CultureInfo.InvariantCulture); 106 | } 107 | } 108 | } 109 | 110 | private void AfterTextEditor_TextChanged(object sender, TextChangedEventArgs e) 111 | { 112 | if (AfterTextEditor.IsKeyboardFocusWithin) 113 | { 114 | try 115 | { 116 | var pathData = Geometry.Parse(AfterTextEditor.Text); 117 | AfterPath.Data = pathData; 118 | } 119 | catch (Exception ex) 120 | { 121 | AfterPath.Data = null; 122 | } 123 | } 124 | } 125 | 126 | private bool TryGetSvgFileFromDataObject(IDataObject dataObject, [NotNullWhen(true)] out FileInfo? svgFile) 127 | { 128 | var fileDrop = dataObject.GetData(DataFormats.FileDrop); 129 | if (fileDrop is string[] fileArray 130 | && fileArray.Length > 0 131 | && string.Equals(Path.GetExtension(fileArray[0]), ".svg", StringComparison.OrdinalIgnoreCase)) 132 | { 133 | svgFile = new FileInfo(fileArray[0]); 134 | return true; 135 | } 136 | svgFile = null; 137 | return false; 138 | } 139 | 140 | private void InitializeTextEditor(TextEditor textEditor) 141 | { 142 | textEditor.SyntaxHighlighting = HighlightingManager.Instance.GetDefinition("XML"); 143 | TextEditorOptions options = textEditor.Options; 144 | if (options != null) 145 | { 146 | options.AllowScrollBelowDocument = true; 147 | options.EnableHyperlinks = true; 148 | options.EnableEmailHyperlinks = true; 149 | options.EnableVirtualSpace = true; 150 | options.HighlightCurrentLine = true; 151 | options.ShowSpaces = true; 152 | options.ShowTabs = true; 153 | options.ShowEndOfLine = true; 154 | } 155 | 156 | var foldingManager = FoldingManager.Install(textEditor.TextArea); 157 | var foldingStrategy = new XmlFoldingStrategy(); 158 | textEditor.TextArea.IndentationStrategy = new DefaultIndentationStrategy(); 159 | foldingStrategy.UpdateFoldings(foldingManager, textEditor.Document); 160 | } 161 | } 162 | } 163 | -------------------------------------------------------------------------------- /Walterlv.Tools.SvgPathCombiner/MiniLanguages/MiniLanguageParser.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | 4 | using Walterlv.MiniLanguages.Syntax; 5 | using Walterlv.MiniLanguages.Visitors; 6 | 7 | namespace Walterlv.MiniLanguages 8 | { 9 | public static class MiniLanguageParser 10 | { 11 | private static readonly Dictionary SegmentParsers = new() 12 | { 13 | { 'F', new FSyntax() }, 14 | { 'f', new FSyntax() }, 15 | { 'M', new MSyntax() }, 16 | { 'm', new MSyntax() }, 17 | { 'L', new LSyntax() }, 18 | { 'l', new LSyntax() }, 19 | { 'H', new HSyntax() }, 20 | { 'h', new HSyntax() }, 21 | { 'V', new VSyntax() }, 22 | { 'v', new VSyntax() }, 23 | { 'C', new CSyntax() }, 24 | { 'c', new CSyntax() }, 25 | { 'Q', new QSyntax() }, 26 | { 'q', new QSyntax() }, 27 | { 'S', new SSyntax() }, 28 | { 's', new SSyntax() }, 29 | { 'T', new TSyntax() }, 30 | { 't', new TSyntax() }, 31 | { 'A', new ASyntax() }, 32 | { 'a', new ASyntax() }, 33 | { 'Z', new ZSyntax() }, 34 | { 'z', new ZSyntax() }, 35 | }; 36 | 37 | public static void Visit(string pathData, IPathSyntaxVisitor visitor) 38 | { 39 | if (visitor is null) 40 | { 41 | throw new ArgumentNullException(nameof(visitor)); 42 | } 43 | 44 | var context = new CommandContext(pathData); 45 | PathSyntax currentParser = null; 46 | visitor.Start(in context); 47 | 48 | for (var i = 0; i < pathData.Length;) 49 | { 50 | var c = pathData[i]; 51 | context.StartIndex = i; 52 | context.Length = 0; 53 | 54 | if (SegmentParsers.TryGetValue(c, out var parser)) 55 | { 56 | currentParser = parser; 57 | 58 | // 具有明确命令的语法。 59 | i++; 60 | context.Command = c; 61 | parser.Parse(ref context, ref i, visitor); 62 | } 63 | else if (PathSyntax.IsNumberChar(c)) 64 | { 65 | // 没有命令的语法,重复上一次的语法。 66 | currentParser?.Parse(ref context, ref i, visitor); 67 | } 68 | else 69 | { 70 | // 上一命令已结束下一命令尚未开始时,遇到了非重要字符(如 ' ' ',' '\r' '\n')。 71 | i++; 72 | } 73 | } 74 | 75 | visitor.Complete(); 76 | } 77 | } 78 | } 79 | -------------------------------------------------------------------------------- /Walterlv.Tools.SvgPathCombiner/MiniLanguages/Syntax/ASyntax.cs: -------------------------------------------------------------------------------- 1 | using Walterlv.MiniLanguages.Visitors; 2 | 3 | namespace Walterlv.MiniLanguages.Syntax 4 | { 5 | internal sealed class ASyntax : PathSyntax 6 | { 7 | protected internal override void Parse(ref CommandContext context, ref int parsingIndex, IPathSyntaxVisitor visitor) 8 | { 9 | var originalText = context.OriginalText; 10 | var size = ReadSize(originalText, ref parsingIndex); 11 | var rotationAngle = ReadDouble(originalText, ref parsingIndex); 12 | var isLargeArc = ReadBoolean(originalText, ref parsingIndex); 13 | var isClockwise = ReadBoolean(originalText, ref parsingIndex); 14 | var endPoint = ReadPoint(originalText, ref parsingIndex); 15 | context.Length = parsingIndex - context.StartIndex; 16 | visitor.A(in context, size, rotationAngle, isLargeArc, isClockwise, endPoint); 17 | } 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /Walterlv.Tools.SvgPathCombiner/MiniLanguages/Syntax/CSyntax.cs: -------------------------------------------------------------------------------- 1 | using Walterlv.MiniLanguages.Visitors; 2 | 3 | namespace Walterlv.MiniLanguages.Syntax 4 | { 5 | internal sealed class CSyntax : PathSyntax 6 | { 7 | protected internal override void Parse(ref CommandContext context, ref int parsingIndex, IPathSyntaxVisitor visitor) 8 | { 9 | var originalText = context.OriginalText; 10 | var controlPoint1 = ReadPoint(originalText, ref parsingIndex); 11 | var controlPoint2 = ReadPoint(originalText, ref parsingIndex); 12 | var endPoint = ReadPoint(originalText, ref parsingIndex); 13 | context.Length = parsingIndex - context.StartIndex; 14 | visitor.C(in context, controlPoint1, controlPoint2, endPoint); 15 | } 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /Walterlv.Tools.SvgPathCombiner/MiniLanguages/Syntax/FSyntax.cs: -------------------------------------------------------------------------------- 1 | using Walterlv.MiniLanguages.Visitors; 2 | 3 | namespace Walterlv.MiniLanguages.Syntax 4 | { 5 | internal sealed class FSyntax : PathSyntax 6 | { 7 | protected internal override void Parse(ref CommandContext context, ref int parsingIndex, IPathSyntaxVisitor visitor) 8 | { 9 | var originalText = context.OriginalText; 10 | var isEvenOddOtherwiseNonzero = ReadBoolean(originalText, ref parsingIndex); 11 | context.Length = parsingIndex - context.StartIndex; 12 | visitor.F(in context, isEvenOddOtherwiseNonzero); 13 | } 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /Walterlv.Tools.SvgPathCombiner/MiniLanguages/Syntax/HSyntax.cs: -------------------------------------------------------------------------------- 1 | using Walterlv.MiniLanguages.Visitors; 2 | 3 | namespace Walterlv.MiniLanguages.Syntax 4 | { 5 | internal sealed class HSyntax : PathSyntax 6 | { 7 | protected internal override void Parse(ref CommandContext context, ref int parsingIndex, IPathSyntaxVisitor visitor) 8 | { 9 | var originalText = context.OriginalText; 10 | var x = ReadDouble(originalText, ref parsingIndex); 11 | context.Length = parsingIndex - context.StartIndex; 12 | visitor.H(in context, x); 13 | } 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /Walterlv.Tools.SvgPathCombiner/MiniLanguages/Syntax/LSyntax.cs: -------------------------------------------------------------------------------- 1 | using Walterlv.MiniLanguages.Visitors; 2 | 3 | namespace Walterlv.MiniLanguages.Syntax 4 | { 5 | internal sealed class LSyntax : PathSyntax 6 | { 7 | protected internal override void Parse(ref CommandContext context, ref int parsingIndex, IPathSyntaxVisitor visitor) 8 | { 9 | var originalText = context.OriginalText; 10 | var endPoint = ReadPoint(originalText, ref parsingIndex); 11 | context.Length = parsingIndex - context.StartIndex; 12 | visitor.L(in context, endPoint); 13 | } 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /Walterlv.Tools.SvgPathCombiner/MiniLanguages/Syntax/MSyntax.cs: -------------------------------------------------------------------------------- 1 | using Walterlv.MiniLanguages.Visitors; 2 | 3 | namespace Walterlv.MiniLanguages.Syntax 4 | { 5 | internal sealed class MSyntax : PathSyntax 6 | { 7 | protected internal override void Parse(ref CommandContext context, ref int parsingIndex, IPathSyntaxVisitor visitor) 8 | { 9 | var originalText = context.OriginalText; 10 | var startPoint = ReadPoint(originalText, ref parsingIndex); 11 | context.Length = parsingIndex - context.StartIndex; 12 | visitor.M(in context, startPoint); 13 | } 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /Walterlv.Tools.SvgPathCombiner/MiniLanguages/Syntax/PathSyntax.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Globalization; 3 | using System.Runtime.CompilerServices; 4 | using System.Windows; 5 | 6 | using Walterlv.MiniLanguages.Visitors; 7 | 8 | namespace Walterlv.MiniLanguages.Syntax 9 | { 10 | internal abstract class PathSyntax 11 | { 12 | protected internal abstract void Parse(ref CommandContext context, ref int parsingIndex, IPathSyntaxVisitor visitor); 13 | 14 | protected static bool ReadBoolean(string originalText, ref int parsingIndex) 15 | { 16 | var value = ReadDouble(originalText, ref parsingIndex); 17 | // 取值只有 1 和 0,我们用 0.5 来将其区分。 18 | return value >= 0.5; 19 | } 20 | 21 | protected static Point ReadPoint(string originalText, ref int parsingIndex) 22 | { 23 | var x = ReadDouble(originalText, ref parsingIndex); 24 | var y = ReadDouble(originalText, ref parsingIndex); 25 | return new Point(x, y); 26 | } 27 | 28 | protected static Size ReadSize(string originalText, ref int parsingIndex) 29 | { 30 | var x = ReadDouble(originalText, ref parsingIndex); 31 | var y = ReadDouble(originalText, ref parsingIndex); 32 | return new Size(x, y); 33 | } 34 | 35 | protected static double ReadDouble(string originalText, ref int parsingIndex) 36 | { 37 | var numberLength = 0; 38 | for (var i = parsingIndex; i < originalText.Length; i++) 39 | { 40 | var shouldParse = false; 41 | var c = originalText[i]; 42 | if (IsNumberChar(c)) 43 | { 44 | // 遇到数字,长度增加。 45 | numberLength++; 46 | } 47 | else if (numberLength is 0) 48 | { 49 | // 开头遇到非数字,跳过。 50 | parsingIndex++; 51 | } 52 | else 53 | { 54 | shouldParse = true; 55 | } 56 | 57 | var isEnd = i == originalText.Length - 1; 58 | if (shouldParse || isEnd) 59 | { 60 | // 非开头遇到非数字(或者已抵达文本末尾),解析数字。 61 | var number = double.TryParse( 62 | #if NETCOREAPP 63 | originalText.AsSpan(parsingIndex, numberLength), 64 | #else 65 | originalText.Substring(parsingIndex, numberLength), 66 | #endif 67 | NumberStyles.Float, CultureInfo.InvariantCulture, out var result) 68 | ? result 69 | : 0; 70 | // 正常是遇到了后面的非数字才结束解析的,而那时 index 已经往后移了一位了。 71 | // 但现在解析到数字时遇到了字符串结尾,index 还没有往后移;所以我们需要补偿一个 1,以便让解析正常结束,否则陷入无限循环。 72 | parsingIndex = (!shouldParse && isEnd) ? i + 1 : i; 73 | return number; 74 | } 75 | } 76 | return 0; 77 | } 78 | 79 | [MethodImpl(MethodImplOptions.AggressiveInlining)] 80 | internal static bool IsNumberChar(char c) 81 | { 82 | return char.IsDigit(c) || c is '.' or '+' or '-' or 'E'; 83 | } 84 | } 85 | } 86 | -------------------------------------------------------------------------------- /Walterlv.Tools.SvgPathCombiner/MiniLanguages/Syntax/QSyntax.cs: -------------------------------------------------------------------------------- 1 | using Walterlv.MiniLanguages.Visitors; 2 | 3 | namespace Walterlv.MiniLanguages.Syntax 4 | { 5 | internal sealed class QSyntax : PathSyntax 6 | { 7 | protected internal override void Parse(ref CommandContext context, ref int parsingIndex, IPathSyntaxVisitor visitor) 8 | { 9 | var originalText = context.OriginalText; 10 | var controlPoint = ReadPoint(originalText, ref parsingIndex); 11 | var endPoint = ReadPoint(originalText, ref parsingIndex); 12 | context.Length = parsingIndex - context.StartIndex; 13 | visitor.Q(in context, controlPoint, endPoint); 14 | } 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /Walterlv.Tools.SvgPathCombiner/MiniLanguages/Syntax/SSyntax.cs: -------------------------------------------------------------------------------- 1 | using Walterlv.MiniLanguages.Visitors; 2 | 3 | namespace Walterlv.MiniLanguages.Syntax 4 | { 5 | internal sealed class SSyntax : PathSyntax 6 | { 7 | protected internal override void Parse(ref CommandContext context, ref int parsingIndex, IPathSyntaxVisitor visitor) 8 | { 9 | var originalText = context.OriginalText; 10 | var controlPoint2 = ReadPoint(originalText, ref parsingIndex); 11 | var endPoint = ReadPoint(originalText, ref parsingIndex); 12 | context.Length = parsingIndex - context.StartIndex; 13 | visitor.S(in context, controlPoint2, endPoint); 14 | } 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /Walterlv.Tools.SvgPathCombiner/MiniLanguages/Syntax/TSyntax.cs: -------------------------------------------------------------------------------- 1 | using Walterlv.MiniLanguages.Visitors; 2 | 3 | namespace Walterlv.MiniLanguages.Syntax 4 | { 5 | internal sealed class TSyntax : PathSyntax 6 | { 7 | protected internal override void Parse(ref CommandContext context, ref int parsingIndex, IPathSyntaxVisitor visitor) 8 | { 9 | var originalText = context.OriginalText; 10 | var endPoint = ReadPoint(originalText, ref parsingIndex); 11 | context.Length = parsingIndex - context.StartIndex; 12 | visitor.T(in context, endPoint); 13 | } 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /Walterlv.Tools.SvgPathCombiner/MiniLanguages/Syntax/VSyntax.cs: -------------------------------------------------------------------------------- 1 | using Walterlv.MiniLanguages.Visitors; 2 | 3 | namespace Walterlv.MiniLanguages.Syntax 4 | { 5 | internal sealed class VSyntax : PathSyntax 6 | { 7 | protected internal override void Parse(ref CommandContext context, ref int parsingIndex, IPathSyntaxVisitor visitor) 8 | { 9 | var originalText = context.OriginalText; 10 | var y = ReadDouble(originalText, ref parsingIndex); 11 | context.Length = parsingIndex - context.StartIndex; 12 | visitor.V(in context, y); 13 | } 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /Walterlv.Tools.SvgPathCombiner/MiniLanguages/Syntax/ZSyntax.cs: -------------------------------------------------------------------------------- 1 | using Walterlv.MiniLanguages.Visitors; 2 | 3 | namespace Walterlv.MiniLanguages.Syntax 4 | { 5 | internal sealed class ZSyntax : PathSyntax 6 | { 7 | protected internal override void Parse(ref CommandContext context, ref int parsingIndex, IPathSyntaxVisitor visitor) 8 | { 9 | context.Length = 1; 10 | visitor.Z(in context); 11 | } 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /Walterlv.Tools.SvgPathCombiner/MiniLanguages/Visitors/CommandContext.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace Walterlv.MiniLanguages.Visitors 4 | { 5 | public ref struct CommandContext 6 | { 7 | public CommandContext(string originalText) : this() 8 | { 9 | OriginalText = originalText ?? throw new ArgumentNullException(nameof(originalText)); 10 | } 11 | 12 | public string OriginalText { get; } 13 | 14 | public int StartIndex { get; internal set; } 15 | 16 | public int Length { get; internal set; } 17 | 18 | public char Command { get; internal set; } 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /Walterlv.Tools.SvgPathCombiner/MiniLanguages/Visitors/IPathSyntaxVisitor.cs: -------------------------------------------------------------------------------- 1 | using System.Windows; 2 | 3 | namespace Walterlv.MiniLanguages.Visitors 4 | { 5 | public interface IPathSyntaxVisitor 6 | { 7 | void Start(in CommandContext context); 8 | void F(in CommandContext context, bool isEvenOddOtherwiseNonzero); 9 | void M(in CommandContext context, Point startPoint); 10 | void L(in CommandContext context, Point endPoint); 11 | void H(in CommandContext context, double x); 12 | void V(in CommandContext context, double y); 13 | void C(in CommandContext context, Point controlPoint1, Point controlPoint2, Point endPoint); 14 | void Q(in CommandContext context, Point controlPoint, Point endPoint); 15 | void S(in CommandContext context, Point controlPoint2, Point endPoint); 16 | void T(in CommandContext context, Point endPoint); 17 | void A(in CommandContext context, Size size, double rotationAngle, bool isLargeArc, bool isClockwise, Point endPoint); 18 | void Z(in CommandContext context); 19 | void Complete(); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /Walterlv.Tools.SvgPathCombiner/MiniLanguages/Visitors/PathSyntaxVisitor.cs: -------------------------------------------------------------------------------- 1 | using System.Runtime.CompilerServices; 2 | using System.Windows; 3 | 4 | namespace Walterlv.MiniLanguages.Visitors 5 | { 6 | public abstract class PathSyntaxVisitor : IPathSyntaxVisitor 7 | { 8 | private char _lastCommand; 9 | private Point _lastPoint; 10 | private Point _lastControlPoint; 11 | 12 | void IPathSyntaxVisitor.Start(in CommandContext context) 13 | { 14 | Start(); 15 | } 16 | 17 | void IPathSyntaxVisitor.F(in CommandContext context, bool isEvenOddOtherwiseNonzero) 18 | { 19 | _lastCommand = 'F'; 20 | F(isEvenOddOtherwiseNonzero); 21 | } 22 | 23 | void IPathSyntaxVisitor.M(in CommandContext context, Point startPoint) 24 | { 25 | _lastCommand = 'M'; 26 | M(startPoint); 27 | _lastPoint = startPoint; 28 | } 29 | 30 | void IPathSyntaxVisitor.L(in CommandContext context, Point endPoint) 31 | { 32 | _lastCommand = 'L'; 33 | endPoint = MakeAbsoluteEndPoint(context.Command, in endPoint); 34 | _lastCommand = 'L'; 35 | L(_lastPoint, endPoint); 36 | _lastPoint = endPoint; 37 | } 38 | 39 | void IPathSyntaxVisitor.H(in CommandContext context, double x) 40 | { 41 | var endPoint = new Point(x + (char.IsUpper(context.Command) ? 0 : _lastPoint.X), _lastPoint.Y); 42 | _lastCommand = 'L'; 43 | L(_lastPoint, endPoint); 44 | _lastPoint = endPoint; 45 | } 46 | 47 | void IPathSyntaxVisitor.V(in CommandContext context, double y) 48 | { 49 | var endPoint = new Point(_lastPoint.X, y + (char.IsUpper(context.Command) ? 0 : _lastPoint.Y)); 50 | _lastCommand = 'L'; 51 | L(_lastPoint, endPoint); 52 | _lastPoint = endPoint; 53 | } 54 | 55 | void IPathSyntaxVisitor.C(in CommandContext context, Point controlPoint1, Point controlPoint2, Point endPoint) 56 | { 57 | controlPoint1 = MakeAbsoluteEndPoint(context.Command, in controlPoint1); 58 | controlPoint2 = MakeAbsoluteEndPoint(context.Command, in controlPoint2); 59 | endPoint = MakeAbsoluteEndPoint(context.Command, in endPoint); 60 | _lastCommand = 'C'; 61 | _lastControlPoint = controlPoint2; 62 | C(_lastPoint, controlPoint1, controlPoint2, endPoint); 63 | _lastPoint = endPoint; 64 | } 65 | 66 | void IPathSyntaxVisitor.Q(in CommandContext context, Point controlPoint, Point endPoint) 67 | { 68 | controlPoint = MakeAbsoluteEndPoint(context.Command, in controlPoint); 69 | endPoint = MakeAbsoluteEndPoint(context.Command, in endPoint); 70 | _lastCommand = 'Q'; 71 | _lastControlPoint = controlPoint; 72 | Q(_lastPoint, controlPoint, endPoint); 73 | _lastPoint = endPoint; 74 | } 75 | 76 | void IPathSyntaxVisitor.S(in CommandContext context, Point controlPoint2, Point endPoint) 77 | { 78 | controlPoint2 = MakeAbsoluteEndPoint(context.Command, in controlPoint2); 79 | endPoint = MakeAbsoluteEndPoint(context.Command, in endPoint); 80 | var controlPoint1 = _lastCommand is 'C' 81 | ? Reflect() 82 | : _lastPoint; 83 | _lastCommand = 'C'; 84 | _lastControlPoint = controlPoint2; 85 | C(_lastPoint, controlPoint1, controlPoint2, endPoint); 86 | _lastPoint = endPoint; 87 | } 88 | 89 | void IPathSyntaxVisitor.T(in CommandContext context, Point endPoint) 90 | { 91 | endPoint = MakeAbsoluteEndPoint(context.Command, in endPoint); 92 | var controlPoint = _lastCommand is 'Q' 93 | ? Reflect() 94 | : _lastPoint; 95 | _lastCommand = 'Q'; 96 | _lastControlPoint = controlPoint; 97 | Q(_lastPoint, controlPoint, endPoint); 98 | _lastPoint = endPoint; 99 | } 100 | 101 | void IPathSyntaxVisitor.A(in CommandContext context, Size size, double rotationAngle, bool isLargeArc, bool isClockwise, Point endPoint) 102 | { 103 | _lastCommand = 'A'; 104 | endPoint = MakeAbsoluteEndPoint(context.Command, in endPoint); 105 | A(_lastPoint, size, rotationAngle, isLargeArc, isClockwise, endPoint); 106 | _lastPoint = endPoint; 107 | } 108 | 109 | void IPathSyntaxVisitor.Z(in CommandContext context) 110 | { 111 | _lastCommand = 'Z'; 112 | Z(); 113 | } 114 | 115 | void IPathSyntaxVisitor.Complete() 116 | { 117 | Complete(); 118 | } 119 | 120 | public virtual void Start() 121 | { 122 | } 123 | 124 | public virtual void F(bool isEvenOddOtherwiseNonzero) 125 | { 126 | } 127 | 128 | public virtual void M(Point startPoint) 129 | { 130 | } 131 | 132 | public virtual void L(Point lastPoint, Point endPoint) 133 | { 134 | } 135 | 136 | public virtual void C(Point lastPoint, Point controlPoint1, Point controlPoint2, Point endPoint) 137 | { 138 | } 139 | 140 | public virtual void Q(Point lastPoint, Point controlPoint, Point endPoint) 141 | { 142 | } 143 | 144 | public virtual void A(Point lastPoint, Size size, double rotationAngle, bool isLargeArc, bool isClockwise, Point endPoint) 145 | { 146 | } 147 | 148 | public virtual void Z() 149 | { 150 | } 151 | 152 | public virtual void Complete() 153 | { 154 | } 155 | 156 | /// 157 | /// 将上一个控制点根据上一个点的位置进行对称,以获得平滑的贝塞尔曲线。 158 | /// 159 | /// 平滑的贝塞尔曲线控制点。 160 | [MethodImpl(MethodImplOptions.AggressiveInlining)] 161 | private Point Reflect() 162 | { 163 | return new Point(2 * _lastPoint.X - _lastControlPoint.X, 2 * _lastPoint.Y - _lastControlPoint.Y); 164 | } 165 | 166 | [MethodImpl(MethodImplOptions.AggressiveInlining)] 167 | private Point MakeAbsoluteEndPoint(in char command, in Point endPoint) 168 | { 169 | return char.IsUpper(command) ? endPoint : _lastPoint + new Vector(endPoint.X, endPoint.Y); 170 | } 171 | } 172 | } 173 | -------------------------------------------------------------------------------- /Walterlv.Tools.SvgPathCombiner/PathTransformVisitor.cs: -------------------------------------------------------------------------------- 1 | using System.Windows; 2 | using System.Windows.Media; 3 | 4 | using Walterlv.MiniLanguages.Visitors; 5 | 6 | namespace Walterlv.Tools 7 | { 8 | internal class PathTransformVisitor : PathSyntaxVisitor 9 | { 10 | private readonly Transform _transform; 11 | private PathGeometry _path = new(); 12 | private PathFigure _figure = null!; 13 | 14 | public PathTransformVisitor(Transform? transform) 15 | { 16 | _transform = transform ?? Transform.Identity; 17 | } 18 | 19 | public override void Start() 20 | { 21 | } 22 | 23 | public override void F(bool isEvenOddOtherwiseNonzero) 24 | { 25 | _path.FillRule = isEvenOddOtherwiseNonzero ? FillRule.EvenOdd : FillRule.Nonzero; 26 | } 27 | 28 | public override void M(Point startPoint) 29 | { 30 | _figure = new PathFigure 31 | { 32 | StartPoint = TransformPoint(startPoint) 33 | }; 34 | _path.Figures.Add(_figure); 35 | } 36 | 37 | public override void L(Point lastPoint, Point endPoint) 38 | { 39 | _figure.Segments.Add(new LineSegment( 40 | TransformPoint(endPoint), 41 | false)); 42 | } 43 | 44 | public override void C(Point lastPoint, Point controlPoint1, Point controlPoint2, Point endPoint) 45 | { 46 | _figure.Segments.Add(new BezierSegment( 47 | TransformPoint(controlPoint1), 48 | TransformPoint(controlPoint2), 49 | TransformPoint(endPoint), 50 | false)); 51 | } 52 | 53 | public override void Q(Point lastPoint, Point controlPoint, Point endPoint) 54 | { 55 | _figure.Segments.Add(new QuadraticBezierSegment( 56 | TransformPoint(controlPoint), 57 | TransformPoint(endPoint), 58 | false)); 59 | } 60 | 61 | public override void A(Point lastPoint, Size size, double rotationAngle, bool isLargeArc, bool isClockwise, Point endPoint) 62 | { 63 | var scale = GetScaleSize(_transform.Value); 64 | _figure.Segments.Add(new ArcSegment( 65 | TransformPoint(endPoint), 66 | new Size(size.Width * scale.Width, size.Height * scale.Height), 67 | rotationAngle, 68 | isLargeArc, 69 | isClockwise ? SweepDirection.Clockwise : SweepDirection.Counterclockwise, 70 | false)); 71 | } 72 | 73 | public override void Z() 74 | { 75 | _figure.IsClosed = true; 76 | } 77 | 78 | public override void Complete() 79 | { 80 | } 81 | 82 | private static Size GetScaleSize(Matrix transform) 83 | { 84 | // 计算旋转分量。 85 | var unitVector = new Vector(1, 0); 86 | var vector = transform.Transform(unitVector); 87 | //如果图片旋转了,那么得到的值和图片显示的不同,会被计算旋转后的值,参见 Element 旋转。 88 | //所以需要把图片还原 89 | //还原的方法是计算获得的角度,也就是和单位分量角度,由角度可以得到旋转度。 90 | //用转换旋转之前旋转角度反过来就是得到原来图片的值 91 | var angle = Vector.AngleBetween(unitVector, vector); 92 | transform.Rotate(-angle); 93 | // 综合缩放。 94 | var rect = new Rect(new Size(1, 1)); 95 | rect.Transform(transform); 96 | 97 | return rect.Size; 98 | } 99 | 100 | public override string ToString() 101 | { 102 | return _path.ToString(); 103 | } 104 | 105 | private Point TransformPoint(Point point) 106 | { 107 | if (_transform is MatrixTransform mt) 108 | { 109 | if (mt.Matrix == Matrix.Identity) 110 | { 111 | return point; 112 | } 113 | 114 | if (mt.Matrix.M11 == 1 && mt.Matrix.M22 == 1 115 | && mt.Matrix.M12 == 0 && mt.Matrix.M21 == 0) 116 | { 117 | return new Point( 118 | (double)((decimal)point.X + (decimal)mt.Matrix.OffsetX), 119 | (double)((decimal)point.Y + (decimal)mt.Matrix.OffsetY)); 120 | } 121 | } 122 | return _transform.Transform(point); 123 | } 124 | } 125 | } 126 | -------------------------------------------------------------------------------- /Walterlv.Tools.SvgPathCombiner/SvgPathCombiner.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.ComponentModel.DataAnnotations; 4 | using System.Diagnostics.CodeAnalysis; 5 | using System.Globalization; 6 | using System.Linq; 7 | using System.Security.Cryptography.Xml; 8 | using System.Text; 9 | using System.Threading.Tasks; 10 | using System.Windows; 11 | using System.Windows.Media; 12 | 13 | using Walterlv.MiniLanguages; 14 | 15 | namespace Walterlv.Tools 16 | { 17 | public class SvgPathCombiner 18 | { 19 | public static bool TryGuessSvgDrawingViewbox(DrawingGroup dg, out Rect viewbox) 20 | { 21 | var current = dg; 22 | for (var i = 0; i < 2; i++) 23 | { 24 | if (current.ClipGeometry is RectangleGeometry rectangleGeometry && rectangleGeometry.Rect is { } rect) 25 | { 26 | viewbox = rect; 27 | return true; 28 | } 29 | if(current.Children.FirstOrDefault() is DrawingGroup d) 30 | { 31 | current = d; 32 | } 33 | else 34 | { 35 | break; 36 | } 37 | } 38 | viewbox = default; 39 | return false; 40 | } 41 | 42 | public static string Combine(DrawingGroup drawingGroup) 43 | { 44 | string? currentGeometry = null; 45 | foreach (var drawing in drawingGroup.Children.OfType()) 46 | { 47 | if (drawing is DrawingGroup dg) 48 | { 49 | var path1 = currentGeometry; 50 | var path2 = Combine(dg); 51 | currentGeometry = RecursiveCombine(path1, path2); 52 | } 53 | else if (drawing is GeometryDrawing gd) 54 | { 55 | if (gd.Brush is null) 56 | { 57 | // 不可见图形。 58 | } 59 | else if (gd.Brush is SolidColorBrush scb && scb.Color.A == 0) 60 | { 61 | // 不可见图形。 62 | } 63 | else if (gd.Geometry is PathGeometry pg) 64 | { 65 | var path1 = currentGeometry; 66 | var path2 = pg.ToString(CultureInfo.InvariantCulture); 67 | currentGeometry = RecursiveCombine(path1, path2); 68 | } 69 | } 70 | } 71 | if (currentGeometry is null) 72 | { 73 | return ""; 74 | } 75 | else 76 | { 77 | var visitor = new PathTransformVisitor(drawingGroup.Transform); 78 | MiniLanguageParser.Visit(currentGeometry, visitor); 79 | return visitor.ToString(); 80 | } 81 | } 82 | 83 | private static string RecursiveCombine(string? path1, string path2) 84 | { 85 | if (path1 is null) 86 | { 87 | return path2; 88 | } 89 | else 90 | { 91 | var mIndex = path2.IndexOf('M'); 92 | if (mIndex > 0) 93 | { 94 | path2 = path2[mIndex..]; 95 | } 96 | 97 | return path1 + path2; 98 | } 99 | } 100 | } 101 | } 102 | -------------------------------------------------------------------------------- /Walterlv.Tools.SvgPathCombiner/Walterlv.Tools.SvgPathCombiner.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | WinExe 5 | net5.0-windows 6 | true 7 | enable 8 | Walterlv.Tools 9 | 1.3.0 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | -------------------------------------------------------------------------------- /docs/img/main_screenshot.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dotnet-campus/dotnetCampus.SvgPathCombiner/6d74d884deb4b3f5ae6587ecd76fd4d3359cd232/docs/img/main_screenshot.png --------------------------------------------------------------------------------