■ SVG 파일을 XAML로 변환하는 방법을 보여준다.
▶ ConversionMode.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
namespace TestProject { /// <summary> /// 변환 모드 /// </summary> public enum ConversionMode { /// <summary> /// 드로잉 그룹 /// </summary> DrawingGroup, /// <summary> /// 드로잉 이미지 /// </summary> DrawingImage } } |
▶ SVGHelper.cs
1 2 3 4 5 6 7 8 9 10 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 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 |
using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.IO.Compression; using System.Linq; using System.Text.RegularExpressions; using System.Windows; using System.Windows.Media; using System.Xml; using System.Xml.Linq; using System.Xml.XPath; using SharpVectors.Converters; using SharpVectors.Renderers.Wpf; namespace TestProject { /// <summary> /// SVG 헬퍼 /// </summary> public static class SVGHelper { //////////////////////////////////////////////////////////////////////////////////////////////////// Field ////////////////////////////////////////////////////////////////////////////////////////// Static //////////////////////////////////////////////////////////////////////////////// Private #region Field /// <summary> /// 디폴트 XML 네임스페이스 /// </summary> private static XNamespace _defaultXMLNamespace = "http://schemas.microsoft.com/winfx/2006/xaml/presentation"; /// <summary> /// X XML 네임스페이스 /// </summary> private static XNamespace _xXMLNamespace = "http://schemas.microsoft.com/winfx/2006/xaml"; /// <summary> /// XML 네임스페이스 관리자 /// </summary> private static XmlNamespaceManager _xmlNamespaceManager = new XmlNamespaceManager(new NameTable()); #endregion ////////////////////////////////////////////////////////////////////////////////////////// Instance //////////////////////////////////////////////////////////////////////////////// Private #region Field /// <summary> /// 접두사 분리자 /// </summary> private const char PREFIX_SEPARATOR = '_'; #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor ////////////////////////////////////////////////////////////////////////////////////////// Static #region 생성자 - SVGHelper() /// <summary> /// 생성자 /// </summary> static SVGHelper() { _xmlNamespaceManager.AddNamespace("defns", "http://schemas.microsoft.com/winfx/2006/xaml/presentation"); _xmlNamespaceManager.AddNamespace("x" , "http://schemas.microsoft.com/winfx/2006/xaml" ); } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Static //////////////////////////////////////////////////////////////////////////////// Public #region 객체 구하기 - GetObject(filePath, conversionMode, settings, name, resourceKeyInfo) /// <summary> /// 객체 구하기 /// </summary> /// <param name="filePath">파일 경로</param> /// <param name="conversionMode">변환 모드</param> /// <param name="settings">설정</param> /// <param name="name">명칭</param> /// <param name="resourceKeyInfo">리소스 키 정보</param> /// <returns>객체</returns> public static object GetObject ( string filePath, ConversionMode conversionMode, WpfDrawingSettings settings, out string name, ResourceKeyInfo resourceKeyInfo ) { DrawingGroup drawingGroup = GetDrawingGroup(filePath, settings); string elementName = Path.GetFileNameWithoutExtension(filePath); switch(conversionMode) { case ConversionMode.DrawingGroup : name = GetDrawingGroupName(elementName, resourceKeyInfo); return drawingGroup; case ConversionMode.DrawingImage: name = GetDrawingImageName(elementName, resourceKeyInfo); return GetDrawingImage(drawingGroup); default : throw new ArgumentOutOfRangeException(nameof(conversionMode)); } } #endregion #region XAML 구하기 - GetXAML(instance, includeRuntime, name, filterPixelCountPerDIP) /// <summary> /// XAML 구하기 /// </summary> /// <param name="instance">인스턴스</param> /// <param name="includeRuntime">런타임 포함 여부</param> /// <param name="name">명칭</param> /// <param name="filterPixelCountPerDIP">DIP 당 픽셀 카운트 필터링 여부</param> /// <returns>XAML</returns> public static string GetXAML(object instance, bool includeRuntime, string name, bool filterPixelCountPerDIP) { var xamlUntidy = GetXAML(instance, includeRuntime); XDocument document = XDocument.Parse(xamlUntidy); NormalizeDrawingElement(document.Root, name); if(filterPixelCountPerDIP) { FilterPixelCountPerDIP(document.Root); } string temporaryXAML = document.ToString(); string xaml = RemoveNamespaceDeclaration(temporaryXAML); return xaml; } #endregion #region XAML 구하기 - GetXAML(filePath, conversionMode, resourceKeyInfo, filterPixelCountPerDIP, settings) /// <summary> /// XAML 구하기 /// </summary> /// <param name="filePath">파일 경로</param> /// <param name="conversionMode">변환 모드</param> /// <param name="resourceKeyInfo">리소스 키 정보</param> /// <param name="filterPixelCountPerDIP">DIP당 픽셀 카운트 필터링 여부</param> /// <param name="settings">WPF 그리기 설정</param> /// <returns>XAML</returns> public static string GetXAML ( string filePath, ConversionMode conversionMode, ResourceKeyInfo resourceKeyInfo, bool filterPixelCountPerDIP, WpfDrawingSettings settings = null ) { object instance = GetObject(filePath, conversionMode, settings, out var name, resourceKeyInfo); return GetXAML(instance, settings != null && settings.IncludeRuntime, name, filterPixelCountPerDIP); } #endregion #region SVG 데이터 구하기 - GetSVGData(filePath) /// <summary> /// SVG 데이터 구하기 /// </summary> /// <param name="filePath">파일 경로</param> /// <returns>SVG 데이터</returns> public static SVGData GetSVGData(string filePath) { return new SVGData { FilePath = filePath }; } #endregion //////////////////////////////////////////////////////////////////////////////// Private #region SVGZ 파일 여부 구하기 - IsSVGZFile(filePath) /// <summary> /// SVGZ 파일 여부 구하기 /// </summary> /// <param name="filePath">파일 경로</param> /// <returns>SVGZ 파일 여부</returns> private static bool IsSVGZFile(string filePath) { return string.Equals(Path.GetExtension(filePath), ".svgz", StringComparison.OrdinalIgnoreCase); } #endregion #region ID 정정하기 - FixID(rootElement) /// <summary> /// ID 정정하기 /// </summary> /// <param name="rootElement">루트 엘리먼트</param> private static void FixID(XElement rootElement) { IEnumerable<XAttribute> attributeEnumerable = rootElement.DescendantsAndSelf() .SelectMany(d => d.Attributes()) .Where(a => string.Equals(a.Name.LocalName, "Id", StringComparison.InvariantCultureIgnoreCase)); foreach(XAttribute attribute in attributeEnumerable) { if(char.IsDigit(attribute.Value.FirstOrDefault())) { attribute.Value = "_" + attribute.Value; } attribute.Value = attribute.Value.Replace("/", "_"); } } #endregion #region 드로잉 그룹 구하기 (코어) - GetDrawingGroupCore(filePath, settings) /// <summary> /// 드로잉 그룹 구하기 (코어) /// </summary> /// <param name="filePath">파일 경로</param> /// <param name="settings">설정</param> /// <returns>드로잉 그룹</returns> private static DrawingGroup GetDrawingGroupCore(string filePath, WpfDrawingSettings settings) { if(settings == null) { settings = new WpfDrawingSettings { IncludeRuntime = false, TextAsGeometry = false, OptimizePath = true }; } FileSvgReader reader = new FileSvgReader(settings); filePath = Path.GetFullPath(filePath); Stream stream = IsSVGZFile(filePath) ? (Stream)new GZipStream(File.OpenRead(filePath), CompressionMode.Decompress, false) : File.OpenRead(filePath); XDocument document = XDocument.Load(stream); stream.Dispose(); FixID(document.Root); // 예 : "3d-view-icon" -> "_3d-view-icon" using(MemoryStream memoryStream = new MemoryStream()) { document.Save(memoryStream); memoryStream.Position = 0; reader.Read(memoryStream); return reader.Drawing; } } #endregion #region 드로잉 그룹에서 크기 구하기 - GetSizeFromDrawingGroup(drawingGroup) /// <summary> /// 드로잉 그룹에서 크기 구하기 /// </summary> /// <param name="drawingGroup">드로잉 그룹</param> /// <returns>크기</returns> private static Size? GetSizeFromDrawingGroup(DrawingGroup drawingGroup) { if(drawingGroup != null) { DrawingGroup firstChild = drawingGroup.Children.OfType<DrawingGroup>() .FirstOrDefault(child => child.ClipGeometry != null); if(firstChild != null) { return firstChild.ClipGeometry.Bounds.Size; } } return null; } #endregion #region 패스 지오메트리 리스트 구하기 - GetPathGeometryList(sourceDrawing) /// <summary> /// 패스 지오메트리 리스트 구하기 /// </summary> /// <param name="sourceDrawing">소스 드로잉</param> /// <returns>패스 지오메트리 리스트</returns> private static List<PathGeometry> GetPathGeometryList(Drawing sourceDrawing) { List<PathGeometry> list = new List<PathGeometry>(); Action<Drawing> action = null; action = drawing => { if(drawing is DrawingGroup) { foreach(Drawing childDrawing in ((DrawingGroup)drawing).Children) { action(childDrawing); } } if(drawing is GeometryDrawing) { GeometryDrawing geometryDrawing = (GeometryDrawing)drawing; Geometry geometry = geometryDrawing.Geometry; if(geometry is PathGeometry) { list.Add((PathGeometry)geometry); } } }; action(sourceDrawing); return list; } #endregion #region 크기 패스 피규어 추가하기 - AddSizePathFigure(sourceGeometry, size) /// <summary> /// 크기 패스 피규어 추가하기 /// </summary> /// <param name="sourceGeometry">소스 패스 지오메트리</param> /// <param name="size">크기</param> private static void AddSizePathFigure(PathGeometry sourceGeometry, Size size) { if(size.Width > 0 && size.Height > 0) { PathFigure[] pathFigureArray = { new PathFigure ( new Point(size.Width, size.Height), Enumerable.Empty<PathSegment>(), true ), new PathFigure ( new Point(0,0), Enumerable.Empty<PathSegment>(), true ) }; PathGeometry targetGeometry = new PathGeometry ( pathFigureArray.Concat(sourceGeometry.Figures), sourceGeometry.FillRule, null ); sourceGeometry.Clear(); sourceGeometry.AddGeometry(targetGeometry); } } #endregion #region 패스 지오메트리에 크기 설정하기 - SetSizeToPathGeometry(drawingGroup) /// <summary> /// 패스 지오메트리에 크기 설정하기 /// </summary> /// <param name="drawingGroup">드로잉 그룹</param> private static void SetSizeToPathGeometry(DrawingGroup drawingGroup) { Size? size = GetSizeFromDrawingGroup(drawingGroup); if(size.HasValue) { List<PathGeometry> pathGeometryList = GetPathGeometryList(drawingGroup); pathGeometryList.ForEach(pathGemoetry => AddSizePathFigure(pathGemoetry, size.Value)); } } #endregion #region 객체 명칭 값 제거하기 - RemoveObjectNameValue(drawingGroup) /// <summary> /// 객체 명칭 값 제거하기 /// </summary> /// <param name="drawingGroup">드로잉 그룹</param> public static void RemoveObjectNameValue(DrawingGroup drawingGroup) { if(drawingGroup.GetValue(FrameworkElement.NameProperty) != null) { drawingGroup.SetValue(FrameworkElement.NameProperty, null); } foreach(DependencyObject child in drawingGroup.Children.OfType<DependencyObject>()) { if(child.GetValue(FrameworkElement.NameProperty) != null) { child.SetValue(FrameworkElement.NameProperty, null); } if(child is DrawingGroup) { RemoveObjectNameValue(child as DrawingGroup); } } } #endregion #region 드로잉 그룹 구하기 - GetDrawingGroup(filePath, settings) /// <summary> /// 드로잉 그룹 구하기 /// </summary> /// <param name="filePath">파일 경로</param> /// <param name="settings">설정</param> /// <returns>드로잉 그룹</returns> private static DrawingGroup GetDrawingGroup(string filePath, WpfDrawingSettings settings) { DrawingGroup drawingGroup = GetDrawingGroupCore(filePath, settings); SetSizeToPathGeometry(drawingGroup); RemoveObjectNameValue(drawingGroup); return drawingGroup; } #endregion #region 명칭 검증하기 - ValidateName(name) /// <summary> /// 명칭 검증하기 /// </summary> /// <param name="name">명칭</param> /// <returns>명칭</returns> private static string ValidateName(string name) { string result = Regex.Replace(name, @"[^[0-9a-zA-Z]]*", "_"); if(Regex.IsMatch(result, "^[0-9].*")) { result = "_" + result; } return result; } #endregion #region 명칭 구하기 - GetName(sourceName, resourceKeyInfo) /// <summary> /// 명칭 구하기 /// </summary> /// <param name="sourceName">소스 명칭</param> /// <param name="resourceKeyInfo">리소스 키 정보</param> /// <returns>명칭</returns> private static string GetName(string sourceName, ResourceKeyInfo resourceKeyInfo) { if(resourceKeyInfo.UseComponentRessourceKey) { return $"{{x:Static {resourceKeyInfo.NameSpaceName}:{resourceKeyInfo.XAMLName}.{ValidateName(sourceName)}Key}}"; } string targetName = sourceName; if(resourceKeyInfo.Prefix != null) { targetName = resourceKeyInfo.Prefix + PREFIX_SEPARATOR + sourceName; } targetName = ValidateName(targetName); return targetName; } #endregion #region 드로잉 그룹명 구하기 - GetDrawingGroupName(elementName, resourceKeyInfo) /// <summary> /// 드로잉 그룹명 구하기 /// </summary> /// <param name="elementName">엘리먼트명</param> /// <param name="resourceKeyInfo">리소스 키 정보</param> /// <returns>드로잉 그룹명</returns> private static string GetDrawingGroupName(string elementName, ResourceKeyInfo resourceKeyInfo) { string sourceName = elementName + "DrawingGroup"; return GetName(sourceName, resourceKeyInfo); } #endregion #region 드로잉 이미지명 구하기 - GetDrawingImageName(elementName, resourceKeyInfo) /// <summary> /// 드로잉 이미지명 구하기 /// </summary> /// <param name="elementName">엘리먼트명</param> /// <param name="resourceKeyInfo">리소스 키 정보</param> /// <returns>드로잉 이미지명</returns> private static string GetDrawingImageName(string elementName, ResourceKeyInfo resourceKeyInfo) { string sourceName = elementName + "DrawingImage"; return GetName(sourceName, resourceKeyInfo); } #endregion #region 드로잉 이미지 구하기 - GetDrawingImage(drawing) /// <summary> /// 드로잉 이미지 구하기 /// </summary> /// <param name="drawing">드로잉</param> /// <returns>드로잉 이미지</returns> private static DrawingImage GetDrawingImage(Drawing drawing) { return new DrawingImage(drawing); } #endregion #region XAML 구하기 - GetXAML(instance, includeRuntime) /// <summary> /// XAML 구하기 /// </summary> /// <param name="instance">인스턴스</param> /// <param name="includeRuntime">런타임 포함 여부</param> /// <returns>XAML</returns> private static string GetXAML(object instance, bool includeRuntime) { XmlXamlWriter writer = new XmlXamlWriter(new WpfDrawingSettings { IncludeRuntime = includeRuntime }); string xaml = writer.Save(instance); return xaml; } #endregion #region 클리핑 엘리먼트 구하기 - GetClippingElement(drawingGroupElement, rectangle) /// <summary> /// 클리핑 엘리먼트 구하기 /// </summary> /// <param name="drawingGroupElement">드로잉 그룹 엘리먼트</param> /// <param name="rectangle">사각형</param> /// <returns>클리핑 엘리먼트</returns> private static XElement GetClippingElement(XElement drawingGroupElement, out Rect rectangle) { rectangle = default(Rect); if(drawingGroupElement == null) { return null; } XElement clippingElement = drawingGroupElement.XPathSelectElement(".//defns:DrawingGroup.ClipGeometry", _xmlNamespaceManager); if(clippingElement != null) { XElement rectangleElement = clippingElement.Element(_defaultXMLNamespace + "RectangleGeometry"); if(rectangleElement != null) { XAttribute rectangleAttribute = rectangleElement.Attribute("Rect"); if(rectangleAttribute != null) { rectangle = Rect.Parse(rectangleAttribute.Value); return clippingElement; } } } return null; } #endregion #region 인라인 클리핑 추가하기 - AddInlineClipping(drawingElement) /// <summary> /// 인라인 클리핑 추가하기 /// </summary> /// <param name="drawingElement">드로잉 엘리먼트</param> private static void AddInlineClipping(XElement drawingElement) { Rect clippingRectangle; XElement clippingElement = GetClippingElement(drawingElement, out clippingRectangle); if(clippingElement != null && clippingElement.Parent.Name.LocalName == "DrawingGroup") { clippingElement.Parent.Add ( new XAttribute ( "ClipGeometry", string.Format ( CultureInfo.InvariantCulture, "M{0},{1} V{2} H{3} V{0} H{1} Z", clippingRectangle.Left, clippingRectangle.Top, clippingRectangle.Bottom, clippingRectangle.Right ) ) ); clippingElement.Remove(); } } #endregion #region 계단식 드로잉 그룹 제거하기 - RemoveCascadedDrawingGroup(drawingElement) /// <summary> /// 계단식 드로잉 그룹 제거하기 /// </summary> /// <param name="drawingElement">드로잉 엘리먼트</param> private static void RemoveCascadedDrawingGroup(XElement drawingElement) { IEnumerable<XElement> drawingGroupEnumerable = drawingElement.DescendantsAndSelf(_defaultXMLNamespace + "DrawingGroup"); foreach(XElement drawingGroup in drawingGroupEnumerable) { List<XElement> elementList = drawingGroup.Elements().ToList(); if(elementList.Count == 1 && elementList[0].Name.LocalName == "DrawingGroup") { XElement childDrawingGroup = elementList[0]; IEnumerable<XName> childAttributeNameEnumerable = childDrawingGroup.Attributes().Select(a => a.Name); IEnumerable<XName> attributeNameEnumerable = drawingGroup.Attributes().Select(a => a.Name); if(childAttributeNameEnumerable.Intersect(attributeNameEnumerable).Any()) { return; } drawingGroup.Add(childDrawingGroup.Attributes()); drawingGroup.Add(childDrawingGroup.Elements()); childDrawingGroup.Remove(); } } } #endregion #region 패스 지오메트리 축소하기 - CollapsePathGeometries(drawingElement) /// <summary> /// 패스 지오메트리 축소하기 /// </summary> /// <param name="drawingElement">드로잉 엘리먼트</param> private static void CollapsePathGeometries(XElement drawingElement) { XElement[] pathGeometryElementArray = drawingElement.Descendants(_defaultXMLNamespace + "PathGeometry").ToArray(); foreach(XElement pathGeometryElement in pathGeometryElementArray) { if ( pathGeometryElement.Parent != null && pathGeometryElement.Parent.Parent != null && pathGeometryElement.Parent.Parent.Name.LocalName == "GeometryDrawing" ) { List<string> attributeNameList = pathGeometryElement.Attributes().Select(a => a.Name.LocalName).ToList(); if ( attributeNameList.Count <= 2 && attributeNameList.Contains("Figures") && (attributeNameList.Contains("FillRule") || attributeNameList.Count == 1) ) { string figuresValue = pathGeometryElement.Attribute("Figures").Value; XAttribute fillRuleAttribute = pathGeometryElement.Attribute("FillRule"); if(fillRuleAttribute != null) { if(fillRuleAttribute.Value == "Nonzero") { figuresValue = "F1 " + figuresValue; // Nonzero } else { figuresValue = "F0 " + figuresValue; // EvenOdd } } pathGeometryElement.Parent.Parent.Add(new XAttribute("Geometry", figuresValue)); pathGeometryElement.Parent.Remove(); } } } } #endregion #region 드로잉 엘리먼트 명칭 설정하기 - SetDrawingElementName(drawingElement, name) /// <summary> /// 드로잉 엘리먼트 명칭 설정하기 /// </summary> /// <param name="drawingElement">드로잉 엘리먼트</param> /// <param name="name">명칭</param> private static void SetDrawingElementName(XElement drawingElement, string name) { if(string.IsNullOrWhiteSpace(name)) { return; } List<XAttribute> attributeList = drawingElement.Attributes().ToList(); attributeList.Insert(0, new XAttribute(_xXMLNamespace + "Key", name)); drawingElement.ReplaceAttributes(attributeList); } #endregion #region 드로잉 엘리먼트 정규화하기 - NormalizeDrawingElement(drawingElement, name) /// <summary> /// 드로잉 엘리먼트 정규화하기 /// </summary> /// <param name="drawingElement">드로잉 엘리먼트</param> /// <param name="name">명칭</param> private static void NormalizeDrawingElement(XElement drawingElement, string name) { AddInlineClipping(drawingElement); RemoveCascadedDrawingGroup(drawingElement); CollapsePathGeometries(drawingElement); SetDrawingElementName(drawingElement, name); } #endregion #region DIP당 픽셀 카운트 필터링하기 - FilterPixelCountPerDIP(drawingElement) /// <summary> /// DIP당 픽셀 카운트 필터링하기 /// </summary> /// <param name="drawingElement">드로잉 엘리먼트</param> private static void FilterPixelCountPerDIP(XElement drawingElement) { List<XElement> glyphRunElementList = drawingElement.Descendants(_defaultXMLNamespace + nameof(GlyphRun)).ToList(); foreach(XElement glyphRunElement in glyphRunElementList) { XAttribute pixelCountPerDIPAttribute = glyphRunElement.Attribute(nameof(GlyphRun.PixelsPerDip)); if(pixelCountPerDIPAttribute != null) { pixelCountPerDIPAttribute.Remove(); } } } #endregion #region 네임스페이스 선언 제거하기 - RemoveNamespaceDeclaration(source) /// <summary> /// 네임스페이스 선언 제거하기 /// </summary> /// <param name="source">소스 문자열</param> /// <returns>네임스페이서 선언 제거 문자열</returns> public static string RemoveNamespaceDeclaration(string source) { source = source.Replace(" xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"", ""); source = source.Replace(" xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\"", ""); return source; } #endregion } } |
▶ SVGData.cs
1 2 3 4 5 6 7 8 9 10 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 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 |
using System.IO; using System.Windows; namespace TestProject { /// <summary> /// SVG 데이터 /// </summary> public class SVGData { //////////////////////////////////////////////////////////////////////////////////////////////////// Field ////////////////////////////////////////////////////////////////////////////////////////// Private #region Field /// <summary> /// 파일 경로 /// </summary> private string filePath; /// <summary> /// 변환 객체 /// </summary> private DependencyObject convertedObject; /// <summary> /// 객체명 /// </summary> private string objectName; /// <summary> /// SVG 데이터 /// </summary> private string svg; /// <summary> /// XAML 데이터 /// </summary> private string xaml; #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Property ////////////////////////////////////////////////////////////////////////////////////////// Public #region 파일 경로 - FilePath /// <summary> /// 파일 경로 /// </summary> public string FilePath { get { return this.filePath; } set { this.filePath = value; } } #endregion #region 변환 객체 - ConvertedObject /// <summary> /// 변환 객체 /// </summary> public DependencyObject ConvertedObject { get { if(this.convertedObject == null) { this.convertedObject = SVGHelper.GetObject ( this.filePath, ConversionMode.DrawingImage, null, out this.objectName, new ResourceKeyInfo() ) as DependencyObject; } return this.convertedObject; } set { this.convertedObject = value; } } #endregion #region SVG - SVG /// <summary> /// SVG /// </summary> public string SVG { get { return this.svg ?? (this.svg = File.ReadAllText(this.filePath)); } set { this.svg = value; } } #endregion #region XAML - XAML /// <summary> /// XAML /// </summary> public string XAML { get { return this.xaml ?? (this.xaml = SVGHelper.GetXAML(ConvertedObject, false, this.objectName, false)); } set { this.xaml = value; } } #endregion } } |
▶ MainWindow.xaml
1 2 3 4 5 6 7 8 9 10 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 |
<Window x:Class="TestProject.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Width="800" Height="600" Title="SVG 파일을 XAML로 변환하기" FontFamily="나눔고딕코딩" FontSize="16"> <Grid> <Grid.ColumnDefinitions> <ColumnDefinition Width="*" /> <ColumnDefinition Width="Auto" /> <ColumnDefinition Width="10" /> <ColumnDefinition Width="Auto" /> <ColumnDefinition Width="*" /> </Grid.ColumnDefinitions> <Grid.RowDefinitions> <RowDefinition Height="*" /> <RowDefinition Height="Auto" /> <RowDefinition Height="10" /> <RowDefinition Height="Auto" /> <RowDefinition Height="*" /> </Grid.RowDefinitions> <Border Grid.Row="1" Grid.Column="1" HorizontalAlignment="Center" VerticalAlignment="Center" BorderThickness="1" BorderBrush="DarkGray"> <Image Name="image" Stretch="Uniform" Width="64" Height="64" /> </Border> <TextBox Name="textBox" Grid.Row="1" Grid.Column="3" Width="400" Height="400" HorizontalScrollBarVisibility="Auto" VerticalScrollBarVisibility="Auto" IsReadOnly="True" /> <Button Name="openFileButton" Grid.Row="3" Grid.Column="3" HorizontalAlignment="Right" VerticalAlignment="Bottom" Margin="20" Width="100" Height="30" Content="파일 열기" /> </Grid> </Window> |
▶ MainWindow.xaml.cs
1 2 3 4 5 6 7 8 9 10 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 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 |
using Microsoft.Win32; using System.Windows; using System.Windows.Media; namespace TestProject { /// <summary> /// 메인 윈도우 /// </summary> public partial class MainWindow : Window { //////////////////////////////////////////////////////////////////////////////////////////////////// Field ////////////////////////////////////////////////////////////////////////////////////////// Private #region Field /// <summary> /// 파일 열기 대화 상자 /// </summary> private OpenFileDialog openFileDialog; #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor ////////////////////////////////////////////////////////////////////////////////////////// Public #region 생성자 - MainWindow() /// <summary> /// 생성자 /// </summary> public MainWindow() { InitializeComponent(); this.openFileDialog = new OpenFileDialog(); this.openFileDialog.Filter = "SVG 파일 (*.svg)|*.svg"; this.openFileDialog.FilterIndex = 1; this.openFileDialog.DefaultExt = ".svg"; this.openFileButton.Click += openFileButton_Click; } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Private #region 파일 열기 버튼 클릭시 처리하기 - openFileButton_Click(sender, e) /// <summary> /// 파일 열기 버튼 클릭시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private void openFileButton_Click(object sender, RoutedEventArgs e) { bool result = this.openFileDialog.ShowDialog(this).GetValueOrDefault(); if(result) { SVGData data = SVGHelper.GetSVGData(this.openFileDialog.FileName); this.image.Source = data.ConvertedObject as DrawingImage; this.textBox.Text = data.XAML; } } #endregion } } |