private SvgSvgElement MoveIntoSvgElement()
        {
            SvgDocument   doc    = _patternElement.OwnerDocument;
            SvgSvgElement svgElm = doc.CreateElement("", "svg", SvgDocument.SvgNamespace) as SvgSvgElement;

            XmlNodeList children = _patternElement.Children;

            if (children.Count > 0)
            {
                oldParent = children[0].ParentNode as XmlElement;
            }

            for (int i = 0; i < children.Count; i++)
            {
                svgElm.AppendChild(children[i]);
            }

            if (_patternElement.HasAttribute("viewBox"))
            {
                svgElm.SetAttribute("viewBox", _patternElement.GetAttribute("viewBox"));
            }
            svgElm.SetAttribute("x", "0");
            svgElm.SetAttribute("y", "0");
            svgElm.SetAttribute("width", _patternElement.GetAttribute("width"));
            svgElm.SetAttribute("height", _patternElement.GetAttribute("height"));

            if (_patternElement.PatternContentUnits.AnimVal.Equals((ushort)SvgUnitType.ObjectBoundingBox))
            {
                svgElm.SetAttribute("viewBox", "0 0 1 1");
            }

            _patternElement.AppendChild(svgElm);

            return(svgElm);
        }
Пример #2
0
        private Drawing GetImage(WpfDrawingContext context)
        {
            WpfDrawingRenderer renderer = new WpfDrawingRenderer();

            renderer.Window = _patternElement.OwnerDocument.Window as SvgWindow;

            WpfDrawingSettings settings = context.Settings.Clone();

            settings.TextAsGeometry = true;
            WpfDrawingContext patternContext = new WpfDrawingContext(true, settings);

            patternContext.Initialize(null, context.FontFamilyVisitor, null);

            SvgSvgElement elm = MoveIntoSvgElement();

            renderer.Render(elm, patternContext);
            DrawingGroup rootGroup = renderer.Drawing;

            MoveOutOfSvgElement(elm);

            if (rootGroup.Children.Count == 1)
            {
                return(rootGroup.Children[0]);
            }

            return(rootGroup);
        }
        public string BuildSvg(Page page)
        {
            //this.Page = page;
            //this.Origin = new PointF(page.Width / 2, page.Height / 2);

            this.Root = new SvgSvgElement(
                page.SvgLengthWidth, page.SvgLengthHeight,
                new SvgNumList(new float[] { -page.Width / 2, -page.Height / 2, page.Width, page.Height }));

            SvgGroupElement mainGroup = new SvgGroupElement("Main");

            mainGroup.Style = s_MajorLineStyle;
            this.Root.AddChild(mainGroup);

            float outerRadius = 40f;

            AddCenteredCircle(mainGroup, outerRadius);
            AddCenteredCircle(mainGroup, 24.7f);
            AddCenteredCircle(mainGroup, 7.5f);
            AddGuideLines(mainGroup, outerRadius);

            float sideLength = 59f;
            float radius     = sideLength / 2f / (float)Math.Cos(30.0 / 180.0 * Math.PI);

            AddCenteredTriangle(mainGroup, sideLength, radius);
            AddCenteredCircle(mainGroup, radius);

            AddRays(mainGroup, outerRadius);

            return(this.Root.WriteSVGString(true, false));
        }
Пример #4
0
        private DrawingGroup CreateOuterGroup()
        {
            DrawingGroup drawGroup = null;

            SvgSvgElement svgElm = (SvgSvgElement)_svgElement;

            ISvgAnimatedPreserveAspectRatio animatedAspectRatio = svgElm.PreserveAspectRatio;

            if (animatedAspectRatio == null || animatedAspectRatio.AnimVal == null)
            {
                return(drawGroup);
            }

            double x      = svgElm.X.AnimVal.Value;
            double y      = svgElm.Y.AnimVal.Value;
            double width  = svgElm.Width.AnimVal.Value;
            double height = svgElm.Height.AnimVal.Value;

            if (width.Equals(0.0) || height.Equals(0.0))
            {
                return(drawGroup);
            }

            Rect clipRect = new Rect(x, y, width, height);

            if (!clipRect.IsEmpty)
            {
                drawGroup = new DrawingGroup();
                drawGroup.ClipGeometry = new RectangleGeometry(clipRect);
            }

            return(drawGroup);
        }
Пример #5
0
        public void Render(SvgDocument docElement)
        {
            var baseUrl = docElement.BaseURI;

            var context = _renderer.Context;

            if (!string.IsNullOrWhiteSpace(baseUrl) && context != null)
            {
                context.AddUrl(baseUrl);

                var window = docElement.Window;
                if (window != null && window.BaseUrls == null)
                {
                    window.BaseUrls = context.BaseUrls;
                }
            }

            SvgSvgElement root = docElement.RootElement as SvgSvgElement;

            if (root != null)
            {
                this.Render(root);
            }

            if (!string.IsNullOrWhiteSpace(baseUrl) && context != null)
            {
                context.RemoveUrl(baseUrl);
            }
        }
Пример #6
0
        private void OnAfterRender(WpfDrawingRenderer renderer)
        {
            Debug.Assert(_drawGroup != null);

            // Support for Tiny 1.2 viewport-fill property...
            if (_svgElement.HasAttribute("viewport-fill"))
            {
                var viewportFill = _svgElement.GetAttribute("viewport-fill");
                if (!string.IsNullOrWhiteSpace(viewportFill))
                {
                    SvgSvgElement svgElm = (SvgSvgElement)_svgElement;

                    var brush = WpfFill.CreateViewportBrush(svgElm);
                    if (brush != null)
                    {
                        var bounds  = new RectangleGeometry(_drawGroup.Bounds);
                        var drawing = new GeometryDrawing(brush, null, bounds);

                        _drawGroup.Children.Insert(0, drawing);
                    }
                }
            }

            WpfDrawingContext context = renderer.Context;

            DrawingGroup currentGroup = context.Peek();

            if (currentGroup == null || currentGroup != _drawGroup)
            {
                throw new InvalidOperationException("An existing group is expected.");
            }

            context.Pop();

            if (_isRoot && !context.IsFragment)
            {
                this.AdjustViewbox();
            }
            if (_isRoot || context.IsFragment)
            {
                return;
            }

            DrawingGroup drawGroup = CreateOuterGroup();

            if (drawGroup == null)
            {
                return;
            }

            currentGroup = context.Peek();
            if (currentGroup == null || currentGroup.Children.Remove(_drawGroup) == false)
            {
                return;
            }

            drawGroup.Children.Add(_drawGroup);
            currentGroup.Children.Add(drawGroup);
        }
