Example #1
0
 /// <summary>
 /// Background task work method.
 /// </summary>
 private void DoPrepareSvg(object sender, DoWorkEventArgs e)
 {
     // Lock to allow only one of these operations at a time.
     lock (_updateLock)
     {
         KanjiDao dao = new KanjiDao();
         // Get the kanji strokes.
         KanjiStrokes strokes = dao.GetKanjiStrokes(_kanjiEntity.DbKanji.ID);
         if (strokes != null && strokes.FramesSvg.Length > 0)
         {
             // If the strokes was successfuly retrieved, we have to read the compressed SVG contained inside.
             SharpVectors.Renderers.Wpf.WpfDrawingSettings settings = new SharpVectors.Renderers.Wpf.WpfDrawingSettings();
             using (FileSvgReader r = new FileSvgReader(settings))
             {
                 // Unzip the stream and remove instances of "px" that are problematic for SharpVectors.
                 string svgString = StringCompressionHelper.Unzip(strokes.FramesSvg);
                 svgString    = svgString.Replace("px", string.Empty);
                 StrokesCount = Regex.Matches(svgString, "<circle").Count;
                 using (MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(svgString)))
                 {
                     // Then read the stream to a DrawingGroup.
                     // We are forced to do this operation on the UI thread because DrawingGroups must
                     // be always manipulated by the same thread.
                     DispatcherHelper.Invoke(() =>
                     {
                         StrokesDrawingGroup = r.Read(stream);
                         SetCurrentStroke(1);
                     });
                 }
             }
         }
     }
 }
Example #2
0
        internal static DrawingGroup SvgFileToWpfObject(string filepath, WpfDrawingSettings wpfDrawingSettings)
        {
            if (wpfDrawingSettings == null) //use defaults if null
                wpfDrawingSettings = new WpfDrawingSettings { IncludeRuntime = false, TextAsGeometry = false, OptimizePath = true };
            var reader = new FileSvgReader(wpfDrawingSettings);

            //this is straight forward, but in this version of the dlls there is an error when name starts with a digit
            //var uri = new Uri(Path.GetFullPath(filepath));
            //reader.Read(uri); //accessing using the filename results is problems with the uri (if the dlls are packed in ressources)
            //return reader.Drawing;

            //this should be faster, but using CreateReader will loose text items like "JOG" ?!
            //using (var stream = File.OpenRead(Path.GetFullPath(filepath)))
            //{
            //    //workaround: error when Id starts with a number
            //    var doc = XDocument.Load(stream);
            //    ReplaceIdsWithNumbers(doc.Root); //id="3d-view-icon" -> id="_3d-view-icon"
            //    using (var xmlReader = doc.CreateReader())
            //    {
            //        reader.Read(xmlReader);
            //        return reader.Drawing;
            //    }
            //}

            //workaround: error when Id starts with a number
            var doc = XDocument.Load(Path.GetFullPath(filepath));
            FixIds(doc.Root); //id="3d-view-icon" -> id="_3d-view-icon"
            using (var ms = new MemoryStream())
            {
                doc.Save(ms);
                ms.Position = 0;
                reader.Read(ms);
                return reader.Drawing;
            }
        }
Example #3
0
        private void OnWindowLoaded(object sender, RoutedEventArgs e)
        {
            // 1. Create conversion options
            WpfDrawingSettings settings = new WpfDrawingSettings();

            settings.IncludeRuntime = true;
            settings.TextAsGeometry = false;

            // 2. Select a file to be converted
            string svgTestFile = "Test.svg";

            // 3. Create a file reader
            FileSvgReader converter = new FileSvgReader(settings);
            // 4. Read the SVG file
            DrawingGroup drawing = converter.Read(svgTestFile);

            if (drawing != null)
            {
                svgImage.Source = new DrawingImage(drawing);

                using (StringWriter textWriter = new StringWriter())
                {
                    if (converter.Save(textWriter))
                    {
                        svgBox.Text = textWriter.ToString();
                    }
                }
            }
        }
        public static bool TryConvert(byte[] bytes, out DrawingGroup drawing)
        {
            drawing = null;
            if (bytes == null || bytes.Length == 0)
            {
                return(false);
            }

            using (var stream = new MemoryStream(bytes))
            {
                try
                {
                    var settings = new WpfDrawingSettings
                    {
                        IncludeRuntime = true,
                        TextAsGeometry = false
                    };

                    var converter = new FileSvgReader(settings);
                    drawing = converter.Read(stream);
                }
                catch (Exception)
                {
                    return(false);
                }
            }

            return(true);
        }
Example #5
0
        public static ImageSource GetSVGImageSource(string svgXml, out Exception svgException)
        {
            ImageSource imageSource = null;

            try
            {
                WpfDrawingSettings settings = new WpfDrawingSettings();
                settings.IncludeRuntime = true;
                settings.TextAsGeometry = true;
                settings.OptimizePath   = true;
                //settings.CultureInfo = ;

                using (var stringReader = new StringReader(svgXml))
                {
                    using (FileSvgReader reader = new FileSvgReader(settings))
                    {
                        DrawingGroup drawGroup = reader.Read(stringReader);

                        if (drawGroup != null)
                        {
                            svgException = null;
                            return(new DrawingImage(drawGroup));
                        }
                    }
                }
            }
            catch (Exception e1)
            {
                svgException = e1;
                return(null);
            }

            svgException = null;
            return(imageSource);
        }
Example #6
0
        public override object ProvideValue(IServiceProvider serviceProvider)
        {
            var settings = new WpfDrawingSettings
            {
                IncludeRuntime = IncludeRuntime,
                TextAsGeometry = TextAsGeometry,
                OptimizePath   = OptimizePath
            };

            if (Culture != null)
            {
                settings.CultureInfo = Culture;
            }
            using (FileSvgReader fileSvgReader = new FileSvgReader(settings))
            {
                using (var svgStream = new MemoryStream(Source))
                {
                    var drawingGroup = fileSvgReader.Read(svgStream);

                    if (Size.HasValue)
                    {
                        var rect = drawingGroup.Bounds;
                        drawingGroup.Transform = new ScaleTransform(Size.Value.Width / rect.Width, Size.Value.Height / rect.Height);
                    }
                    if (drawingGroup != null)
                    {
                        return(new DrawingImage(drawingGroup));
                    }
                }
            }
            return(null);
        }
Example #7
0
        private bool ConvertDocument()
        {
            try
            {
                if (string.IsNullOrWhiteSpace(_svgFilePath) || File.Exists(_svgFilePath) == false)
                {
                    return(false);
                }
                DrawingGroup drawing = _fileReader.Read(_svgFilePath, _directoryInfo);
                if (drawing == null)
                {
                    return(false);
                }

                if (_xamlPage != null && !string.IsNullOrWhiteSpace(_xamlFilePath))
                {
                    if (File.Exists(_xamlFilePath))
                    {
                        _xamlPage.LoadDocument(_xamlFilePath);

                        // Delete the file after loading it...
                        File.Delete(_xamlFilePath);
                    }
                }
                _currentDrawing = drawing;

                Rect drawingBounds = drawing.Bounds;

                svgDrawing.UnloadDiagrams();

                svgDrawing.RenderDiagrams(drawing);

                zoomPanControl.InvalidateMeasure();

                Rect bounds = drawing.Bounds;

                //zoomPanControl.AnimatedScaleToFit();
                //Rect rect = new Rect(0, 0,
                //    mainFrame.RenderSize.Width, mainFrame.RenderSize.Height);
                //Rect rect = new Rect(0, 0,
                //    bounds.Width, bounds.Height);
                if (bounds.IsEmpty)
                {
                    bounds = new Rect(0, 0, viewerFrame.ActualWidth, viewerFrame.ActualHeight);
                }
                zoomPanControl.AnimatedZoomTo(bounds);

                return(true);
            }
            catch (Exception ex)
            {
                //svgDrawing.Source = null;
                svgDrawing.UnloadDiagrams();

                this.ReportError(ex);

                return(false);
            }
        }