Пример #7
0
 public SvgElementToDynamicPdfElementConverter(SvgSvgElement rootSvgElement, VectorElementPdfPageViewport pageViewport, float pageHeight, PdfSpotColor spotColorOverride)
 {
     _spotColorOverride = spotColorOverride;
     _rootSvgElement    = rootSvgElement ?? throw new ArgumentNullException(nameof(rootSvgElement));
     _pageViewport      = pageViewport ?? throw new ArgumentNullException(nameof(pageViewport));
     _pageHeight        = pageHeight;
     _matrixStack.Push(SvgMatrix.Identity);
 }
Пример #8
0
        private void MoveOutOfSvgElement(SvgSvgElement svgElm)
        {
            while (svgElm.ChildNodes.Count > 0)
            {
                oldParent.AppendChild(svgElm.ChildNodes[0]);
            }

            _patternElement.RemoveChild(svgElm);
        }
        public GridBuilder2(Page page, float originOffset)
        {
            this.Page = page;

            this.Origin = new PointF(this.Page.Width / 2, originOffset);
            this.Root   = new SvgSvgElement(
                GetSvgLength(this.Page.Width),
                GetSvgLength(this.Page.Height));
        }
        public void Render(SvgDocument docElement)
        {
            SvgSvgElement root = docElement.RootElement as SvgSvgElement;

            if (root != null)
            {
                this.Render(root);
            }
        }
Пример #11
0
        private void AddEncoderRing(SvgSvgElement root, EncoderRing encoderRing, int index)
        {
            if (encoderRing == null)
            {
                return;
            }

            encoderRing.InsertSvg(root, index);
        }
Пример #12
0
        public void InsertSvg(SvgSvgElement root, int index)
        {
            SvgGroupElement slicesGroup = new SvgGroupElement("Slices" + index.ToString());

            slicesGroup.Style = s_FilledWhite;
            root.AddChild(slicesGroup);

            InsertSlices(slicesGroup);
            // Add inner black disk
            root.AddChild(EncoderDisk.CreateCenteredCircle(this.OuterRadius - this.SlotLength, s_FilledBlack));
        }
Пример #13
0
        private Image GetImage(RectangleF bounds)
        {
            _patternElement.PatternBounds = new SvgRect(bounds.X, bounds.Y, bounds.Width, bounds.Height);

            // For single image pattern...
            if (_patternElement.ChildNodes.Count == 1)
            {
                var imageElement = _patternElement.ChildNodes[0] as SvgImageElement;
                if (imageElement != null)
                {
                    var image = GdiImageRendering.GetBitmap(imageElement);
                    if (image != null)
                    {
                        return(image);
                    }
                }
            }

            GdiGraphicsRenderer renderer = new GdiGraphicsRenderer(true, false);
            var svgWindow   = _patternElement.OwnerDocument.Window as SvgWindow;
            var ownedWindow = svgWindow.CreateOwnedWindow();

            renderer.Window = ownedWindow;

            SvgSvgElement elm = MoveIntoSvgElement();

            int winWidth  = (int)elm.Width.BaseVal.Value;
            int winHeight = (int)elm.Height.BaseVal.Value;

            if (winWidth == 0 || winHeight == 0)
            {
                var size = elm.GetSize();
                if (size.Width.Equals(0) || size.Height.Equals(0))
                {
                    winWidth  = (int)bounds.Width;
                    winHeight = (int)bounds.Height;
                }
                else
                {
                    winWidth  = (int)size.Width;
                    winHeight = (int)size.Height;
                }
            }

            ownedWindow.Resize(winWidth, winHeight);

            renderer.Render(elm as SvgElement);
            Image img = renderer.RasterImage;

            MoveOutOfSvgElement(elm);

            return(img);
        }
Пример #14
0
        internal void Build(Wheel wheel, SvgSvgElement root)
        {
            SvgGroupElement helperLinesGroup = new SvgGroupElement("HelperLines");

            helperLinesGroup.Style = Styles.HelperLineStyle;
            root.AddChild(helperLinesGroup);

            // Wheel pitch circle
            helperLinesGroup.AddChild(SvgHelper.CreateCircle(wheel.Center, wheel.PitchDiameter / 2.0));

            // Wheel addendum circle
            helperLinesGroup.AddChild(SvgHelper.CreateCircle(wheel.Center, wheel.PitchDiameter / 2.0 + wheel.Addendum));

            // Wheel dedendum circle
            helperLinesGroup.AddChild(SvgHelper.CreateCircle(wheel.Center, wheel.PitchDiameter / 2.0 - wheel.Dedendum));

            // wheel center
            double halfCrossLength = 10;

            helperLinesGroup.AddChild(new SvgLineElement(wheel.Center.X - halfCrossLength, wheel.Center.Y, wheel.Center.X + halfCrossLength, wheel.Center.Y));
            helperLinesGroup.AddChild(new SvgLineElement(wheel.Center.X, wheel.Center.Y - halfCrossLength, wheel.Center.X, wheel.Center.Y + halfCrossLength));


            SvgGroupElement mainGroup = new SvgGroupElement("Main");

            mainGroup.Style = Styles.MinorLineStyle;
            root.AddChild(mainGroup);


            WheelTooth[]  teeth       = wheel.GetTeeth(0);
            StringBuilder pathBuilder = new StringBuilder();

            pathBuilder.AppendFormat(CultureInfo.InvariantCulture, "M{0},{1}", (float)teeth[0].DedendumIntersectLeft.X, (float)teeth[0].DedendumIntersectLeft.Y);
            for (int i = 0; i < teeth.Length; i++)
            {
                WheelTooth tooth     = teeth[i];
                WheelTooth nextTooth = teeth[(i + 1) % teeth.Length];
                InsertWheelToothPath(wheel, tooth, nextTooth, pathBuilder);
            }
            pathBuilder.Append(" z");

            SvgPath        svgPath        = new SvgPath(pathBuilder.ToString());
            SvgPathElement svgPathElement = new SvgPathElement();

            svgPathElement.D = svgPath;

            mainGroup.AddChild(svgPathElement);

            if (wheel.CenterHoleDiameter > 0)
            {
                mainGroup.AddChild(SvgHelper.CreateCircle(wheel.Center, wheel.CenterHoleDiameter / 2.0));
            }
        }