Example #8
0
 /// <see cref="IDiagramRenderer.Render(Stream)"/>
 public ImageSource Render(Stream imageData)
 {
     using (var reader = new StreamReader(imageData))
         using (var converter = new FileSvgReader(settings))
         {
             var drawingGroup = converter.Read(reader);
             return(CreateFrozenDrawing(drawingGroup));
         }
 }
Example #9
0
        public void Handwheel1() //pure svg# without any modifications
        {
            var           fileReader = new FileSvgReader(null);
            DrawingGroup  drawing    = fileReader.Read("TestFiles\\Handwheel.svg");
            XmlXamlWriter writer     = new XmlXamlWriter(null);
            var           xaml       = writer.Save(drawing);

            CheckXamlOutput(xaml);
        }
Example #10
0
        public void Handwheel1() //pure svg# without any modifications
        {
            var           fileReader = new FileSvgReader(null);
            DrawingGroup  drawing    = fileReader.Read("TestFiles\\Handwheel.svg");
            XmlXamlWriter writer     = new XmlXamlWriter(null);
            var           xaml       = writer.Save(drawing);

            Console.WriteLine(xaml);
            Clipboard.SetText(xaml);
        }
        public void LoadDocument(string svgFilePath, string pngFilePath)
        {
            this.UnloadDocument();

            BitmapImage bitmap = null;

            try
            {
                bitmap           = new BitmapImage(new Uri(pngFilePath));
                pngResult.Source = bitmap;
            }
            catch
            {
                throw;
            }

            try
            {
                DrawingGroup drawing = _fileReader.Read(svgFilePath, _directoryInfo);

                //if (bitmap != null)
                //{
                //    drawing.ClipGeometry = new RectangleGeometry(
                //        new Rect(0, 0, bitmap.Width, bitmap.Height));
                //}

                //svgDrawing.Source = new DrawingImage(drawing);

                svgDrawing.UnloadDiagrams();

                svgDrawing.RenderDiagrams(drawing);

                if (bitmap != null)
                {
                    //SvgDrawingCanvas drawCanvas = svgDrawing.DrawingCanvas;
                    viewBox.Width  = bitmap.Width;
                    viewBox.Height = bitmap.Height;
                    //svgDrawing.Width = bitmap.Width;
                    //svgDrawing.Height = bitmap.Height;

                    //SvgZoomableCanvas zoomableCanvas = svgDrawing.ZoomableCanvas;
                    ////zoomableCanvas.Width = bitmap.Width;
                    ////zoomableCanvas.Height = bitmap.Height;

                    //zoomableCanvas.FitWindow(new Size(bitmap.Width, bitmap.Height));
                }
            }
            catch
            {
                //svgDrawing.Source = null;
                svgDrawing.UnloadDiagrams();

                throw;
            }
        }
Example #12
0
        public static DrawingGroup SvgToDrawingGroup(Stream stream)
        {
            FileSvgReader reader = new FileSvgReader(new WpfDrawingSettings
            {
                CultureInfo    = CultureInfo.InvariantCulture,
                IncludeRuntime = true,
            });

            reader.Read(stream);
            return(reader.Drawing);
        }
Example #13
0
        private void UpdateDrawing(string svgFilePath)
        {
            var wpfSettings = new WpfDrawingSettings();

            wpfSettings.CultureInfo = wpfSettings.NeutralCultureInfo;
            using (var textReader = new StreamReader(svgFilePath))
            {
                using (var fileReader = new FileSvgReader(wpfSettings))
                {
                    _imageCount++;
                    try
                    {
                        if (_isVerbose)
                        {
                            this.AppendLine("Start Converting: " + svgFilePath);
                        }
                        else
                        {
                            _columnCount++;
                            AppendText("*");
                            if (_columnCount >= NumberOfColumns)
                            {
                                _columnCount = 0;
                                if (_imageCount < NumberOfImages)
                                {
                                    AppendLine(string.Empty);
                                }
                            }
                        }

                        fileReader.SaveXaml = false;
                        fileReader.SaveZaml = false;
                        var drawing = fileReader.Read(textReader);
                        drawing.Freeze();

                        AppendImage(drawing, Path.GetFileNameWithoutExtension(svgFilePath));

                        if (_isVerbose)
                        {
                            this.AppendLine("Completed Converting: " + svgFilePath);
                        }
                    }
                    catch (Exception ex)
                    {
                        if (_isVerbose)
                        {
                            AppendClear();
                        }
                        this.AppendLine("File: " + svgFilePath);
                        AppendError(ex.ToString());
                    }
                }
            }
        }
        public SVGExplorer(string svgFile)
        {
            FileSvgReader fr = new FileSvgReader(false, false,
                                                 new DirectoryInfo(Environment.CurrentDirectory),
                                                 null);

            fr.DrawingSettings.InteractiveMode = SvgInteractiveModes.Standard;              //PAUL: Updates!
            var dg = fr.Read(svgFile);

            constructFromDrawing(dg, fr.DrawingDocument);
        }
Example #15
0
        private DrawingImage LoadSvg(Stream svgStream)
        {
            if (svgStream == null)
            {
                return(null);
            }

            // Read the SVG file
            DrawingGroup drawing = _converter.Read(svgStream);

            if (drawing != null)
            {
                DomDocument = _converter.DomDocument;
                ISvgSvgElement root        = DomDocument.RootElement;
                Color?         fillColor   = GetColor(root, @"fill");
                Color?         strokeColor = GetColor(root, @"stroke");
                if (fillColor != null)
                {
                    _BackgroundColor.ARGB = CommonFunction.CovertColorToInt(fillColor.Value);
                    _bSupportBackground   = true;
                    FirePropertyChanged("vBackgroundColor");
                }

                if (strokeColor != null)
                {
                    _StrokeColor.ARGB = CommonFunction.CovertColorToInt(strokeColor.Value);
                    _bSupportBorder   = true;
                    FirePropertyChanged("vBorderLineColor");
                }


                string ratio = root.GetAttribute("preserveAspectRatio");
                if (string.IsNullOrEmpty(ratio))
                {
                    root.SetAttribute("preserveAspectRatio", "none");
                    GetApectRatio(root.GetAttribute("viewBox"));
                }

                MemoryStream stream = new MemoryStream();
                (DomDocument as SvgDocument).Save(stream);
                (_model as SVGModel).SVGUpdateStream = stream;
                return(new DrawingImage(drawing));
            }
            else
            {
                DomDocument         = null;
                _bSupportBackground = false;
                _bSupportBorder     = false;
                FirePropertyChanged("vBackgroundColor");
                FirePropertyChanged("vBorderLineColor");
                return(null);
            }
        }
Example #16
0
        /// <see cref="IDiagramRenderer.Render(Diagram)"/>
        public ImageSource Render(Diagram diagram)
        {
            if (diagram.ImageFile == null || !diagram.ImageFile.Exists)
            {
                return(null);
            }

            using (var converter = new FileSvgReader(settings))
            {
                var drawingGroup = converter.Read(diagram.ImageFile.FullName);
                return(CreateFrozenDrawing(drawingGroup));
            }
        }
Example #17
0
        public static ImageSource LoadTurtleImage()
        {
            var settings = new WpfDrawingSettings
            {
                IncludeRuntime = true,
                TextAsGeometry = false
            };

            var converter = new FileSvgReader(settings);
            var drawing   = converter.Read(Path.Combine(GetProjectDir(), "assets", "Turtle1.svg"));

            return(new DrawingImage(drawing));
        }