Пример #15
0
        private Image getImage(RectangleF bounds)
        {
            GdiRenderer renderer = new GdiRenderer();

            renderer.Window = _patternElement.OwnerDocument.Window as SvgWindow;

            SvgSvgElement elm = moveIntoSvgElement();

            Image img = renderer.Render(elm as SvgElement);

            moveOutOfSvgElement(elm);

            return(img);
        }
Пример #16
0
        public override void Render(ISvgRenderer renderer)
        {
            GraphicsWrapper graphics = ((GdiRenderer)renderer).GraphicsWrapper;

            SvgSvgElement svgElm = (SvgSvgElement)element;

            float x      = (float)svgElm.X.AnimVal.Value;
            float y      = (float)svgElm.Y.AnimVal.Value;
            float width  = (float)svgElm.Width.AnimVal.Value;
            float height = (float)svgElm.Height.AnimVal.Value;

            RectangleF elmRect = new RectangleF(x, y, width, height);

            fitToViewbox(graphics, elmRect);
        }
Пример #17
0
        private void InvalidateAndRender()
        {
            try
            {
                if (_svgRenderer != null)
                {
                    SvgSvgElement svgEl = (SvgSvgElement)_svgWindow.Document.RootElement;

                    SvgSizeF r = svgEl.GetSize();

                    int winWidth  = (int)svgEl.Width.BaseVal.Value;
                    int winHeight = (int)svgEl.Height.BaseVal.Value;

                    if (!r.Width.Equals(0.0) && !r.Height.Equals(0.0) && (r.Width * 4 * r.Height) < BitmapLimit)
                    {
                        winWidth  = (int)r.Width;
                        winHeight = (int)r.Height;
                    }
                    if ((winWidth * 4 * winHeight) >= BitmapLimit)
                    {
                        winWidth  = this.Width;
                        winHeight = this.Height;
                    }

                    _svgWindow.Resize(winWidth, winHeight);

                    _svgRenderer.Render(_svgWindow.Document as SvgDocument);
                }
            }
            catch (Exception ex)
            {
                Trace.TraceError(ex.ToString());

                if (this.DesignMode)
                {
                    return;
                }

                var errorArgs = new SvgErrorArgs("An exception occurred while rendering", ex);
                _svgErrors?.Invoke(this, errorArgs);
                if (!errorArgs.Handled)
                {
                    MessageBox.Show(errorArgs.Message + ": " + ex.Message,
                                    _appTitle, MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }
Пример #18
0
        public override PageElement VisitSvgElement(SvgSvgElement element)
        {
            if (element.IsOutermost)
            {
                return(EstablishViewportThen(element, element.ViewWidth, element.ViewHeight, VisitStructuralElement, element));
            }
            var tx = element.X?.Value ?? 0;
            var ty = element.Y?.Value ?? 0;

            PushMatrix(SvgMatrix.CreateTranslate(tx, ty));
            var viewportWidth  = element.Width ?? 0;
            var viewportHeight = element.Height ?? 0;
            var result         = EstablishViewportThen(element, viewportWidth, viewportHeight, VisitStructuralElement, element);

            PopMatrix();
            return(result);
        }
Пример #19
0
        private string BuildSvg()
        {
            m_Root = new SvgSvgElement(
                m_Page.SvgLengthWidth, m_Page.SvgLengthHeight,
                new SvgNumList(new float[] { -m_Page.Width / 2, -m_Page.Height / 2, m_Page.Width, m_Page.Height }));

            SvgGroupElement mainGroup = new SvgGroupElement("Main");

            for (int xIndex = 0; xIndex < m_XCount; xIndex++)
            {
                for (int yIndex = 0; yIndex < m_YCount; yIndex++)
                {
                    InsertSquare(mainGroup, xIndex, yIndex);
                }
            }

            m_Root.AddChild(mainGroup);
            return(m_Root.WriteSVGString(true, false));
        }
Пример #20
0
        public static void SaveSvg(SvgSvgElement svg, string path)
        {
            // Make sure the output directory exists
            var outDir = Path.GetDirectoryName(path);

            if (!Directory.Exists(outDir))
            {
                Console.WriteLine("Creating output directory: {0}.", outDir);
                Directory.CreateDirectory(outDir);
            }

            // Write the SVG
            using (var writer = new StreamWriter(path))
            {
                Svg.Save(svg, writer);
            }

            // Tell the user where we wrote it
            Console.WriteLine("Wrote SVG to {0}.", path);
        }
Пример #21
0
        public override void Render(ISvgRenderer renderer)
        {
            GraphicsWrapper graphics = ((GdiRenderer)renderer).GraphicsWrapper;

            SvgSvgElement svgElm = (SvgSvgElement)element;

            float x      = (float)svgElm.X.AnimVal.Value;
            float y      = (float)svgElm.Y.AnimVal.Value;
            float width  = (float)svgElm.Width.AnimVal.Value;
            float height = (float)svgElm.Height.AnimVal.Value;

            RectangleF elmRect = new RectangleF(x, y, width, height);

            if (element.ParentNode is SvgElement)
            {
                // TODO: should it be moved with x and y?
            }

            fitToViewbox(graphics, elmRect);
        }
        public override void Render(GdiGraphicsRenderer renderer)
        {
            var graphics = renderer.GdiGraphics;

            SvgSvgElement svgElm = (SvgSvgElement)_svgElement;

            float x      = (float)svgElm.X.AnimVal.Value;
            float y      = (float)svgElm.Y.AnimVal.Value;
            float width  = (float)svgElm.Width.AnimVal.Value;
            float height = (float)svgElm.Height.AnimVal.Value;

            RectangleF elmRect = new RectangleF(x, y, width, height);

            //if (element.ParentNode is SvgElement)
            //{
            //    // TODO: should it be moved with x and y?
            //}

            FitToViewbox(graphics, elmRect);
        }
Пример #23
0
        public string BuildSvg(Page page)
        {
            SvgSvgElement root = new SvgSvgElement(
                page.SvgLengthWidth, page.SvgLengthHeight,
                new SvgNumList(new float[] { -page.Width / 2, -page.Height / 2, page.Width, page.Height }));

            root.AddChild(CreateCenteredCircle(this.OuterRadius, s_FilledBlack));

            // Add encoder rings
            AddEncoderRing(root, this.OuterEncoderRing, 1);
            AddEncoderRing(root, this.InnerEncoderRing, 2);

            root.AddChild(CreateCenteredCircle(this.CenterHoleRadius, s_FilledWhite));

            SvgGroupElement crossLinesGroup = new SvgGroupElement("CrossLines");

            crossLinesGroup.Style = s_NormalLineStyle;
            root.AddChild(crossLinesGroup);
            AddGuideLines(crossLinesGroup, (float)this.CenterHoleRadius);

            return(root.WriteSVGString(true, false));
        }
Пример #24
0
        public string Build()
        {
            double border = 5;             // border around grahics in mm

            Wheel  wheel  = m_CycloidalGear.Wheel;
            Pinion pinion = m_CycloidalGear.Pinion;

            double pageWidth  = wheel.Addendum + wheel.PitchDiameter + pinion.PitchDiameter + pinion.Addendum + 2 * border;
            double pageHeight = 2 * wheel.Addendum + wheel.PitchDiameter + 2 * border;
            Page   page       = new Page((float)pageWidth, (float)pageHeight, SvgLengthType.SVG_LENGTHTYPE_MM);

            SvgSvgElement root = new SvgSvgElement(
                page.SvgLengthWidth, page.SvgLengthHeight,
                new SvgNumList(new float[] { -(float)(wheel.Addendum + wheel.PitchDiameter / 2.0 + border), -page.Height / 2, page.Width, page.Height }));

            wheel.Center  = new Point(0, 0);
            pinion.Center = wheel.Center + new Vector(m_CycloidalGear.WheelPinionDistance, 0);

            new WheelGenerator().Build(m_CycloidalGear.Wheel, root);
            new PinionGenerator().Build(m_CycloidalGear.Pinion, root);

            return(root.WriteSVGString(true));
        }
Пример #25
0
        protected virtual void Load()
        {
            try
            {
                if (!string.IsNullOrWhiteSpace(_svgSource))
                {
                    // Load the source
                    _svgWindow.Source = _svgSource;
                    // Initialize the style sheets
                    SetupStyleSheets();
                    // Execute all script elements
                    //UnloadEngines();
                    //InitializeEvents();
                    //ExecuteScripts();

                    SvgSvgElement svgEl = (SvgSvgElement)_svgWindow.Document.RootElement;
                    SvgSizeF      r     = svgEl.GetSize();

                    int winWidth  = (int)svgEl.Width.BaseVal.Value;
                    int winHeight = (int)svgEl.Height.BaseVal.Value;
                    if (!r.Width.Equals(0.0) && !r.Height.Equals(0.0) && (r.Width * 4 * r.Height) < BitmapLimit)
                    {
                        winWidth  = (int)r.Width;
                        winHeight = (int)r.Height;
                    }
                    if ((winWidth * 4 * winHeight) >= BitmapLimit)
                    {
                        winWidth  = this.Width;
                        winHeight = this.Height;
                    }

                    _svgWindow.Resize(winWidth, winHeight);

                    _svgRenderer.InvalidRect = SvgRectF.Empty;

                    this.Render();
                    _isSvgLoaded = true;
                }
                else if (!string.IsNullOrWhiteSpace(_xmlSource) && _xmlSource.Length > ValidSVG.Length)
                {
                    SvgDocument doc = _svgWindow.CreateEmptySvgDocument();
                    doc.LoadXml(_xmlSource);
                    _svgWindow.Document = doc;

                    SetupStyleSheets();

                    SvgSvgElement svgEl = (SvgSvgElement)_svgWindow.Document.RootElement;
                    SvgSizeF      r     = svgEl.GetSize();

                    int winWidth  = (int)svgEl.Width.BaseVal.Value;
                    int winHeight = (int)svgEl.Height.BaseVal.Value;
                    if (!r.Width.Equals(0.0) && !r.Height.Equals(0.0) && (r.Width * 4 * r.Height) < BitmapLimit)
                    {
                        winWidth  = (int)r.Width;
                        winHeight = (int)r.Height;
                    }
                    if ((winWidth * 4 * winHeight) >= BitmapLimit)
                    {
                        winWidth  = this.Width;
                        winHeight = this.Height;
                    }
                    _svgWindow.Resize(winWidth, winHeight);

                    _svgRenderer.InvalidRect = SvgRectF.Empty;

                    this.Render();
                    _isSvgLoaded = true;
                }
                else if (_uriSource != null)
                {
                    // Load the source
                    _svgWindow.Source = _uriSource.AbsoluteUri;
                    // Initialize the style sheets
                    SetupStyleSheets();
                    // Execute all script elements
                    //UnloadEngines();
                    //InitializeEvents();
                    //ExecuteScripts();

                    SvgSvgElement svgEl = (SvgSvgElement)_svgWindow.Document.RootElement;
                    SvgSizeF      r     = svgEl.GetSize();

                    int winWidth  = (int)svgEl.Width.BaseVal.Value;
                    int winHeight = (int)svgEl.Height.BaseVal.Value;
                    if (!r.Width.Equals(0.0) && !r.Height.Equals(0.0) && (r.Width * 4 * r.Height) < BitmapLimit)
                    {
                        winWidth  = (int)r.Width;
                        winHeight = (int)r.Height;
                    }
                    if ((winWidth * 4 * winHeight) >= BitmapLimit)
                    {
                        winWidth  = this.Width;
                        winHeight = this.Height;
                    }

                    _svgWindow.Resize(winWidth, winHeight);

                    _svgRenderer.InvalidRect = SvgRectF.Empty;

                    this.Render();
                    _isSvgLoaded = true;
                }
                else if (_streamSource != null)
                {
                    SvgDocument doc = _svgWindow.CreateEmptySvgDocument();
                    doc.Load(_streamSource);
                    _svgWindow.Document = doc;

                    SetupStyleSheets();

                    SvgSvgElement svgEl = (SvgSvgElement)_svgWindow.Document.RootElement;
                    SvgSizeF      r     = svgEl.GetSize();

                    int winWidth  = (int)svgEl.Width.BaseVal.Value;
                    int winHeight = (int)svgEl.Height.BaseVal.Value;
                    if (!r.Width.Equals(0.0) && !r.Height.Equals(0.0) && (r.Width * 4 * r.Height) < BitmapLimit)
                    {
                        winWidth  = (int)r.Width;
                        winHeight = (int)r.Height;
                    }
                    if ((winWidth * 4 * winHeight) >= BitmapLimit)
                    {
                        winWidth  = this.Width;
                        winHeight = this.Height;
                    }

                    _svgWindow.Resize(winWidth, winHeight);

                    _svgRenderer.InvalidRect = SvgRectF.Empty;

                    this.Render();
                    _isSvgLoaded = true;
                }
            }
            catch (Exception ex)
            {
                Trace.TraceError(ex.ToString());

                if (this.DesignMode)
                {
                    return;
                }
                var errorArgs = new SvgErrorArgs("An error occurred while loading the document", ex);
                _svgErrors?.Invoke(this, errorArgs);
                if (!errorArgs.Handled)
                {
                    MessageBox.Show(errorArgs.Message + ": " + ex.Message,
                                    _appTitle, MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }
Пример #26
0
        public override void BeforeRender(WpfDrawingRenderer renderer)
        {
            base.BeforeRender(renderer);

            WpfDrawingContext context = renderer.Context;

            if (context.Count == 0)
            {
                _drawGroup = new DrawingGroup();
                context.Push(_drawGroup);
                context.Root = _drawGroup;
            }
            else if (context.Count == 1)
            {
                DrawingGroup currentGroup = context.Peek();

                if (currentGroup == null)
                {
                    throw new InvalidOperationException("An existing group is expected.");
                }

                if (currentGroup == context.Root)
                {
                    if (context.IsFragment)
                    {
                        // Do not add extra layer to fragments...
                        _drawGroup = currentGroup;
                    }
                    else
                    {
                        _drawGroup = new DrawingGroup();
                        SvgObject.SetName(_drawGroup, SvgObject.DrawLayer);
                        if (context.IncludeRuntime)
                        {
                            SvgLink.SetKey(_drawGroup, SvgObject.DrawLayer);
                        }

                        currentGroup.Children.Add(_drawGroup);
                        context.Push(_drawGroup);
                    }
                }
                else
                {
                    _drawGroup = new DrawingGroup();
                    currentGroup.Children.Add(_drawGroup);
                    context.Push(_drawGroup);
                }
            }
            else
            {
                _drawGroup = new DrawingGroup();
                DrawingGroup currentGroup = context.Peek();

                if (currentGroup == null)
                {
                    throw new InvalidOperationException("An existing group is expected.");
                }

                currentGroup.Children.Add(_drawGroup);
                context.Push(_drawGroup);
            }

            SvgSvgElement svgElm = (SvgSvgElement)_svgElement;

            double x      = Math.Round(svgElm.X.AnimVal.Value, 4);
            double y      = Math.Round(svgElm.Y.AnimVal.Value, 4);
            double width  = Math.Round(svgElm.Width.AnimVal.Value, 4);
            double height = Math.Round(svgElm.Height.AnimVal.Value, 4);

            if (width < 0 || height < 0)
            {
                // For invalid dimension, prevent the drawing of the children...
                _isRecursive = true;
                return;
            }

            Rect elmRect = new Rect(x, y, width, height);

            XmlNode parentNode = _svgElement.ParentNode;

            ISvgFitToViewBox fitToView = svgElm as ISvgFitToViewBox;
            ISvgAnimatedPreserveAspectRatio preserveAspectRatio = null;

            if (fitToView != null && fitToView.PreserveAspectRatio != null)
            {
                preserveAspectRatio = fitToView.PreserveAspectRatio;
                ISvgAnimatedRect animRect = fitToView.ViewBox;
                if (animRect != null)
                {
                    ISvgRect viewRect = animRect.AnimVal;
                    if (viewRect != null)
                    {
                        Rect wpfViewRect = WpfConvert.ToRect(viewRect);
                        if (!wpfViewRect.IsEmpty && wpfViewRect.Width > 0 && wpfViewRect.Height > 0)
                        {
                            elmRect = wpfViewRect;
                        }
                    }
                }
            }

            Transform transform   = null;
            var       aspectRatio = (preserveAspectRatio != null) ? preserveAspectRatio.AnimVal : null;

            if (parentNode.NodeType != XmlNodeType.Document ||
                (aspectRatio != null && aspectRatio.Align == SvgPreserveAspectRatioType.None))
            {
                FitToViewbox(context, elmRect);

                transform = this.Transform;
                if (transform != null)
                {
                    _drawGroup.Transform = transform;
                }
            }

            if (!elmRect.IsEmpty && !elmRect.Width.Equals(0) && !elmRect.Height.Equals(0))
            {
                // Elements such as "pattern" are also rendered by this renderer, so we make sure we are
                // dealing with the root SVG element...
                if (parentNode != null && parentNode.NodeType == XmlNodeType.Document)
                {
                    _drawGroup.ClipGeometry = new RectangleGeometry(elmRect);
                }
                else
                {
                    if (transform != null)
                    {
                        // We have already applied the transform, which will translate to the start point...
                        if (transform is TranslateTransform)
                        {
                            //_drawGroup.ClipGeometry = new RectangleGeometry(
                            //    new Rect(0, 0, elmRect.Width, elmRect.Height));
                        }
                        else
                        {
                            _drawGroup.ClipGeometry = new RectangleGeometry(elmRect);
                        }
                    }
                    else
                    {
                        _drawGroup.ClipGeometry = new RectangleGeometry(elmRect);
                    }
                }
            }
        }
        public override void Render(GdiGraphicsRenderer renderer)
        {
            base.Render(renderer);

            var             graphics = renderer.GdiGraphics;
            SvgImageElement iElement = (SvgImageElement)_svgElement;

            ImageAttributes imageAttributes = new ImageAttributes();

            float opacityValue = -1;

            string opacity = iElement.GetAttribute("opacity");

            if (string.IsNullOrWhiteSpace(opacity))
            {
                opacity = iElement.GetPropertyValue("opacity");
            }
            if (!string.IsNullOrWhiteSpace(opacity))
            {
                opacityValue = (float)SvgNumber.ParseNumber(opacity);
                opacityValue = Math.Min(opacityValue, 1);
                opacityValue = Math.Max(opacityValue, 0);
            }

            if (opacityValue >= 0 && opacityValue < 1)
            {
                ColorMatrix colorMatrix = new ColorMatrix();
                colorMatrix.Matrix00 = 1.00f;                 // Red
                colorMatrix.Matrix11 = 1.00f;                 // Green
                colorMatrix.Matrix22 = 1.00f;                 // Blue
                colorMatrix.Matrix33 = opacityValue;          // alpha
                colorMatrix.Matrix44 = 1.00f;                 // w

                imageAttributes.SetColorMatrix(colorMatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);
            }

            float width  = (float)iElement.Width.AnimVal.Value;
            float height = (float)iElement.Height.AnimVal.Value;

            RectangleF destRect = new RectangleF((float)iElement.X.AnimVal.Value,
                                                 (float)iElement.Y.AnimVal.Value, (float)iElement.Width.AnimVal.Value,
                                                 (float)iElement.Height.AnimVal.Value);

            RectangleF srcRect;
            RectangleF clipRect = destRect;

//            var container = graphics.BeginContainer();
            graphics.SetClip(new Region(clipRect), CombineMode.Intersect);

            Image     image  = null;
            SvgWindow svgWnd = null;

            if (iElement.IsSvgImage)
            {
                svgWnd = GetSvgWindow(graphics);
                if (width > 0 && height > 0)
                {
                    srcRect = new RectangleF(0, 0, width, height);
                }
                else
                {
                    SvgSvgElement svgEl = (SvgSvgElement)svgWnd.Document.RootElement;

                    SvgSizeF size = svgEl.GetSize();

                    srcRect = new RectangleF(new PointF(0, 0), new SizeF(size.Width, size.Height));
                }
            }
            else
            {
                image = GetBitmap(iElement);
                if (image == null)
                {
                    return;
                }
                srcRect = new RectangleF(0, 0, image.Width, image.Height);
            }

            ISvgAnimatedPreserveAspectRatio animatedAspectRatio = iElement.PreserveAspectRatio;

            if (animatedAspectRatio != null && animatedAspectRatio.AnimVal != null)
            {
                SvgPreserveAspectRatio     aspectRatio     = animatedAspectRatio.AnimVal as SvgPreserveAspectRatio;
                SvgPreserveAspectRatioType aspectRatioType =
                    (aspectRatio != null) ? aspectRatio.Align : SvgPreserveAspectRatioType.Unknown;

                if (aspectRatio != null && aspectRatioType != SvgPreserveAspectRatioType.None &&
                    aspectRatioType != SvgPreserveAspectRatioType.Unknown)
                {
                    var fScaleX = destRect.Width / srcRect.Width;
                    var fScaleY = destRect.Height / srcRect.Height;
                    var xOffset = 0.0f;
                    var yOffset = 0.0f;

                    SvgMeetOrSlice meetOrSlice = aspectRatio.MeetOrSlice;
                    if (meetOrSlice == SvgMeetOrSlice.Slice)
                    {
                        fScaleX = Math.Max(fScaleX, fScaleY);
                        fScaleY = Math.Max(fScaleX, fScaleY);
                    }
                    else
                    {
                        fScaleX = Math.Min(fScaleX, fScaleY);
                        fScaleY = Math.Min(fScaleX, fScaleY);
                    }

                    switch (aspectRatioType)
                    {
                    case SvgPreserveAspectRatioType.XMinYMin:
                        break;

                    case SvgPreserveAspectRatioType.XMidYMin:
                        xOffset = (destRect.Width - srcRect.Width * fScaleX) / 2;
                        break;

                    case SvgPreserveAspectRatioType.XMaxYMin:
                        xOffset = (destRect.Width - srcRect.Width * fScaleX);
                        break;

                    case SvgPreserveAspectRatioType.XMinYMid:
                        yOffset = (destRect.Height - srcRect.Height * fScaleY) / 2;
                        break;

                    case SvgPreserveAspectRatioType.XMidYMid:
                        xOffset = (destRect.Width - srcRect.Width * fScaleX) / 2;
                        yOffset = (destRect.Height - srcRect.Height * fScaleY) / 2;
                        break;

                    case SvgPreserveAspectRatioType.XMaxYMid:
                        xOffset = (destRect.Width - srcRect.Width * fScaleX);
                        yOffset = (destRect.Height - srcRect.Height * fScaleY) / 2;
                        break;

                    case SvgPreserveAspectRatioType.XMinYMax:
                        yOffset = (destRect.Height - srcRect.Height * fScaleY);
                        break;

                    case SvgPreserveAspectRatioType.XMidYMax:
                        xOffset = (destRect.Width - srcRect.Width * fScaleX) / 2;
                        yOffset = (destRect.Height - srcRect.Height * fScaleY);
                        break;

                    case SvgPreserveAspectRatioType.XMaxYMax:
                        xOffset = (destRect.Width - srcRect.Width * fScaleX);
                        yOffset = (destRect.Height - srcRect.Height * fScaleY);
                        break;
                    }

                    destRect = new RectangleF(destRect.X + xOffset, destRect.Y + yOffset,
                                              srcRect.Width * fScaleX, srcRect.Height * fScaleY);
                }
                if (image != null)
                {
                    SvgColorProfileElement colorProfile = (SvgColorProfileElement)iElement.ColorProfile;
                    if (colorProfile != null)
                    {
                        SvgUriReference svgUri     = colorProfile.UriReference;
                        Uri             profileUri = new Uri(svgUri.AbsoluteUri);

                        imageAttributes.SetOutputChannelColorProfile(profileUri.LocalPath, ColorAdjustType.Default);
                    }

                    graphics.DrawImage(this, image, destRect, srcRect, GraphicsUnit.Pixel, imageAttributes);

                    image.Dispose();
                    image = null;
                }
                else if (iElement.IsSvgImage && svgWnd != null)
                {
                    svgWnd.Resize((int)srcRect.Width, (int)srcRect.Height);

                    var currOffset = new PointF(graphics.Transform.OffsetX, graphics.Transform.OffsetY);
                    if (!currOffset.IsEmpty)
                    {
                        graphics.TranslateTransform(-currOffset.X, -currOffset.Y);
                    }
                    graphics.ScaleTransform(destRect.Width / srcRect.Width, destRect.Height / srcRect.Height);
                    if (!currOffset.IsEmpty)
                    {
                        graphics.TranslateTransform(currOffset.X + destRect.X, currOffset.Y + destRect.Y);
                    }

                    _embeddedRenderer.Render(svgWnd.Document);
                }

                graphics.ResetClip();
//                graphics.EndContainer(container);
            }

            if (_embeddedRenderer != null)
            {
                _embeddedRenderer.GdiGraphics = null;
                _embeddedRenderer.Dispose();
                _embeddedRenderer = null;
            }

            if (imageAttributes != null)
            {
                imageAttributes.Dispose();
                imageAttributes = null;
            }
        }
Пример #28
0
        public override void BeforeRender(WpfDrawingRenderer renderer)
        {
            base.BeforeRender(renderer);

            WpfDrawingContext context = renderer.Context;

            _drawGroup = new DrawingGroup();

            if (context.Count == 0)
            {
                context.Push(_drawGroup);
                context.Root = _drawGroup;
            }
            else if (context.Count == 1)
            {
                DrawingGroup currentGroup = context.Peek();

                if (currentGroup == null)
                {
                    throw new InvalidOperationException("An existing group is expected.");
                }
                if (currentGroup == context.Root && !context.IsFragment)
                {
                    _drawGroup.SetValue(FrameworkElement.NameProperty, SvgObject.DrawLayer);
                    if (context.IncludeRuntime)
                    {
                        SvgLink.SetKey(_drawGroup, SvgObject.DrawLayer);
                    }
                }

                currentGroup.Children.Add(_drawGroup);
                context.Push(_drawGroup);
            }
            else
            {
                DrawingGroup currentGroup = context.Peek();

                if (currentGroup == null)
                {
                    throw new InvalidOperationException("An existing group is expected.");
                }

                currentGroup.Children.Add(_drawGroup);
                context.Push(_drawGroup);
            }

            SvgSvgElement svgElm = (SvgSvgElement)_svgElement;

            double x      = Math.Round(svgElm.X.AnimVal.Value, 4);
            double y      = Math.Round(svgElm.Y.AnimVal.Value, 4);
            double width  = Math.Round(svgElm.Width.AnimVal.Value, 4);
            double height = Math.Round(svgElm.Height.AnimVal.Value, 4);

            Rect elmRect = new Rect(x, y, width, height);

            //if (element.ParentNode is SvgElement)
            //{
            //    // TODO: should it be moved with x and y?
            //}

            XmlNode parentNode = _svgElement.ParentNode;

            //if (parentNode.NodeType == XmlNodeType.Document)
            {
                ISvgFitToViewBox fitToView = svgElm as ISvgFitToViewBox;
                if (fitToView != null)
                {
                    ISvgAnimatedRect animRect = fitToView.ViewBox;
                    if (animRect != null)
                    {
                        ISvgRect viewRect = animRect.AnimVal;
                        if (viewRect != null)
                        {
                            Rect wpfViewRect = WpfConvert.ToRect(viewRect);
                            if (!wpfViewRect.IsEmpty && wpfViewRect.Width > 0 && wpfViewRect.Height > 0)
                            {
                                elmRect = wpfViewRect;
                            }
                        }
                    }
                }
            }

            Transform transform = null;

            if (parentNode.NodeType != XmlNodeType.Document)
            {
                FitToViewbox(context, elmRect);

                transform = this.Transform;
                if (transform != null)
                {
                    _drawGroup.Transform = transform;
                }
            }

            //if (height > 0 && width > 0)
            //{
            //    ClipGeometry = new RectangleGeometry(elmRect);
            //}
            //Geometry clipGeom = this.ClipGeometry;
            //if (clipGeom != null)
            //{
            //    _drawGroup.ClipGeometry = clipGeom;
            //}

            if (((float)elmRect.Width != 0 && (float)elmRect.Height != 0))
            {
                // Elements such as "pattern" are also rendered by this renderer, so we make sure we are
                // dealing with the root SVG element...
                if (parentNode != null && parentNode.NodeType == XmlNodeType.Document)
                {
                    _drawGroup.ClipGeometry = new RectangleGeometry(elmRect);
                }
                else
                {
                    if (transform != null)
                    {
                        // We have already applied the transform, which will translate to the start point...
                        if (transform is TranslateTransform)
                        {
                            _drawGroup.ClipGeometry = new RectangleGeometry(
                                new Rect(0, 0, elmRect.Width, elmRect.Height));
                        }
                        else
                        {
                            _drawGroup.ClipGeometry = new RectangleGeometry(elmRect);
                        }
                    }
                    else
                    {
                        _drawGroup.ClipGeometry = new RectangleGeometry(elmRect);
                    }
                }

                //DrawingGroup animationGroup = context.Links;
                //if (animationGroup != null)
                //{
                //    animationGroup.ClipGeometry = clipGeom;
                //}
            }
        }
Пример #29
0
 public virtual void VisitSvgElement(SvgSvgElement element)
 => DefaultVisit(element);
        public static Image GetBitmap(SvgImageElement element)
        {
            var comparer = StringComparison.OrdinalIgnoreCase;

            if (!element.IsSvgImage)
            {
                if (!element.Href.AnimVal.StartsWith("data:", comparer))
                {
                    SvgUriReference svgUri   = element.UriReference;
                    Uri             imageUri = new Uri(svgUri.AbsoluteUri);
                    if (imageUri.IsFile && File.Exists(imageUri.LocalPath))
                    {
                        return(Image.FromFile(imageUri.LocalPath, element.ColorProfile != null));
                    }

                    WebResponse resource = svgUri.ReferencedResource;
                    if (resource == null)
                    {
                        return(null);
                    }

                    Stream stream = resource.GetResponseStream();
                    if (stream == null)
                    {
                        return(null);
                    }

                    return(Image.FromStream(stream, element.ColorProfile != null));
                }

                string sURI = element.Href.AnimVal.Replace(" ", "").Trim();
                sURI = sURI.Replace(@"\n", "");
                int nColon     = sURI.IndexOf(":", comparer);
                int nSemiColon = sURI.IndexOf(";", comparer);
                int nComma     = sURI.IndexOf(",", comparer);

                string sMimeType = sURI.Substring(nColon + 1, nSemiColon - nColon - 1);
                string sContent  = sURI.Substring(nComma + 1);

                sContent = sContent.Replace('-', '+').Replace('_', '/');
                sContent = sContent.PadRight(4 * ((sContent.Length + 3) / 4), '=');
                byte[] bResult = Convert.FromBase64CharArray(sContent.ToCharArray(),
                                                             0, sContent.Length);

                if (sMimeType.Equals("image/svg+xml", StringComparison.OrdinalIgnoreCase))
                {
                    GdiGraphicsRenderer renderer = new GdiGraphicsRenderer(true, false);

                    var currentWindow = element.OwnerDocument.Window as SvgWindow;
                    var svgWindow     = currentWindow.CreateOwnedWindow();
                    renderer.Window = svgWindow;

                    SvgDocument doc      = svgWindow.CreateEmptySvgDocument();
                    bool        isGZiped = sContent.StartsWith(GdiObject.GZipSignature, StringComparison.Ordinal);
                    if (isGZiped)
                    {
                        byte[] imageBytes = Convert.FromBase64CharArray(sContent.ToCharArray(),
                                                                        0, sContent.Length);
                        using (var stream = new MemoryStream(imageBytes))
                        {
                            using (GZipStream zipStream = new GZipStream(stream, CompressionMode.Decompress))
                            {
                                doc.Load(zipStream);
                            }
                        }
                    }
                    else
                    {
                        var svgData     = Convert.FromBase64String(Convert.ToBase64String(bResult));
                        var svgFragment = Encoding.ASCII.GetString(svgData);

                        doc.LoadXml(svgFragment);
                    }
                    svgWindow.Document = doc;

                    SvgSvgElement elm = (SvgSvgElement)doc.RootElement;

                    int winWidth  = (int)elm.Width.BaseVal.Value;
                    int winHeight = (int)elm.Height.BaseVal.Value;
                    if (winWidth == 0 || winHeight == 0)
                    {
                        var size = elm.GetSize();
                        winWidth  = (int)size.Width;
                        winHeight = (int)size.Height;
                    }

                    svgWindow.Resize(winWidth, winHeight);

                    renderer.Render(elm as SvgElement);
                    Image img = renderer.RasterImage;

                    return(img);
                }

                MemoryStream ms = new MemoryStream(bResult);
                return(Image.FromStream(ms, element.ColorProfile != null));
            }
            return(null);
        }