Example #18
0
        private void Part8Button_Click(object sender, RoutedEventArgs e)
        {
            if (!_part8Complete)
            {
                //var layersList = _segmentLayers.Select(p => p.Value).ToList();
                //_image.Layers = layersList;
                //_svgImage = ToSvgString(_image, _segmentLayers, _options.SvgRendering);
                _svgImage = new TracedImage(_segmentLayers, _loadedImage.Width, _loadedImage.Height).ToSvgString(_options.SvgRendering);
                File.WriteAllText(_outputFilename, _svgImage);

                //http://stackoverflow.com/questions/1879395/how-to-generate-a-stream-from-a-string
                using (MemoryStream stream = new MemoryStream())
                    using (StreamWriter writer = new StreamWriter(stream))
                    {
                        writer.Write(_svgImage);
                        writer.Flush();
                        stream.Position = 0;

                        var wpfSettings = new WpfDrawingSettings();
                        wpfSettings.CultureInfo = wpfSettings.NeutralCultureInfo;
                        var reader = new FileSvgReader(wpfSettings);
                        _renderedSvg = reader.Read(stream);

                        //ZoomPanControl.ScaleToFit();
                        //CanvasScroller.Visibility = Visibility.Visible;
                    }

                //SvgViewer.UnloadDiagrams();


                CanvasScroller.Visibility = Visibility.Hidden;
                SvgViewer.RenderDiagrams(_renderedSvg);

                Rect bounds = SvgViewer.Bounds;
                if (bounds.IsEmpty)
                {
                    bounds = new Rect(0, 0, CanvasScroller.ActualWidth, CanvasScroller.ActualHeight);
                }

                ZoomPanControl.AnimatedZoomTo(bounds);

                _part8Complete = true;
                //Part8Button.IsEnabled = false;
            }
            else
            {
                CanvasScroller.Visibility = Visibility.Visible;
            }

            ImageDisplay.Source = BitmapToImageSource(CreateTransparentBitmap(_loadedImage.Width + 1, _loadedImage.Height + 1));
        }
Example #19
0
        public static DrawingGroup SvgToDrawingGroup(string svgStr)
        {
            WpfDrawingSettings settings = new WpfDrawingSettings
            {
                CultureInfo    = CultureInfo.InvariantCulture,
                IncludeRuntime = true,
            };

            using (FileSvgReader reader = new FileSvgReader(settings))
            {
                reader.Read(svgStr);
                return(reader.Drawing);
            }
        }
        public static DrawingGroup ConvertToDrawingGroup(string svgContent)
        {
            var settings = new WpfDrawingSettings
            {
                IncludeRuntime = false,
                TextAsGeometry = false,
                OptimizePath   = true
            };

            var converter = new FileSvgReader(settings);

            using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(svgContent)))
            {
                return(converter.Read(stream));
            }
        }
Example #21
0
        public static DrawingGroup SvgFileToWpfObject(string filepath)
        {
            var wpfDrawingSettings = new WpfDrawingSettings {
                IncludeRuntime = false, TextAsGeometry = false, OptimizePath = true
            };
            var reader = new FileSvgReader(wpfDrawingSettings);

            //workaround: error when Id starts with a number
            var doc = XDocument.Load(filepath);

            FixIds(doc.Root); //id="3d-view-icon" -> id="_3d-view-icon"
            using (var ms = new MemoryStream())
            {
                doc.Save(ms);
                ms.Position = 0;
                reader.Read(ms);
                return(reader.Drawing);
            }
        }
        public static string ConvertToXaml(string svgContent)
        {
            var settings = new WpfDrawingSettings
            {
                IncludeRuntime = false,
                TextAsGeometry = false,
                OptimizePath   = true
            };

            var converter = new FileSvgReader(settings);

            using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(svgContent)))
            {
                var dg = converter.Read(stream);
                SetSizeToGeometries(dg);
                RemoveObjectNames(dg);

                return(SvgObjectToXaml(new DrawingImage(dg), settings.IncludeRuntime, "Icon"));
            }
        }
Example #23
0
        /// <summary>
        /// Creates an image source from a local image.
        /// </summary>
        /// <param name="imagePath">The path to the image, or the name of the icon in the assets directory.</param>
        /// <param name="color">The color, for monochrome vectors.</param>
        /// <returns>null if the image is not supported.</returns>
        public static ImageSource?CreateImageSource(string imagePath, Color?color = null)
        {
            ImageSource?result;

            try
            {
                if (!imagePath.Contains('/'))
                {
                    imagePath = GetBarIconFile(imagePath) ?? imagePath;
                }

                if (Path.GetExtension(imagePath) == ".svg")
                {
                    using FileSvgReader svg = new FileSvgReader(new WpfDrawingSettings());
                    DrawingGroup drawingGroup = svg.Read(imagePath);
                    if (color.HasValue)
                    {
                        ChangeDrawingColor(drawingGroup, color.Value);
                    }
                    result = new DrawingImage(drawingGroup);
                }
                else
                {
                    BitmapImage image = new BitmapImage();
                    image.BeginInit();
                    image.CacheOption = BitmapCacheOption.OnLoad;
                    image.UriSource   = new Uri(imagePath);
                    image.EndInit();

                    result = image;
                }
            }
            catch (Exception e) when(e is NotSupportedException || e is XmlException || e is SvgException)
            {
                result = null;
            }

            return(result);
        }
Example #24
0
        private async void RebuildDcr(string rawDcr, string editWindowString, string name = "Full merge graph", bool buildInMemoryDcr = true)
        {
            var dcrGraph = _dcrGraph;

            try
            {
                var svg = await DcrToSvg.GetSvgFromDcr(rawDcr);

                var settings = new WpfDrawingSettings
                {
                    IncludeRuntime = true,
                    TextAsGeometry = true,
                    OptimizePath   = true
                };

                var converter = new FileSvgReader(settings);

                var drawingGroup = converter.Read(new MemoryStream(Encoding.UTF8.GetBytes(svg)));

                Model.DcrImage = new DrawingImage(drawingGroup);

                if (buildInMemoryDcr)
                {
                    dcrGraph = new DcrGraph(rawDcr, dcrGraph?.StrictActivities, editWindowString, name);
                }
            }
            catch (Exception e)
            {
                return;
            }
            _dcrGraph = dcrGraph;

            //Used if need to be able to execute
            //Model.Events.Clear();
            //foreach (var activity in _dcrGraph.GetExecutableActivityNames())
            //{
            //    Model.Events.Add(activity);
            //}
        }
        public ImageSource GetImageSource(byte[] bytes)
        {
            var settings = new WpfDrawingSettings();

            using (var fileSvgReader = new FileSvgReader(settings))
            {
                using (var svgStream = new MemoryStream(bytes))
                {
                    var drawingGroup = fileSvgReader.Read(svgStream);

                    if (_size.HasValue)
                    {
                        var rect = drawingGroup.Bounds;
                        drawingGroup.Transform = new ScaleTransform(_size.Value.Width / rect.Width, _size.Value.Height / rect.Height);
                    }
                    if (drawingGroup != null)
                    {
                        return(new DrawingImage(drawingGroup));
                    }
                    return(null);
                }
            }
        }
Example #26
0
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            var image = new Image();

            image.Stretch = Stretch.Uniform;

            if (value is string imagePaths)
            {
                var imagePath = new FileInfo(imagePaths);

                if (imagePath.Extension.ToUpper() == ".SVG")
                {
                    var settings = new WpfDrawingSettings
                    {
                        TextAsGeometry = false,
                        IncludeRuntime = true,
                    };

                    var converter = new FileSvgReader(settings);

                    var drawing = converter.Read(imagePath.FullName);

                    if (drawing != null)
                    {
                        var drawImage = new DrawingImage(drawing);
                        image.Source = drawImage;
                    }
                }
                else
                {
                    var bitmapSource = new BitmapImage(new Uri(imagePath.FullName));
                    image.Source = bitmapSource;
                }
            }

            return(image);
        }
Example #27
0
        private DrawingImage LoadSvg(Stream svgStream)
        {
            if (svgStream == null)
            {
                return(null);
            }

            // Create conversion options
            WpfDrawingSettings settings = new WpfDrawingSettings();

            settings.IncludeRuntime = true;
            settings.TextAsGeometry = false;

            // Create a file reader
            FileSvgReader converter = new FileSvgReader(settings);
            // Read the SVG file
            DrawingGroup drawing = converter.Read(svgStream);

            if (drawing != null)
            {
                return(new DrawingImage(drawing));
            }
            return(null);
        }
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            var dravingImage = new DrawingImage();

            if (!(value is FileEntityViewModel viewModel))
            {
                return(dravingImage);
            }

            var imagePath = ChromEr.Instance.IconsManager.GetIconPath(viewModel);

            if (imagePath.Extension.ToUpper() == ".SVG")
            {
                var settings = new WpfDrawingSettings
                {
                    TextAsGeometry = false,
                    IncludeRuntime = true,
                };

                var converter = new FileSvgReader(settings);

                var drawing = converter.Read(imagePath.FullName);

                if (drawing != null)
                {
                    return(new DrawingImage(drawing));
                }
            }
            else
            {
                var bitmapSource = new BitmapImage(new Uri(imagePath.FullName));
                return(bitmapSource);
            }

            return(dravingImage);
        }
        protected DrawingImage getCachedImageFromName(string name)
        {
            if (_cache.ContainsKey(name))
            {
                return(_cache[name]);
            }
            try
            {
                StreamResourceInfo sri = Application.GetResourceStream(new Uri(string.Format("Resources/symbols/{0}.svg", name), UriKind.Relative));
                if (sri != null)
                {
                    using (Stream s = sri.Stream)
                    {
                        return(_cache[name] = new DrawingImage(converter.Read(sri.Stream)));
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(name + ":" + e.Message);
            }

            return(null);
        }
Example #30
0
        /// <summary>
        /// This converts the SVG resource specified by the Uri to <see cref="DrawingGroup"/>.
        /// </summary>
        /// <param name="svgSource">A <see cref="Uri"/> specifying the source of the SVG resource.</param>
        /// <returns>A <see cref="DrawingGroup"/> of the converted SVG resource.</returns>
        private DrawingGroup GetDrawing(Uri svgSource)
        {
            WpfDrawingSettings settings = new WpfDrawingSettings();

            settings.IncludeRuntime = false;
            settings.TextAsGeometry = true;
            settings.OptimizePath   = true;

            StreamResourceInfo svgStreamInfo = null;

            if (svgSource.ToString().IndexOf("siteoforigin", StringComparison.OrdinalIgnoreCase) >= 0)
            {
                svgStreamInfo = Application.GetRemoteStream(svgSource);
            }
            else
            {
                svgStreamInfo = Application.GetResourceStream(svgSource);
            }

            Stream svgStream = (svgStreamInfo != null) ? svgStreamInfo.Stream : null;

            if (svgStream != null)
            {
                string fileExt      = IoPath.GetExtension(svgSource.ToString());
                bool   isCompressed = !string.IsNullOrWhiteSpace(fileExt) &&
                                      string.Equals(fileExt, ".svgz", StringComparison.OrdinalIgnoreCase);

                if (isCompressed)
                {
                    using (svgStream)
                    {
                        using (var zipStream = new GZipStream(svgStream, CompressionMode.Decompress))
                        {
                            using (FileSvgReader reader = new FileSvgReader(settings))
                            {
                                DrawingGroup drawGroup = reader.Read(zipStream);

                                if (drawGroup != null)
                                {
                                    return(drawGroup);
                                }
                            }
                        }
                    }
                }
                else
                {
                    using (svgStream)
                    {
                        using (FileSvgReader reader = new FileSvgReader(settings))
                        {
                            DrawingGroup drawGroup = reader.Read(svgStream);

                            if (drawGroup != null)
                            {
                                return(drawGroup);
                            }
                        }
                    }
                }
            }

            return(null);
        }