private ImageSource GetImage(SvgImageElement element, WpfDrawingContext context)
        {
            if (context != null && context.Settings.IncludeRuntime == false)
            {
                return(null);
            }

            var comparer = StringComparison.OrdinalIgnoreCase;

            string sURI       = element.Href.AnimVal.Replace(" ", "");
            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 = SvgObject.RemoveWhitespace(sURI.Substring(nComma + 1));

            byte[] imageBytes = Convert.FromBase64CharArray(sContent.ToCharArray(),
                                                            0, sContent.Length);
            bool isGZiped = sContent.StartsWith(SvgObject.GZipSignature, StringComparison.Ordinal);

            if (string.Equals(sMimeType, "image/svg+xml", comparer))
            {
                if (isGZiped)
                {
                    using (var stream = new MemoryStream(imageBytes))
                    {
                        using (GZipStream zipStream = new GZipStream(stream, CompressionMode.Decompress))
                        {
                            using (var reader = new FileSvgReader(context.Settings))
                                return(new DrawingImage(reader.Read(zipStream)));
                        }
                    }
                }
                else
                {
                    using (var stream = new MemoryStream(imageBytes))
                    {
                        using (var reader = new FileSvgReader(context.Settings))
                            return(new DrawingImage(reader.Read(stream)));
                    }
                }
            }

            return(new EmbeddedBitmapSource(new MemoryStream(imageBytes)));
        }
Beispiel #2
0
 public void RegisterDrawing(string elementId, string uniqueId, Drawing drawing)
 {
     if (_drawingDocument != null)
     {
         if (_settings != null && _settings.IncludeRuntime)
         {
             if (!string.IsNullOrWhiteSpace(elementId))
             {
                 SvgObject.SetId(drawing, elementId);
             }
             if (!string.IsNullOrWhiteSpace(uniqueId))
             {
                 SvgObject.SetUniqueId(drawing, uniqueId);
             }
         }
         _drawingDocument.Add(elementId, uniqueId, drawing);
     }
 }
        public override void BeforeRender(WpfDrawingRenderer renderer)
        {
            base.BeforeRender(renderer);

            WpfDrawingContext context = renderer.Context;

            _drawGroup = new DrawingGroup();

            string elementId = this.GetElementName();

            if (!string.IsNullOrWhiteSpace(elementId) && !context.IsRegisteredId(elementId))
            {
                SvgObject.SetName(_drawGroup, elementId);

                context.RegisterId(elementId);

                if (context.IncludeRuntime)
                {
                    SvgObject.SetId(_drawGroup, elementId);
                }
            }

            string elementClass = this.GetElementClass();

            if (!string.IsNullOrWhiteSpace(elementClass) && context.IncludeRuntime)
            {
                SvgObject.SetClass(_drawGroup, elementClass);
            }

            DrawingGroup currentGroup = context.Peek();

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

            currentGroup.Children.Add(_drawGroup);
            context.Push(_drawGroup);
        }
        private DrawingGroup GetDrawingLayer(DrawingGroup drawingGroup, ref bool isFound)
        {
            isFound = false;

            DrawingGroup groupDrawing = null;

            // Enumerate the drawings in the DrawingCollection.
            foreach (Drawing drawing in drawingGroup.Children)
            {
                var itemKey = SvgLink.GetKey(drawing);
                if (!string.IsNullOrWhiteSpace(itemKey) &&
                    itemKey.Equals(SvgObject.DrawLayer, StringComparison.OrdinalIgnoreCase))
                {
                    isFound = true;
                    return((DrawingGroup)drawing);
                }

                // If the drawing is a DrawingGroup, call the function recursively.
                if (TryCast.Cast(drawing, out groupDrawing))
                {
                    SvgObjectType objectType = SvgObject.GetType(groupDrawing);
                    if (objectType != SvgObjectType.Text)
                    {
                        var nextGroup = GetDrawingLayer(groupDrawing, ref isFound);
                        if (nextGroup != groupDrawing)
                        {
                            itemKey = SvgLink.GetKey(nextGroup);
                            if (!string.IsNullOrWhiteSpace(itemKey) &&
                                itemKey.Equals(SvgObject.DrawLayer, StringComparison.OrdinalIgnoreCase))
                            {
                                return(nextGroup);
                            }
                        }
                    }
                }
            }
            return(drawingGroup);
        }
Beispiel #5
0
        // Enumerate the drawings in the DrawingGroup.
        private void EnumDrawingGroup(DrawingGroup drawingGroup)
        {
            DrawingCollection dc = drawingGroup.Children;

            DrawingGroup groupDrawing = null;

            // Enumerate the drawings in the DrawingCollection.
            foreach (Drawing drawing in dc)
            {
                string objectId = SvgObject.GetId(drawing);
                if (!string.IsNullOrWhiteSpace(objectId))
                {
                    _idMap.Add(objectId, drawing);
                }
                string objectName = (string)drawing.GetValue(FrameworkElement.NameProperty);
                if (!string.IsNullOrWhiteSpace(objectName))
                {
                    _idMap[objectName] = drawing;
                }
                string uniqueId = SvgObject.GetUniqueId(drawing);
                if (!string.IsNullOrWhiteSpace(uniqueId))
                {
                    _guidMap.Add(uniqueId, drawing);
                }

                // If the drawing is a DrawingGroup, call the function recursively.
                if (TryCast.Cast(drawing, out groupDrawing))
                {
                    SvgObjectType objectType = SvgObject.GetType(groupDrawing);
                    if (objectType != SvgObjectType.Text)
                    {
                        EnumDrawingGroup(groupDrawing);
                    }
                }
            }
        }
        public WpfHitTestResult HitTest(Rect rect, IntersectionDetail detail)
        {
            var svgDrawing = this.PerformHitTest(rect, detail);

            if (svgDrawing == null)
            {
                return(WpfHitTestResult.Empty);
            }
            string uniqueId = SvgObject.GetUniqueId(svgDrawing);

            if (string.IsNullOrWhiteSpace(uniqueId))
            {
                return(new WpfHitTestResult(rect, null, svgDrawing));
//                return WpfHitTestResult.Empty;
            }
            var svgElement = this.GetSvgByUniqueId(uniqueId);

            if (svgElement == null)
            {
                return(WpfHitTestResult.Empty);
            }

            return(new WpfHitTestResult(rect, svgElement, svgDrawing));
        }
Beispiel #7
0
        public override void BeforeRender(WpfDrawingRenderer renderer)
        {
            base.BeforeRender(renderer);

            _idElement = string.Empty;

            WpfDrawingContext context = renderer.Context;

            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);
            }

            SvgPatternElement svgElm = (SvgPatternElement)_svgElement;

            _idElement = svgElm.Id;
            if (!string.IsNullOrWhiteSpace(_idElement))
            {
                context.AddUrl(_idElement);
            }

            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 (aspectRatio != null /* && aspectRatio.Align == SvgPreserveAspectRatioType.None*/)
            {
                FitToViewbox(context, elmRect);

                transform = this.Transform;
                if (transform != null)
                {
                    _drawGroup.Transform = transform;
                }
            }
        }
Beispiel #8
0
        public override void BeforeRender(WpfDrawingRenderer renderer)
        {
            base.BeforeRender(renderer);

            if (renderer == null)
            {
                return;
            }

            _isLineSegment   = false;
            _setBrushOpacity = true;

            WpfDrawingContext context = renderer.Context;

            //SetQuality(context);
            //SetTransform(context);
            //SetMask(context);

//            _drawGroup = new DrawingGroup();

            SvgStyleableElement styleElm = (SvgStyleableElement)_svgElement;

            float opacityValue   = -1;
            bool  isStyleOpacity = false;

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

            if (string.IsNullOrWhiteSpace(opacity))
            {
                opacity = styleElm.GetPropertyValue("opacity");
                if (!string.IsNullOrWhiteSpace(opacity))
                {
                    isStyleOpacity = true;
                }
            }
            if (!string.IsNullOrWhiteSpace(opacity))
            {
                opacityValue = (float)SvgNumber.ParseNumber(opacity);
                opacityValue = Math.Min(opacityValue, 1);
                opacityValue = Math.Max(opacityValue, 0);
                if (isStyleOpacity && (opacityValue >= 0 && opacityValue < 1))
                {
                    _setBrushOpacity = false;
                    if (styleElm.HasAttribute("fill-opacity") || (styleElm.HasAttribute("style") &&
                                                                  styleElm.GetAttribute("style").Contains("fill-opacity")))
                    {
                        _setBrushOpacity = true;
                    }
                }
            }
            //string eVisibility = _svgElement.GetAttribute("visibility");
            //string eDisplay    = _svgElement.GetAttribute("display");
            //if (string.Equals(eVisibility, "hidden") || string.Equals(eDisplay, "none"))
            //{
            //    opacityValue = 0;
            //}
            //else
            //{
            //    string sVisibility = styleElm.GetPropertyValue("visibility");
            //    string sDisplay = styleElm.GetPropertyValue("display");
            //    if (string.Equals(sVisibility, "hidden") || string.Equals(sDisplay, "none"))
            //    {
            //        opacityValue = 0;
            //    }
            //}
            string sVisibility = styleElm.GetPropertyValue("visibility");

            if (string.IsNullOrWhiteSpace(sVisibility))
            {
                sVisibility = _svgElement.GetAttribute("visibility");
            }
            string sDisplay = styleElm.GetPropertyValue("display");

            if (string.IsNullOrWhiteSpace(sDisplay))
            {
                sDisplay = _svgElement.GetAttribute("display");
            }
            if (string.Equals(sVisibility, "hidden") || string.Equals(sDisplay, "none"))
            {
                opacityValue = 0;
            }

            Transform pathTransform = this.Transform;

            if (pathTransform != null && !pathTransform.Value.IsIdentity)
            {
                if (_drawGroup == null)
                {
                    _drawGroup = new DrawingGroup();
                }
                _drawGroup.Transform = pathTransform;
            }
            else
            {
                pathTransform = null; // render any identity transform useless...
            }

            Geometry pathClip = this.ClipGeometry;

            if (pathClip != null && !pathClip.IsEmpty())
            {
                if (_drawGroup == null)
                {
                    _drawGroup = new DrawingGroup();
                }
                _drawGroup.ClipGeometry = pathClip;
            }
            else
            {
                pathClip = null; // render any empty geometry useless...
            }
            Brush pathMask = this.Masking;

            if (pathMask != null)
            {
                if (_drawGroup == null)
                {
                    _drawGroup = new DrawingGroup();
                }
                _drawGroup.OpacityMask = pathMask;
            }

            if (pathTransform != null || pathClip != null || pathMask != null || (opacityValue >= 0 && opacityValue < 1))
            {
                if (_drawGroup == null)
                {
                    _drawGroup = new DrawingGroup();
                }
                if ((opacityValue >= 0 && opacityValue < 1))
                {
                    _drawGroup.Opacity = opacityValue;
                }

                DrawingGroup curGroup = _context.Peek();
                Debug.Assert(curGroup != null);
                if (curGroup != null)
                {
                    curGroup.Children.Add(_drawGroup);
                    context.Push(_drawGroup);
                }
            }
            else
            {
                _drawGroup = null;
            }

            if (_drawGroup != null)
            {
                string elementClass = this.GetElementClass();
                if (!string.IsNullOrWhiteSpace(elementClass) && context.IncludeRuntime)
                {
                    SvgObject.SetClass(_drawGroup, elementClass);
                }

                string elementId = this.GetElementName();
                if (!string.IsNullOrWhiteSpace(elementId) && !context.IsRegisteredId(elementId))
                {
                    SvgObject.SetName(_drawGroup, elementId);

                    context.RegisterId(elementId);

                    if (context.IncludeRuntime)
                    {
                        SvgObject.SetId(_drawGroup, elementId);
                    }
                }
            }
        }
Beispiel #9
0
        private void RenderPath(WpfDrawingRenderer renderer)
        {
            WpfDrawingContext context = renderer.Context;

            SvgRenderingHint hint = _svgElement.RenderingHint;

            if (hint != SvgRenderingHint.Shape || hint == SvgRenderingHint.Clipping)
            {
                return;
            }
            var parentNode = _svgElement.ParentNode;

            // We do not directly render the contents of the clip-path, unless specifically requested...
            if (string.Equals(parentNode.LocalName, "clipPath") &&
                !context.RenderingClipRegion)
            {
                return;
            }

            SvgStyleableElement styleElm = (SvgStyleableElement)_svgElement;

            //string sVisibility = styleElm.GetPropertyValue("visibility");
            //string sDisplay    = styleElm.GetPropertyValue("display");
            //if (string.Equals(sVisibility, "hidden") || string.Equals(sDisplay, "none"))
            //{
            //    return;
            //}

            DrawingGroup drawGroup = context.Peek();

            Debug.Assert(drawGroup != null);

            Geometry geometry = CreateGeometry(_svgElement, context.OptimizePath);

            string elementId    = this.GetElementName();
            string elementClass = this.GetElementClass();

            GeometryDrawing drawing = null;

            if (geometry == null || geometry.IsEmpty())
            {
                return;
            }

            var bounds = geometry.Bounds;

            if (string.Equals(_svgElement.LocalName, "line", StringComparison.Ordinal))
            {
                _isLineSegment = true;
            }
            else if (string.Equals(_svgElement.LocalName, "rect", StringComparison.Ordinal))
            {
                _isLineSegment = bounds.Width.Equals(0) || bounds.Height.Equals(0);
            }
            else if (string.Equals(_svgElement.LocalName, "path", StringComparison.Ordinal))
            {
                _isLineSegment = bounds.Width.Equals(0) || bounds.Height.Equals(0);
            }

            context.UpdateBounds(geometry.Bounds);

//                SetClip(context);

            WpfSvgPaint fillPaint = new WpfSvgPaint(context, styleElm, "fill");

            string fileValue = styleElm.GetAttribute("fill");

            Brush brush            = fillPaint.GetBrush(geometry, _setBrushOpacity);
            bool  isFillTransmable = fillPaint.IsFillTransformable;

            WpfSvgPaint strokePaint = new WpfSvgPaint(context, styleElm, "stroke");
            Pen         pen         = strokePaint.GetPen(geometry, _setBrushOpacity);

            // By the SVG Specifications:
            // Keyword 'objectBoundingBox' should not be used when the geometry of the applicable
            // element has no width or no height, such as the case of a horizontal or vertical line,
            // even when the line has actual thickness when viewed due to having a non-zero stroke
            // width since stroke width is ignored for bounding box calculations. When the geometry
            // of the applicable element has no width or height and 'objectBoundingBox' is specified,
            // then the given effect (e.g., a gradient) will be ignored.
            if (pen != null && _isLineSegment && strokePaint.FillType == WpfFillType.Gradient)
            {
                WpfGradientFill gradientFill = (WpfGradientFill)strokePaint.PaintServer;
                if (gradientFill.IsUserSpace == false)
                {
                    bool invalidGrad = false;
                    if (string.Equals(_svgElement.LocalName, "line", StringComparison.Ordinal))
                    {
                        LineGeometry lineGeometry = geometry as LineGeometry;
                        if (lineGeometry != null)
                        {
                            invalidGrad = SvgObject.IsEqual(lineGeometry.EndPoint.X, lineGeometry.StartPoint.X) ||
                                          SvgObject.IsEqual(lineGeometry.EndPoint.Y, lineGeometry.StartPoint.Y);
                        }
                    }
                    else
                    {
                        invalidGrad = true;
                    }
                    if (invalidGrad)
                    {
                        // Brush is not likely inherited, we need to support fallback too
                        WpfSvgPaint fallbackPaint = strokePaint.WpfFallback;
                        if (fallbackPaint != null)
                        {
                            pen.Brush = fallbackPaint.GetBrush(geometry, _setBrushOpacity);
                        }
                        else
                        {
                            var scopePaint = strokePaint.GetScopeStroke();
                            if (scopePaint != null)
                            {
                                if (scopePaint != strokePaint)
                                {
                                    pen.Brush = scopePaint.GetBrush(geometry, _setBrushOpacity);
                                }
                                else
                                {
                                    pen.Brush = null;
                                }
                            }
                            else
                            {
                                pen.Brush = null;
                            }
                        }
                    }
                }
            }

            if (_paintContext != null)
            {
                _paintContext.Fill   = fillPaint;
                _paintContext.Stroke = strokePaint;
                _paintContext.Tag    = geometry;
            }

            if (brush != null || pen != null)
            {
                Transform transform = this.Transform;
                if (transform != null && !transform.Value.IsIdentity)
                {
                    geometry.Transform = transform;
                    if (brush != null && isFillTransmable)
                    {
                        Transform brushTransform = brush.Transform;
                        if (brushTransform == null || brushTransform == Transform.Identity)
                        {
                            brush.Transform = transform;
                        }
                        else
                        {
                            TransformGroup groupTransform = new TransformGroup();
                            groupTransform.Children.Add(brushTransform);
                            groupTransform.Children.Add(transform);
                            brush.Transform = groupTransform;
                        }
                    }
                    if (pen != null && pen.Brush != null)
                    {
                        Transform brushTransform = pen.Brush.Transform;
                        if (brushTransform == null || brushTransform == Transform.Identity)
                        {
                            pen.Brush.Transform = transform;
                        }
                        else
                        {
                            TransformGroup groupTransform = new TransformGroup();
                            groupTransform.Children.Add(brushTransform);
                            groupTransform.Children.Add(transform);
                            pen.Brush.Transform = groupTransform;
                        }
                    }
                }
                else
                {
                    transform = null; // render any identity transform useless...
                }

                drawing = new GeometryDrawing(brush, pen, geometry);

                if (!string.IsNullOrWhiteSpace(elementId) && !context.IsRegisteredId(elementId))
                {
                    SvgObject.SetName(drawing, elementId);

                    context.RegisterId(elementId);

                    if (context.IncludeRuntime)
                    {
                        SvgObject.SetId(drawing, elementId);
                    }
                }

                if (!string.IsNullOrWhiteSpace(elementClass) && context.IncludeRuntime)
                {
                    SvgObject.SetClass(drawing, elementClass);
                }

                Brush    maskBrush = this.Masking;
                Geometry clipGeom  = this.ClipGeometry;
                if (clipGeom != null || maskBrush != null)
                {
                    //Geometry clipped = Geometry.Combine(geometry, clipGeom,
                    //    GeometryCombineMode.Exclude, null);

                    //if (clipped != null && !clipped.IsEmpty())
                    //{
                    //    geometry = clipped;
                    //}
                    DrawingGroup clipMaskGroup = new DrawingGroup();

                    Rect geometryBounds = geometry.Bounds;

                    if (clipGeom != null)
                    {
                        clipMaskGroup.ClipGeometry = clipGeom;

                        SvgUnitType clipUnits = this.ClipUnits;
                        if (clipUnits == SvgUnitType.ObjectBoundingBox)
                        {
                            Rect drawingBounds = geometryBounds;

                            if (transform != null)
                            {
                                drawingBounds = transform.TransformBounds(drawingBounds);
                            }

                            TransformGroup transformGroup = new TransformGroup();

                            // Scale the clip region (at (0, 0)) and translate to the top-left corner of the target.
                            transformGroup.Children.Add(new ScaleTransform(drawingBounds.Width, drawingBounds.Height));
                            transformGroup.Children.Add(new TranslateTransform(drawingBounds.X, drawingBounds.Y));

                            clipGeom.Transform = transformGroup;
                        }
                        else
                        {
                            if (transform != null)
                            {
                                clipGeom.Transform = transform;
                            }
                        }
                    }
                    if (maskBrush != null)
                    {
                        DrawingBrush drawingBrush = (DrawingBrush)maskBrush;

                        SvgUnitType maskUnits        = this.MaskUnits;
                        SvgUnitType maskContentUnits = this.MaskContentUnits;
                        if (maskUnits == SvgUnitType.ObjectBoundingBox)
                        {
                            Rect drawingBounds = geometryBounds;

                            if (transform != null)
                            {
                                drawingBounds = transform.TransformBounds(drawingBounds);
                            }
                            DrawingGroup maskGroup = drawingBrush.Drawing as DrawingGroup;
                            if (maskGroup != null)
                            {
                                DrawingCollection maskDrawings = maskGroup.Children;
                                for (int i = 0; i < maskDrawings.Count; i++)
                                {
                                    Drawing         maskDrawing  = maskDrawings[i];
                                    GeometryDrawing maskGeomDraw = maskDrawing as GeometryDrawing;
                                    if (maskGeomDraw != null)
                                    {
                                        if (maskGeomDraw.Brush != null)
                                        {
                                            ConvertColors(maskGeomDraw.Brush);
                                        }
                                        if (maskGeomDraw.Pen != null)
                                        {
                                            ConvertColors(maskGeomDraw.Pen.Brush);
                                        }
                                    }
                                }
                            }

                            if (maskContentUnits == SvgUnitType.ObjectBoundingBox)
                            {
                                TransformGroup transformGroup = new TransformGroup();

                                // Scale the clip region (at (0, 0)) and translate to the top-left corner of the target.
                                var scaleTransform = new ScaleTransform(drawingBounds.Width, drawingBounds.Height);
                                transformGroup.Children.Add(scaleTransform);
                                var translateTransform = new TranslateTransform(drawingBounds.X, drawingBounds.Y);
                                transformGroup.Children.Add(translateTransform);

                                Matrix scaleMatrix     = new Matrix();
                                Matrix translateMatrix = new Matrix();

                                scaleMatrix.Scale(drawingBounds.Width, drawingBounds.Height);
                                translateMatrix.Translate(drawingBounds.X, drawingBounds.Y);

                                Matrix matrix = Matrix.Multiply(scaleMatrix, translateMatrix);
                                //maskBrush.Transform = transformGroup;
                                maskBrush.Transform = new MatrixTransform(matrix);
                            }
                            else
                            {
                                drawingBrush.Viewbox      = drawingBounds;
                                drawingBrush.ViewboxUnits = BrushMappingMode.Absolute;

                                drawingBrush.Stretch = Stretch.Uniform;

                                drawingBrush.Viewport      = drawingBounds;
                                drawingBrush.ViewportUnits = BrushMappingMode.Absolute;
                            }
                        }
                        else
                        {
                            if (transform != null)
                            {
                                maskBrush.Transform = transform;
                            }
                        }

                        clipMaskGroup.OpacityMask = maskBrush;
                    }

                    clipMaskGroup.Children.Add(drawing);
                    drawGroup.Children.Add(clipMaskGroup);
                }
                else
                {
                    drawGroup.Children.Add(drawing);
                }
            }

            // If this is not the child of a "marker", then try rendering a marker...
            if (!string.Equals(parentNode.LocalName, "marker"))
            {
                RenderMarkers(renderer, styleElm, context);
            }

            // Register this drawing with the Drawing-Document...
            if (drawing != null)
            {
                this.Rendered(drawing);
            }
        }
Beispiel #10
0
        public override void BeforeRender(WpfDrawingRenderer renderer)
        {
            base.BeforeRender(renderer);

            if (renderer == null)
            {
                return;
            }

            WpfDrawingContext context = renderer.Context;

            //SetQuality(context);
            //SetTransform(context);
            //SetMask(context);

            _drawGroup = new DrawingGroup();

            SvgStyleableElement styleElm = (SvgStyleableElement)_svgElement;

            Transform pathTransform = this.Transform;

            if (pathTransform != null && !pathTransform.Value.IsIdentity)
            {
                _drawGroup.Transform = pathTransform;
            }
            else
            {
                pathTransform = null; // render any identity transform useless...
            }
            Geometry pathClip = this.ClipGeometry;

            if (pathClip != null && !pathClip.IsEmpty())
            {
                _drawGroup.ClipGeometry = pathClip;
            }
            else
            {
                pathClip = null; // render any empty geometry useless...
            }
            Brush pathMask = this.Masking;

            if (pathMask != null)
            {
                _drawGroup.OpacityMask = pathMask;
            }

            if (pathTransform != null || pathClip != null || pathMask != null)
            {
                DrawingGroup curGroup = _context.Peek();
                Debug.Assert(curGroup != null);
                if (curGroup != null)
                {
                    curGroup.Children.Add(_drawGroup);
                    context.Push(_drawGroup);
                }
            }
            else
            {
                _drawGroup = null;
            }

            if (_drawGroup != null)
            {
                string sVisibility = styleElm.GetPropertyValue("visibility");
                string sDisplay    = styleElm.GetPropertyValue("display");
                if (string.Equals(sVisibility, "hidden") || string.Equals(sDisplay, "none"))
                {
                    _drawGroup.Opacity = 0;
                }

                string elementClass = this.GetElementClass();
                if (!string.IsNullOrWhiteSpace(elementClass) && context.IncludeRuntime)
                {
                    SvgObject.SetClass(_drawGroup, elementClass);
                }

                string elementId = this.GetElementName();
                if (!string.IsNullOrWhiteSpace(elementId) && !context.IsRegisteredId(elementId))
                {
                    SvgObject.SetName(_drawGroup, elementId);

                    context.RegisterId(elementId);

                    if (context.IncludeRuntime)
                    {
                        SvgObject.SetId(_drawGroup, elementId);
                    }
                }
            }
        }
Beispiel #11
0
        private void RenderPath(WpfDrawingRenderer renderer)
        {
            WpfDrawingContext context = renderer.Context;

            SvgRenderingHint hint = _svgElement.RenderingHint;

            if (hint != SvgRenderingHint.Shape || hint == SvgRenderingHint.Clipping)
            {
                return;
            }
            var parentNode = _svgElement.ParentNode;

            // We do not directly render the contents of the clip-path, unless specifically requested...
            if (string.Equals(parentNode.LocalName, "clipPath") &&
                !context.RenderingClipRegion)
            {
                return;
            }

            SvgStyleableElement styleElm = (SvgStyleableElement)_svgElement;

            string sVisibility = styleElm.GetPropertyValue("visibility");
            string sDisplay    = styleElm.GetPropertyValue("display");

            if (string.Equals(sVisibility, "hidden") || string.Equals(sDisplay, "none"))
            {
                return;
            }

            DrawingGroup drawGroup = context.Peek();

            Debug.Assert(drawGroup != null);

            Geometry geometry = CreateGeometry(_svgElement, context.OptimizePath);

            string elementId    = this.GetElementName();
            string elementClass = this.GetElementClass();

            if (geometry != null && !geometry.IsEmpty())
            {
                context.UpdateBounds(geometry.Bounds);

//                SetClip(context);

                WpfSvgPaint fillPaint = new WpfSvgPaint(context, styleElm, "fill");

                string fileValue = styleElm.GetAttribute("fill");

                Brush brush            = fillPaint.GetBrush(geometry);
                bool  isFillTransmable = fillPaint.IsFillTransformable;

                WpfSvgPaint strokePaint = new WpfSvgPaint(context, styleElm, "stroke");
                Pen         pen         = strokePaint.GetPen(geometry);

                if (_paintContext != null)
                {
                    _paintContext.Fill   = fillPaint;
                    _paintContext.Stroke = strokePaint;
                    _paintContext.Tag    = geometry;
                }

                if (brush != null || pen != null)
                {
                    Transform transform = this.Transform;
                    if (transform != null && !transform.Value.IsIdentity)
                    {
                        geometry.Transform = transform;
                        if (brush != null && isFillTransmable)
                        {
                            Transform brushTransform = brush.Transform;
                            if (brushTransform == null || brushTransform == Transform.Identity)
                            {
                                brush.Transform = transform;
                            }
                            else
                            {
                                TransformGroup groupTransform = new TransformGroup();
                                groupTransform.Children.Add(brushTransform);
                                groupTransform.Children.Add(transform);
                                brush.Transform = groupTransform;
                            }
                        }
                        if (pen != null && pen.Brush != null)
                        {
                            Transform brushTransform = pen.Brush.Transform;
                            if (brushTransform == null || brushTransform == Transform.Identity)
                            {
                                pen.Brush.Transform = transform;
                            }
                            else
                            {
                                TransformGroup groupTransform = new TransformGroup();
                                groupTransform.Children.Add(brushTransform);
                                groupTransform.Children.Add(transform);
                                pen.Brush.Transform = groupTransform;
                            }
                        }
                    }
                    else
                    {
                        transform = null; // render any identity transform useless...
                    }

                    GeometryDrawing drawing = new GeometryDrawing(brush, pen, geometry);

                    if (!string.IsNullOrWhiteSpace(elementId) && !context.IsRegisteredId(elementId))
                    {
                        SvgObject.SetName(drawing, elementId);

                        context.RegisterId(elementId);

                        if (context.IncludeRuntime)
                        {
                            SvgObject.SetId(drawing, elementId);
                        }
                    }

                    if (!string.IsNullOrWhiteSpace(elementClass) && context.IncludeRuntime)
                    {
                        SvgObject.SetClass(drawing, elementClass);
                    }

                    Brush    maskBrush = this.Masking;
                    Geometry clipGeom  = this.ClipGeometry;
                    if (clipGeom != null || maskBrush != null)
                    {
                        //Geometry clipped = Geometry.Combine(geometry, clipGeom,
                        //    GeometryCombineMode.Exclude, null);

                        //if (clipped != null && !clipped.IsEmpty())
                        //{
                        //    geometry = clipped;
                        //}
                        DrawingGroup clipMaskGroup = new DrawingGroup();

                        Rect geometryBounds = geometry.Bounds;

                        if (clipGeom != null)
                        {
                            clipMaskGroup.ClipGeometry = clipGeom;

                            SvgUnitType clipUnits = this.ClipUnits;
                            if (clipUnits == SvgUnitType.ObjectBoundingBox)
                            {
                                Rect drawingBounds = geometryBounds;

                                if (transform != null)
                                {
                                    drawingBounds = transform.TransformBounds(drawingBounds);
                                }

                                TransformGroup transformGroup = new TransformGroup();

                                // Scale the clip region (at (0, 0)) and translate to the top-left corner of the target.
                                transformGroup.Children.Add(new ScaleTransform(drawingBounds.Width, drawingBounds.Height));
                                transformGroup.Children.Add(new TranslateTransform(drawingBounds.X, drawingBounds.Y));

                                clipGeom.Transform = transformGroup;
                            }
                            else
                            {
                                if (transform != null)
                                {
                                    clipGeom.Transform = transform;
                                }
                            }
                        }
                        if (maskBrush != null)
                        {
                            DrawingBrush drawingBrush = (DrawingBrush)maskBrush;

                            SvgUnitType maskUnits        = this.MaskUnits;
                            SvgUnitType maskContentUnits = this.MaskContentUnits;
                            if (maskUnits == SvgUnitType.ObjectBoundingBox)
                            {
                                Rect drawingBounds = geometryBounds;

                                if (transform != null)
                                {
                                    drawingBounds = transform.TransformBounds(drawingBounds);
                                }
                                DrawingGroup maskGroup = drawingBrush.Drawing as DrawingGroup;
                                if (maskGroup != null)
                                {
                                    DrawingCollection maskDrawings = maskGroup.Children;
                                    for (int i = 0; i < maskDrawings.Count; i++)
                                    {
                                        Drawing         maskDrawing  = maskDrawings[i];
                                        GeometryDrawing maskGeomDraw = maskDrawing as GeometryDrawing;
                                        if (maskGeomDraw != null)
                                        {
                                            if (maskGeomDraw.Brush != null)
                                            {
                                                ConvertColors(maskGeomDraw.Brush);
                                            }
                                            if (maskGeomDraw.Pen != null)
                                            {
                                                ConvertColors(maskGeomDraw.Pen.Brush);
                                            }
                                        }
                                    }
                                }

                                if (maskContentUnits == SvgUnitType.ObjectBoundingBox)
                                {
                                    TransformGroup transformGroup = new TransformGroup();

                                    // Scale the clip region (at (0, 0)) and translate to the top-left corner of the target.
                                    var scaleTransform = new ScaleTransform(drawingBounds.Width, drawingBounds.Height);
                                    transformGroup.Children.Add(scaleTransform);
                                    var translateTransform = new TranslateTransform(drawingBounds.X, drawingBounds.Y);
                                    transformGroup.Children.Add(translateTransform);

                                    Matrix scaleMatrix     = new Matrix();
                                    Matrix translateMatrix = new Matrix();

                                    scaleMatrix.Scale(drawingBounds.Width, drawingBounds.Height);
                                    translateMatrix.Translate(drawingBounds.X, drawingBounds.Y);

                                    Matrix matrix = Matrix.Multiply(scaleMatrix, translateMatrix);
                                    //maskBrush.Transform = transformGroup;
                                    maskBrush.Transform = new MatrixTransform(matrix);
                                }
                                else
                                {
                                    drawingBrush.Viewbox      = drawingBounds;
                                    drawingBrush.ViewboxUnits = BrushMappingMode.Absolute;

                                    drawingBrush.Stretch = Stretch.Uniform;

                                    drawingBrush.Viewport      = drawingBounds;
                                    drawingBrush.ViewportUnits = BrushMappingMode.Absolute;
                                }
                            }
                            else
                            {
                                if (transform != null)
                                {
                                    maskBrush.Transform = transform;
                                }
                            }

                            clipMaskGroup.OpacityMask = maskBrush;
                        }

                        clipMaskGroup.Children.Add(drawing);
                        drawGroup.Children.Add(clipMaskGroup);
                    }
                    else
                    {
                        drawGroup.Children.Add(drawing);
                    }
                }
            }

            // If this is not the child of a "marker", then try rendering a marker...
            if (!string.Equals(parentNode.LocalName, "marker"))
            {
                RenderMarkers(renderer, styleElm, context);
            }
        }
Beispiel #12
0
        // disable default rendering
        public override void BeforeRender(WpfDrawingRenderer renderer)
        {
            base.BeforeRender(renderer);

            _matrix = Matrix.Identity;

            WpfDrawingContext context = renderer.Context;

            //SetQuality(context);
            //SetTransform(context);
            //SetClip(_context);
            //SetMask(_context);

            _drawGroup = new DrawingGroup();

            string sVisibility = _markerElement.GetPropertyValue("visibility");
            string sDisplay    = _markerElement.GetPropertyValue("display");

            if (string.Equals(sVisibility, "hidden") || string.Equals(sDisplay, "none"))
            {
                // A 'marker' element with 'display' set to 'none' on that element or any
                // ancestor is rendered when referenced by another element.

                // _drawGroup.Opacity = 0;
            }

            string elementId = this.GetElementName();

            if (!string.IsNullOrWhiteSpace(elementId) && !context.IsRegisteredId(elementId))
            {
                _drawGroup.SetValue(FrameworkElement.NameProperty, elementId);

                context.RegisterId(elementId);

                if (context.IncludeRuntime)
                {
                    SvgObject.SetId(_drawGroup, elementId);
                }
            }

            string elementClass = this.GetElementClass();

            if (!string.IsNullOrWhiteSpace(elementClass) && context.IncludeRuntime)
            {
                SvgObject.SetClass(_drawGroup, elementClass);
            }

            //Transform markerTransform = this.Transform;
            //if (markerTransform != null && !markerTransform.Value.IsIdentity)
            //{
            //    _drawGroup.Transform = markerTransform;
            //}
            //else
            //{
            //    markerTransform = null; // render any identity transform useless...
            //}
            Geometry markerClip = this.ClipGeometry;

            if (markerClip != null && !markerClip.IsEmpty())
            {
                _drawGroup.ClipGeometry = markerClip;
            }
            else
            {
                markerClip = null; // render any empty geometry useless...
            }
            Brush markerMask = this.Masking;

            if (markerMask != null)
            {
                _drawGroup.OpacityMask = markerMask;
            }

            DrawingGroup currentGroup = context.Peek();

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

            currentGroup.Children.Add(_drawGroup);
            context.Push(_drawGroup);
        }
        public override void Visit(DrawingGroup group, SvgAElement element,
                                   WpfDrawingContext context, float opacity)
        {
            _isAggregated = false;

            if (group == null || element == null || context == null)
            {
                return;
            }

            AddExtraLinkInformation(group, element);

            //string linkId = element.GetAttribute("id");
            string linkId = GetElementName(element);

            if (string.IsNullOrWhiteSpace(linkId))
            {
                return;
            }
            SvgLink.SetKey(group, linkId);

            if (_dicLinks.ContainsKey(linkId))
            {
                _isAggregated = _dicLinks[linkId];
                return;
            }

            string linkAction = element.GetAttribute("onclick");

            if (string.IsNullOrWhiteSpace(linkAction))
            {
                linkAction = element.GetAttribute("onmouseover");
                if (!string.IsNullOrWhiteSpace(linkAction) &&
                    linkAction.StartsWith("parent.svgMouseOverName", StringComparison.OrdinalIgnoreCase))
                {
                    SvgLink.SetAction(group, SvgLinkAction.LinkTooltip);
                }
                else
                {
                    SvgLink.SetAction(group, SvgLinkAction.LinkNone);
                }
            }
            else
            {
                if (linkAction.StartsWith("parent.svgClick", StringComparison.OrdinalIgnoreCase))
                {
                    SvgLink.SetAction(group, SvgLinkAction.LinkPage);
                }
                else if (linkAction.StartsWith("parent.svgOpenHtml", StringComparison.OrdinalIgnoreCase))
                {
                    SvgLink.SetAction(group, SvgLinkAction.LinkHtml);
                }
                else
                {
                    SvgLink.SetAction(group, SvgLinkAction.LinkNone);
                }
            }

            if (!string.IsNullOrWhiteSpace(linkAction))
            {
                if (linkAction.IndexOf("'Top'", StringComparison.OrdinalIgnoreCase) > 0)
                {
                    SvgLink.SetLocation(group, "Top");
                }
                else if (linkAction.IndexOf("'Bottom'", StringComparison.OrdinalIgnoreCase) > 0)
                {
                    SvgLink.SetLocation(group, "Bottom");
                }
                else
                {
                    SvgLink.SetLocation(group, "Top");
                }
            }

            this.AggregateChildren(element, context, opacity);
            if (_isAggregated)
            {
                Geometry drawGeometry = null;
                if (_aggregatedGeom.Count == 1)
                {
                    drawGeometry = _aggregatedGeom[0];
                }
                else
                {
                    GeometryGroup geomGroup = new GeometryGroup();
                    geomGroup.FillRule = FillRule.Nonzero;

                    for (int i = 0; i < _aggregatedGeom.Count; i++)
                    {
                        geomGroup.Children.Add(_aggregatedGeom[i]);
                    }

                    drawGeometry = geomGroup;
                }

                WpfSvgPaint fillPaint = new WpfSvgPaint(context, _aggregatedFill, "fill");
                Brush       brush     = fillPaint.GetBrush(false);

                SvgObject.SetName(brush, linkId + "_Brush");

                GeometryDrawing drawing = new GeometryDrawing(brush, null, drawGeometry);

                group.Children.Add(drawing);
            }

            _dicLinks.Add(linkId, _isAggregated);
        }
        public override void BeforeRender(WpfDrawingRenderer renderer)
        {
            base.BeforeRender(renderer);

            _isTextPath   = false;
            _isGroupAdded = false;
            _textWidth    = 0;
            _isMeasuring  = false;

            WpfDrawingContext context = renderer.Context;

            SvgRenderingHint hint = _svgElement.RenderingHint;

            if (hint == SvgRenderingHint.Clipping)
            {
                return;
            }
            // We do not directly render the contents of the clip-path, unless specifically requested...
            if (string.Equals(_svgElement.ParentNode.LocalName, "clipPath") &&
                !context.RenderingClipRegion)
            {
                return;
            }

            _context = renderer.Context;

            SetQuality(context);
            SetTransform(context);

            SetClip(_context);

            SetMask(_context);

            _drawGroup = new DrawingGroup();

            string sVisibility = _textElement.GetPropertyValue("visibility");
            string sDisplay    = _textElement.GetPropertyValue("display");

            if (string.Equals(sVisibility, "hidden") || string.Equals(sDisplay, "none"))
            {
                _drawGroup.Opacity = 0;
            }

            string elementId = this.GetElementName();

            if (!string.IsNullOrWhiteSpace(elementId) && !context.IsRegisteredId(elementId))
            {
                SvgObject.SetName(_drawGroup, elementId);

                context.RegisterId(elementId);

                if (context.IncludeRuntime)
                {
                    SvgObject.SetId(_drawGroup, elementId);
                }
            }

            string elementClass = this.GetElementClass();

            if (!string.IsNullOrWhiteSpace(elementClass) && context.IncludeRuntime)
            {
                SvgObject.SetClass(_drawGroup, elementClass);
            }

            Transform textTransform = this.Transform;

            if (textTransform != null && !textTransform.Value.IsIdentity)
            {
                _drawGroup.Transform = textTransform;
            }
            else
            {
                textTransform = null; // render any identity transform useless...
            }
            Geometry textClip = this.ClipGeometry;

            if (textClip != null && !textClip.IsEmpty())
            {
                _drawGroup.ClipGeometry = textClip;
            }
            else
            {
                textClip = null; // render any empty geometry useless...
            }
            Brush textMask = this.Masking;

            if (textMask != null)
            {
                _drawGroup.OpacityMask = textMask;
            }

            if (textTransform != null || textClip != null || textMask != null)
            {
                DrawingGroup curGroup = _context.Peek();
                Debug.Assert(curGroup != null);
                if (curGroup != null)
                {
                    curGroup.Children.Add(_drawGroup);
                    context.Push(_drawGroup);

                    _isGroupAdded = true;
                }
            }

            _drawContext = _drawGroup.Open();

            _horzRenderer.Initialize(_drawContext, _context);
            _vertRenderer.Initialize(_drawContext, _context);
            _pathRenderer.Initialize(_drawContext, _context);
        }
        public override void Render(WpfDrawingRenderer renderer)
        {
            Geometry  clipGeom  = this.ClipGeometry;
            Transform transform = this.Transform;

            WpfDrawingContext context = renderer.Context;

            SvgSwitchElement switchElement = (SvgSwitchElement)_svgElement;

            string elementId = this.GetElementName();

            float opacityValue = -1;

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

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

            if (clipGeom != null || transform != null || (opacityValue >= 0 && opacityValue < 1) ||
                (!string.IsNullOrWhiteSpace(elementId) && !context.IsRegisteredId(elementId)))
            {
                _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);

                if (clipGeom != null)
                {
                    _drawGroup.ClipGeometry = clipGeom;
                }

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

                if (opacityValue >= 0 && opacityValue < 1)
                {
                    _drawGroup.Opacity = opacityValue;
                }

                if (!string.IsNullOrWhiteSpace(elementId) && !context.IsRegisteredId(elementId))
                {
                    SvgObject.SetName(_drawGroup, elementId);

                    context.RegisterId(elementId);

                    if (context.IncludeRuntime)
                    {
                        SvgObject.SetId(_drawGroup, elementId);
                    }
                }
            }

            base.Render(renderer);
        }
Beispiel #16
0
        private void WriteObject(object key, object obj, XmlWriter writer, bool isRoot)
        {
            List <MarkupProperty> propertyElements = new List <MarkupProperty>();
            MarkupProperty        contentProperty  = null;
            string       contentPropertyName       = null;
            MarkupObject markupObj  = MarkupWriter.GetMarkupObjectFor(obj);
            Type         objectType = markupObj.ObjectType;

            string ns     = _namespaceCache.GetNamespaceUriFor(objectType);
            string prefix = _namespaceCache.GetDefaultPrefixFor(ns);

            if (isRoot)
            {
                if (String.IsNullOrEmpty(prefix))
                {
                    if (String.IsNullOrEmpty(ns))
                    {
                        writer.WriteStartElement(markupObj.ObjectType.Name, NamespaceCache.DefaultNamespace);
                        writer.WriteAttributeString("xmlns",
                                                    NamespaceCache.XmlnsNamespace, NamespaceCache.DefaultNamespace);
                    }
                    else
                    {
                        writer.WriteStartElement(markupObj.ObjectType.Name, ns);
                        writer.WriteAttributeString("xmlns", NamespaceCache.XmlnsNamespace, ns);
                    }
                }
                else
                {
                    writer.WriteStartElement(prefix, markupObj.ObjectType.Name, ns);
                }
                writer.WriteAttributeString("xmlns", "x",
                                            NamespaceCache.XmlnsNamespace, NamespaceCache.XamlNamespace);

                foreach (NamespaceMap map in _dicNamespaceMap.Values)
                {
                    if (!String.IsNullOrEmpty(map.Prefix) && !String.Equals(map.Prefix, "x"))
                    {
                        writer.WriteAttributeString("xmlns", map.Prefix, NamespaceCache.XmlnsNamespace, map.XmlNamespace);
                    }
                }
            }
            else
            {
                //TODO: Fix - the best way to handle this case...
                if (markupObj.ObjectType.Name == "PathFigureCollection" && markupObj.Instance != null)
                {
                    WriteState writeState = writer.WriteState;

                    if (writeState == WriteState.Element)
                    {
                        //writer.WriteAttributeString("Figures",
                        //    markupObj.Instance.ToString());
                        writer.WriteAttributeString("Figures",
                                                    System.Convert.ToString(markupObj.Instance, _culture));
                    }
                    else
                    {
                        if (String.IsNullOrEmpty(prefix))
                        {
                            writer.WriteStartElement("PathGeometry.Figures");
                        }
                        else
                        {
                            writer.WriteStartElement("PathGeometry.Figures", ns);
                        }
                        //writer.WriteString(markupObj.Instance.ToString());
                        writer.WriteString(System.Convert.ToString(
                                               markupObj.Instance, _culture));
                        writer.WriteEndElement();
                    }
                    return;
                }
                else
                {
                    if (String.IsNullOrEmpty(prefix))
                    {
                        writer.WriteStartElement(markupObj.ObjectType.Name);
                    }
                    else
                    {
                        writer.WriteStartElement(markupObj.ObjectType.Name, ns);
                    }
                }
            }

            // Add the x:Name for object like Geometry/Drawing not derived from FrameworkElement...
            DependencyObject dep = obj as DependencyObject;

            if (dep != null)
            {
                string nameValue = SvgObject.GetName(dep);
                if (!String.IsNullOrEmpty(nameValue) && !(dep is FrameworkElement))
                {
                    writer.WriteAttributeString("x", "Name", NamespaceCache.XamlNamespace, nameValue);
                }
            }

            if (key != null)
            {
                string keyString = key.ToString();
                if (keyString.Length > 0)
                {
                    writer.WriteAttributeString("x", "Key", NamespaceCache.XamlNamespace, keyString);
                }
                else
                {
                    //TODO: key may not be a string, what about x:Type...
                    throw new NotImplementedException(
                              "Sample XamlWriter cannot yet handle keys that aren't strings");
                }
            }

            //Look for CPA info in our cache that keeps contentProperty names per Type
            //If it doesn't have an entry, go get the info and store it.
            if (!_contentProperties.ContainsKey(objectType))
            {
                string lookedUpContentProperty = String.Empty;
                foreach (Attribute attr in markupObj.Attributes)
                {
                    ContentPropertyAttribute cpa = attr as ContentPropertyAttribute;
                    if (cpa != null)
                    {
                        lookedUpContentProperty = cpa.Name;
                        //Once content property is found, come out of the loop.
                        break;
                    }
                }

                _contentProperties.Add(objectType, lookedUpContentProperty);
            }

            contentPropertyName = _contentProperties[objectType];
            string contentString = String.Empty;

            foreach (MarkupProperty markupProperty in markupObj.Properties)
            {
                if (markupProperty.Name != contentPropertyName)
                {
                    if (markupProperty.IsValueAsString)
                    {
                        contentString = markupProperty.Value as string;
                    }
                    else if (!markupProperty.IsComposite)
                    {
                        string temp = markupProperty.StringValue;

                        if (markupProperty.IsAttached)
                        {
                            string ns1     = _namespaceCache.GetNamespaceUriFor(markupProperty.DependencyProperty.OwnerType);
                            string prefix1 = _namespaceCache.GetDefaultPrefixFor(ns1);

                            if (String.IsNullOrEmpty(prefix1))
                            {
                                writer.WriteAttributeString(markupProperty.Name, temp);
                            }
                            else
                            {
                                writer.WriteAttributeString(markupProperty.Name, ns1, temp);
                            }
                        }
                        else
                        {
                            if (markupProperty.Name == "FontUri" &&
                                (_wpfSettings != null && _wpfSettings.IncludeRuntime))
                            {
                                string fontUri = temp.ToLower();
                                fontUri = fontUri.Replace(_windowsDir, _windowsPath);

                                StringBuilder builder = new StringBuilder();
                                builder.Append("{");
                                builder.Append("svg");
                                builder.Append(":");
                                builder.Append("SvgFontUri ");
                                builder.Append(fontUri);
                                builder.Append("}");

                                writer.WriteAttributeString(markupProperty.Name, builder.ToString());
                            }
                            else
                            {
                                writer.WriteAttributeString(markupProperty.Name, temp);
                            }
                        }
                    }
                    else if (markupProperty.Value.GetType() == _nullType)
                    {
                        if (_nullExtension)
                        {
                            writer.WriteAttributeString(markupProperty.Name, "{x:Null}");
                        }
                    }
                    else
                    {
                        propertyElements.Add(markupProperty);
                    }
                }
                else
                {
                    contentProperty = markupProperty;
                }
            }

            if (contentProperty != null || propertyElements.Count > 0 || contentString != String.Empty)
            {
                foreach (MarkupProperty markupProp in propertyElements)
                {
                    string ns2     = _namespaceCache.GetNamespaceUriFor(markupObj.ObjectType);
                    string prefix2 = null;
                    if (!String.IsNullOrEmpty(ns2))
                    {
                        prefix2 = _namespaceCache.GetDefaultPrefixFor(ns2);
                    }

                    string propElementName = markupObj.ObjectType.Name + "." + markupProp.Name;
                    if (String.IsNullOrEmpty(prefix2))
                    {
                        writer.WriteStartElement(propElementName);
                    }
                    else
                    {
                        writer.WriteStartElement(prefix2, propElementName, ns2);
                    }

                    WriteChildren(writer, markupProp);
                    writer.WriteEndElement();
                }

                if (contentString != String.Empty)
                {
                    writer.WriteValue(contentString);
                }
                else if (contentProperty != null)
                {
                    if (contentProperty.Value is string)
                    {
                        writer.WriteValue(contentProperty.StringValue);
                    }
                    else
                    {
                        WriteChildren(writer, contentProperty);
                    }
                }
            }
            writer.WriteEndElement();
        }
        private Drawing PerformHitTest(Point pt)
        {
            _hitGroup = null;
            if (_hitList == null)
            {
                _hitList = new SortedList <int, Drawing>();
            }
            else if (_hitList.Count != 0)
            {
                _hitList.Clear();
            }

            if (_svgDrawing == null)
            {
                return(null);
            }

            Point ptDisplay = _displayTransform.Transform(pt);

            DrawingGroup    groupDrawing    = null;
            GlyphRunDrawing glyRunDrawing   = null;
            GeometryDrawing geometryDrawing = null;

            Drawing foundDrawing = null;

            DrawingCollection drawings = _svgDrawing.Children;

            for (int i = drawings.Count - 1; i >= 0; i--)
            {
                Drawing drawing = drawings[i];
                if (TryCast.Cast(drawing, out geometryDrawing))
                {
                    if (HitTestDrawing(geometryDrawing, ptDisplay))
                    {
                        int orderNumber = SvgObject.GetOrder(drawing);
                        if (orderNumber >= 0)
                        {
                            _hitList[orderNumber] = drawing;
                        }
                        else
                        {
                            string uniqueId = SvgObject.GetUniqueId(geometryDrawing);
                            if (!string.IsNullOrWhiteSpace(uniqueId))
                            {
                                foundDrawing = drawing;
                                break;
                            }
                        }
                    }
                }
                else if (TryCast.Cast(drawing, out groupDrawing))
                {
                    int orderNumber = SvgObject.GetOrder(drawing);
                    if (SvgObject.GetType(groupDrawing) == SvgObjectType.Text &&
                        groupDrawing.Bounds.Contains(ptDisplay))
                    {
                        if (orderNumber >= 0)
                        {
                            _hitList[orderNumber] = drawing;
                        }
                        else
                        {
                            foundDrawing = drawing;
                            break;
                        }
                    }
                    if (HitTestDrawing(groupDrawing, ptDisplay, out foundDrawing))
                    {
                        if (orderNumber >= 0)
                        {
                            _hitList[orderNumber] = drawing;
                        }
                        else
                        {
                            string uniqueId = SvgObject.GetUniqueId(foundDrawing);
                            if (!string.IsNullOrWhiteSpace(uniqueId))
                            {
                                //foundDrawing = drawing;
                                break;
                            }
                        }
                    }
                }
                else if (TryCast.Cast(drawing, out glyRunDrawing))
                {
                    if (HitTestDrawing(glyRunDrawing, ptDisplay))
                    {
                        int orderNumber = SvgObject.GetOrder(drawing);
                        if (orderNumber >= 0)
                        {
                            _hitList[orderNumber] = drawing;
                        }
                        else
                        {
                            foundDrawing = drawing;
                            break;
                        }
                    }
                }
            }

            if (_hitList.Count != 0)
            {
                return(_hitList.LastOrDefault().Value);
            }

            if (foundDrawing == null)
            {
                return(_hitGroup);
            }

            return(foundDrawing);
        }
        private Drawing PerformHitTest(Point pt)
        {
            if (_svgDrawing == null)
            {
                return(null);
            }

            _hitGroup = null;
            if (_hitList == null)
            {
                _hitList  = new SortedList <int, Drawing>();
                _hitPaths = new SortedList <int, WpfHitPath>();
            }
            else if (_hitList.Count != 0)
            {
                _hitList.Clear();
                _hitPaths.Clear();
            }

            var hitRootPath = new WpfHitPath();

            _hitPath = hitRootPath;

            Point ptDisplay = _displayTransform.Transform(pt);

            DrawingGroup    groupDrawing    = null;
            GlyphRunDrawing glyRunDrawing   = null;
            GeometryDrawing geometryDrawing = null;

            Drawing foundDrawing = null;

            //var isFound = false;
            //var drawingLayer = this.GetDrawingLayer(_svgDrawing, ref isFound);
            //System.Diagnostics.Trace.WriteLine("GetId: " + SvgObject.GetId(drawingLayer));
            //System.Diagnostics.Trace.WriteLine("GetName: " + SvgObject.GetName(drawingLayer));
            //System.Diagnostics.Trace.WriteLine("GetUniqueId: " + SvgObject.GetUniqueId(drawingLayer));

            //DrawingCollection drawings = drawingLayer.Children;
            DrawingCollection drawings = _svgDrawing.Children;

            for (int i = drawings.Count - 1; i >= 0; i--)
            {
                Drawing drawing = drawings[i];
                System.Diagnostics.Trace.WriteLine("GetId: " + SvgObject.GetId(drawing));
                System.Diagnostics.Trace.WriteLine("GetName: " + SvgObject.GetName(drawing));
                System.Diagnostics.Trace.WriteLine("GetUniqueId: " + SvgObject.GetUniqueId(drawing));

                if (TryCast.Cast(drawing, out geometryDrawing))
                {
                    if (HitTestDrawing(geometryDrawing, ptDisplay))
                    {
//                        _hitPath = _hitPath.AddChild(SvgObject.GetUniqueId(geometryDrawing));

                        int orderNumber = SvgObject.GetOrder(drawing);
                        if (orderNumber >= 0)
                        {
                            _hitList[orderNumber]  = drawing;
                            _hitPaths[orderNumber] = _hitPath.AddChild(SvgObject.GetUniqueId(geometryDrawing));
                        }
                        else
                        {
                            string uniqueId = SvgObject.GetUniqueId(geometryDrawing);
                            if (!string.IsNullOrWhiteSpace(uniqueId))
                            {
                                foundDrawing = drawing;
                                break;
                            }
                        }
                    }
                }
                else if (TryCast.Cast(drawing, out groupDrawing))
                {
                    //var ptSaved = ptDisplay;
                    //var transform = groupDrawing.Transform;
                    //if (transform != null && !transform.Value.IsIdentity)
                    //{
                    //    ptDisplay = transform.Inverse.Transform(ptDisplay);
                    //}

                    _hitPath = hitRootPath.AddChild(SvgObject.GetUniqueId(groupDrawing));

                    int orderNumber = SvgObject.GetOrder(groupDrawing);
                    //if (SvgObject.GetType(groupDrawing) == SvgObjectType.Text &&
                    //    groupDrawing.Bounds.Contains(ptDisplay))
                    if (SvgObject.GetType(groupDrawing) == SvgObjectType.Text &&
                        this.HitTestText(groupDrawing, ptDisplay, out foundDrawing))
                    {
                        if (orderNumber >= 0)
                        {
                            _hitList[orderNumber]  = drawing;
                            _hitPaths[orderNumber] = _hitPath;
                        }
                        else
                        {
                            foundDrawing = drawing;
                            break;
                        }
                    }
                    else
                    {
//                        _hitPath = _hitPath.AddChild(SvgObject.GetUniqueId(groupDrawing));

                        var currentPath = _hitPath;
                        try
                        {
                            if (HitTestDrawing(groupDrawing, ptDisplay, out foundDrawing))
                            {
                                if (orderNumber >= 0)
                                {
                                    _hitList[orderNumber]  = drawing;
                                    _hitPaths[orderNumber] = _hitPath.AddChild(SvgObject.GetUniqueId(foundDrawing));
                                }
                                else
                                {
                                    string uniqueId = SvgObject.GetUniqueId(foundDrawing);
                                    if (!string.IsNullOrWhiteSpace(uniqueId))
                                    {
                                        //foundDrawing = drawing;
                                        break;
                                    }
                                }
                            }
                        }
                        finally
                        {
                            _hitPath = currentPath;
                        }
                    }
                }
                else if (TryCast.Cast(drawing, out glyRunDrawing))
                {
                    if (HitTestDrawing(glyRunDrawing, ptDisplay))
                    {
//                        _hitPath = _hitPath.AddChild(SvgObject.GetUniqueId(glyRunDrawing));

                        int orderNumber = SvgObject.GetOrder(drawing);
                        if (orderNumber >= 0)
                        {
                            _hitList[orderNumber]  = drawing;
                            _hitPaths[orderNumber] = _hitPath.AddChild(SvgObject.GetUniqueId(glyRunDrawing));
                        }
                        else
                        {
                            foundDrawing = drawing;
                            break;
                        }
                    }
                }
            }

            if (_hitList.Count != 0)
            {
                var key = _hitList.LastOrDefault().Key;
                if (_hitPaths.ContainsKey(key))
                {
                    System.Diagnostics.Trace.WriteLine("Key Found: " + _hitPaths[key].Path);
                }
                return(_hitList.LastOrDefault().Value);
            }

            if (foundDrawing == null)
            {
                return(_hitGroup);
            }

            return(foundDrawing);
        }
Beispiel #19
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)
                {
                    SvgObject.SetName(_drawGroup, 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);
            }

            SvgSymbolElement svgElm = (SvgSymbolElement)_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);

            XmlNode parentNode = _svgElement.ParentNode;

            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;
                        }
                    }
                }
            }

            FitToViewbox(context, elmRect);

            Transform 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);
                    }
                }
            }
        }
        /// <summary>
        /// Performs the conversion of a valid SVG source file to the <see cref="DrawingGroup"/>.
        /// </summary>
        /// <param name="svgSource">A <see cref="Uri"/> defining the path to the SVG source.</param>
        /// <param name="settings">
        /// This specifies the settings used by the rendering or drawing engine.
        /// If this is <see langword="null"/>, the default settings is used.
        /// </param>
        /// <returns>
        /// This returns <see cref="DrawingGroup"/> if successful; otherwise, it
        /// returns <see langword="null"/>.
        /// </returns>
        protected virtual DrawingGroup CreateDrawing(Uri svgSource, WpfDrawingSettings settings)
        {
            if (svgSource == null)
            {
                return(null);
            }

            string scheme = svgSource.Scheme;

            if (string.IsNullOrWhiteSpace(scheme))
            {
                return(null);
            }

            var comparer = StringComparison.OrdinalIgnoreCase;

            DrawingGroup drawing = null;

            switch (scheme)
            {
            case "file":
            //case "ftp":
            case "https":
            case "http":
                using (FileSvgReader reader = new FileSvgReader(settings))
                {
                    drawing = reader.Read(svgSource);
                }
                break;

            case "pack":
                StreamResourceInfo svgStreamInfo = null;
                if (svgSource.ToString().IndexOf("siteoforigin", comparer) >= 0)
                {
                    svgStreamInfo = Application.GetRemoteStream(svgSource);
                }
                else
                {
                    svgStreamInfo = Application.GetResourceStream(svgSource);
                }

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

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

                    if (isCompressed)
                    {
                        using (svgStream)
                        {
                            using (GZipStream zipStream = new GZipStream(svgStream, CompressionMode.Decompress))
                            {
                                using (FileSvgReader reader = new FileSvgReader(settings))
                                {
                                    drawing = reader.Read(zipStream);
                                }
                            }
                        }
                    }
                    else
                    {
                        using (svgStream)
                        {
                            using (FileSvgReader reader = new FileSvgReader(settings))
                            {
                                drawing = reader.Read(svgStream);
                            }
                        }
                    }
                }
                break;

            case "data":
                var sourceData = svgSource.OriginalString.Replace(" ", "");

                int nColon     = sourceData.IndexOf(":", comparer);
                int nSemiColon = sourceData.IndexOf(";", comparer);
                int nComma     = sourceData.IndexOf(",", comparer);

                string sMimeType = sourceData.Substring(nColon + 1, nSemiColon - nColon - 1);
                string sEncoding = sourceData.Substring(nSemiColon + 1, nComma - nSemiColon - 1);

                if (string.Equals(sMimeType.Trim(), "image/svg+xml", comparer) &&
                    string.Equals(sEncoding.Trim(), "base64", comparer))
                {
                    string sContent   = SvgObject.RemoveWhitespace(sourceData.Substring(nComma + 1));
                    byte[] imageBytes = Convert.FromBase64CharArray(sContent.ToCharArray(),
                                                                    0, sContent.Length);
                    using (var stream = new MemoryStream(imageBytes))
                    {
                        using (var reader = new FileSvgReader(settings))
                        {
                            drawing = reader.Read(stream);
                        }
                    }
                }
                break;
            }

            return(drawing);
        }
Beispiel #21
0
        private ImageSource GetImage(SvgImageElement element, WpfDrawingContext context)
        {
            bool   isSavingImages = _saveImages;
            string imagesDir      = _saveDirectory;

            if (context != null && context.Settings.IncludeRuntime == false)
            {
                isSavingImages = true;
                if (string.IsNullOrWhiteSpace(_saveDirectory) ||
                    Directory.Exists(_saveDirectory) == false)
                {
                    var assembly = Assembly.GetExecutingAssembly();
                    if (assembly != null)
                    {
                        imagesDir = Path.GetDirectoryName(assembly.Location);
                    }
                }
            }

            var comparer = StringComparison.OrdinalIgnoreCase;

            string sURI       = element.Href.AnimVal.Replace(" ", "");
            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 = SvgObject.RemoveWhitespace(sURI.Substring(nComma + 1));

            byte[] imageBytes = Convert.FromBase64CharArray(sContent.ToCharArray(),
                                                            0, sContent.Length);
            bool isGZiped = sContent.StartsWith(SvgObject.GZipSignature, StringComparison.Ordinal);

            if (string.Equals(sMimeType, "image/svg+xml", comparer))
            {
                if (isGZiped)
                {
                    using (var stream = new MemoryStream(imageBytes))
                    {
                        using (GZipStream zipStream = new GZipStream(stream, CompressionMode.Decompress))
                        {
                            using (var reader = new FileSvgReader(context.Settings))
                                return(new DrawingImage(reader.Read(zipStream)));
                        }
                    }
                }
                else
                {
                    using (var stream = new MemoryStream(imageBytes))
                    {
                        using (var reader = new FileSvgReader(context.Settings))
                            return(new DrawingImage(reader.Read(stream)));
                    }
                }
            }

            BitmapImage imageSource = new BitmapImage();

            imageSource.BeginInit();
            imageSource.CreateOptions = BitmapCreateOptions.PreservePixelFormat;
            imageSource.StreamSource  = new MemoryStream(imageBytes);
            imageSource.EndInit();

            imageSource.Freeze();

            if (isSavingImages && !string.IsNullOrWhiteSpace(imagesDir) &&
                Directory.Exists(imagesDir))
            {
                var imagePath = this.GetImagePath(imagesDir);

                BitmapEncoder encoder = new PngBitmapEncoder();
                encoder.Frames.Add(BitmapFrame.Create(imageSource));

                using (var fileStream = new FileStream(imagePath, FileMode.Create))
                {
                    encoder.Save(fileStream);
                }

                BitmapImage savedSource = new BitmapImage();

                savedSource.BeginInit();
                savedSource.CacheOption   = BitmapCacheOption.OnLoad;
                savedSource.CreateOptions = BitmapCreateOptions.PreservePixelFormat;
                savedSource.UriSource     = new Uri(imagePath);
                savedSource.EndInit();

                savedSource.Freeze();

                return(savedSource);
            }

            return(imageSource);
        }
Beispiel #22
0
        private ImageSource GetImage(SvgImageElement element, WpfDrawingContext context)
        {
            bool   isSavingImages = _saveImages;
            string imagesDir      = _saveDirectory;

            if (context != null && context.Settings.IncludeRuntime == false)
            {
                isSavingImages = true;
                if (string.IsNullOrWhiteSpace(_saveDirectory) ||
                    Directory.Exists(_saveDirectory) == false)
                {
                    var assembly = Assembly.GetExecutingAssembly();
                    if (assembly != null)
                    {
                        imagesDir = PathUtils.Combine(assembly);
                    }
                }
            }

            var comparer = StringComparison.OrdinalIgnoreCase;

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

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

            var  sContent   = SvgObject.RemoveWhitespace(sURI.Substring(nComma + 1));
            var  imageBytes = Convert.FromBase64CharArray(sContent.ToCharArray(), 0, sContent.Length);
            bool isGZiped   = sContent.StartsWith(SvgConstants.GZipSignature, StringComparison.Ordinal);
            bool isSvgOrXml = sContent.StartsWith(SvgConstants.SvgSignature, StringComparison.Ordinal) ||
                              sContent.StartsWith(SvgConstants.XmlSignature, StringComparison.Ordinal);

            if (string.Equals(sMimeType, "image/svg+xml", comparer) || isSvgOrXml)
            {
                if (isGZiped)
                {
                    using (var stream = new MemoryStream(imageBytes))
                    {
                        using (GZipStream zipStream = new GZipStream(stream, CompressionMode.Decompress))
                        {
                            using (var reader = new FileSvgReader(context.Settings, true))
                            {
                                return(new DrawingImage(reader.Read(zipStream)));
                            }
                        }
                    }
                }
                else
                {
                    using (var stream = new MemoryStream(imageBytes))
                    {
                        using (var reader = new FileSvgReader(context.Settings, true))
                        {
                            return(new DrawingImage(reader.Read(stream)));
                        }
                    }
                }
            }

            var memStream = new MemoryStream(imageBytes);

            BitmapImage imageSource = new BitmapImage();

            imageSource.BeginInit();
            imageSource.StreamSource  = memStream;
            imageSource.CacheOption   = BitmapCacheOption.OnLoad;
            imageSource.CreateOptions = BitmapCreateOptions.PreservePixelFormat;
            imageSource.EndInit();

            string imagePath = null;

            if (isSavingImages && !string.IsNullOrWhiteSpace(imagesDir) && Directory.Exists(imagesDir))
            {
                imagePath = this.GetImagePath(imagesDir);

                BitmapEncoder encoder = new PngBitmapEncoder();
                encoder.Frames.Add(BitmapFrame.Create(imageSource));

                using (var fileStream = new FileStream(imagePath, FileMode.Create))
                {
                    encoder.Save(fileStream);
                }

                imageSource.CreateOptions = BitmapCreateOptions.PreservePixelFormat | BitmapCreateOptions.IgnoreImageCache;
                imageSource.UriSource     = new Uri(imagePath);

                //imageSource.StreamSource.Dispose();
                //imageSource = null;

                //BitmapImage savedSource = new BitmapImage();

                //savedSource.BeginInit();
                //savedSource.CacheOption   = BitmapCacheOption.None;
                //savedSource.CreateOptions = BitmapCreateOptions.PreservePixelFormat | BitmapCreateOptions.IgnoreImageCache;
                //savedSource.UriSource = new Uri(imagePath);
                //savedSource.EndInit();

                //savedSource.Freeze();

                //if (_imageCreated != null)
                //{
                //    var eventArgs = new EmbeddedImageSerializerArgs(imagePath, savedSource);
                //    _imageCreated.Invoke(this, eventArgs);
                //}

                //return savedSource;
            }
            else if (_converterFallback)
            {
                //if (_imageCreated != null)
                //{
                //    var eventArgs = new EmbeddedImageSerializerArgs(imagePath, imageSource);
                //    _imageCreated.Invoke(this, eventArgs);
                //}
                return(new EmbeddedBitmapSource(memStream, imageSource));
            }
            if (_imageCreated != null)
            {
                var eventArgs = new EmbeddedImageSerializerArgs(imagePath, imageSource);
                _imageCreated.Invoke(this, eventArgs);
            }

            imageSource.Freeze();

            return(imageSource);
        }
Beispiel #23
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);
                    }
                }
            }
        }
Beispiel #24
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>
        protected virtual DrawingGroup GetDrawing(Uri svgSource)
        {
            string scheme = null;
            // A little hack to display preview in design mode: The design mode Uri is not absolute.
            bool designTime = DesignerProperties.GetIsInDesignMode(new DependencyObject());

            if (designTime && svgSource.IsAbsoluteUri == false)
            {
                scheme = "pack";
            }
            else
            {
                scheme = svgSource.Scheme;
            }
            if (string.IsNullOrWhiteSpace(scheme))
            {
                return(null);
            }

            WpfDrawingSettings settings = new WpfDrawingSettings();

            settings.IncludeRuntime = _includeRuntime;
            settings.TextAsGeometry = _textAsGeometry;
            settings.OptimizePath   = _optimizePath;
            if (_culture != null)
            {
                settings.CultureInfo = _culture;
            }

            switch (scheme)
            {
            case "file":
            //case "ftp":
            case "https":
            case "http":
                using (FileSvgReader reader = new FileSvgReader(settings))
                {
                    DrawingGroup drawGroup = reader.Read(svgSource);

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

            case "pack":
                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      = Path.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);
                                }
                            }
                        }
                    }
                }
                break;

            case "data":
                var sourceData = svgSource.OriginalString.Replace(" ", "");

                int nColon     = sourceData.IndexOf(":", StringComparison.OrdinalIgnoreCase);
                int nSemiColon = sourceData.IndexOf(";", StringComparison.OrdinalIgnoreCase);
                int nComma     = sourceData.IndexOf(",", StringComparison.OrdinalIgnoreCase);

                string sMimeType = sourceData.Substring(nColon + 1, nSemiColon - nColon - 1);
                string sEncoding = sourceData.Substring(nSemiColon + 1, nComma - nSemiColon - 1);

                if (string.Equals(sMimeType.Trim(), "image/svg+xml", StringComparison.OrdinalIgnoreCase) &&
                    string.Equals(sEncoding.Trim(), "base64", StringComparison.OrdinalIgnoreCase))
                {
                    string sContent   = SvgObject.RemoveWhitespace(sourceData.Substring(nComma + 1));
                    byte[] imageBytes = Convert.FromBase64CharArray(sContent.ToCharArray(),
                                                                    0, sContent.Length);
                    using (var stream = new MemoryStream(imageBytes))
                    {
                        using (var reader = new FileSvgReader(settings))
                        {
                            DrawingGroup drawGroup = reader.Read(stream);
                            if (drawGroup != null)
                            {
                                return(drawGroup);
                            }
                        }
                    }
                }
                break;
            }

            return(null);
        }
        private bool HitTestDrawing(DrawingGroup group, Point pt, out Drawing hitDrawing)
        {
            hitDrawing = null;
            bool isHit = false;

            if (group.Bounds.Contains(pt))
            {
                var transform = group.Transform;
                if (transform != null)
                {
                    var matrix = transform.Value;
                    if (matrix != null && matrix.IsIdentity == false)
                    {
                        pt = transform.Inverse.Transform(pt);
                    }
                }

                DrawingGroup    groupDrawing    = null;
                GlyphRunDrawing glyRunDrawing   = null;
                GeometryDrawing geometryDrawing = null;

                DrawingCollection drawings = group.Children;
                for (int i = drawings.Count - 1; i >= 0; i--)
                {
                    Drawing drawing = drawings[i];
                    if (TryCast.Cast(drawing, out geometryDrawing))
                    {
                        if (HitTestDrawing(geometryDrawing, pt))
                        {
                            hitDrawing = drawing;
                            int orderNumber = SvgObject.GetOrder(drawing);
                            if (orderNumber >= 0)
                            {
                                _hitList[orderNumber] = drawing;
                                isHit = false;
                            }
                            else
                            {
                                return(true);
                            }
                        }
                    }
                    else if (TryCast.Cast(drawing, out groupDrawing))
                    {
                        SvgObjectType objectType = SvgObject.GetType(groupDrawing);
                        //if (objectType == SvgObjectType.Text && groupDrawing.Bounds.Contains(pt))
                        if (objectType == SvgObjectType.Text)
                        {
                            hitDrawing = drawing;
                            int orderNumber = SvgObject.GetOrder(drawing);
                            if (orderNumber >= 0)
                            {
                                _hitList[orderNumber] = drawing;
                                isHit = false;
                            }
                            else
                            {
                                return(true);
                            }
                        }
                        if (HitTestDrawing(groupDrawing, pt, out hitDrawing))
                        {
                            int orderNumber = SvgObject.GetOrder(drawing);
                            if (orderNumber >= 0)
                            {
                                _hitList[orderNumber] = drawing;
                                isHit = false;
                            }
                            else
                            {
                                return(true);
                            }
                        }
                    }
                    else if (TryCast.Cast(drawing, out glyRunDrawing))
                    {
                        if (HitTestDrawing(glyRunDrawing, pt))
                        {
                            hitDrawing = glyRunDrawing;
                            int orderNumber = SvgObject.GetOrder(drawing);
                            if (orderNumber >= 0)
                            {
                                _hitList[orderNumber] = drawing;
                                isHit = false;
                            }
                            else
                            {
                                return(true);
                            }
                        }
                    }
                }
                string uniqueId = SvgObject.GetUniqueId(group);
                if (!string.IsNullOrWhiteSpace(uniqueId))
                {
                    _hitGroup = group;
                }
            }

            return(isHit);
        }
        private bool HitTestDrawing(DrawingGroup group, Point pt, out Drawing hitDrawing, bool isText = false)
        {
            hitDrawing = null;
            bool isHit = false;

            if (!group.Bounds.Contains(pt))
            {
                return(isHit);
            }
            var transform = group.Transform;

            if (transform != null && !transform.Value.IsIdentity)
            {
                pt = transform.Inverse.Transform(pt);
            }

            var groupHitPath = _hitPath;

            DrawingGroup    groupDrawing    = null;
            GlyphRunDrawing glyRunDrawing   = null;
            GeometryDrawing geometryDrawing = null;

            DrawingCollection drawings = group.Children;

            for (int i = drawings.Count - 1; i >= 0; i--)
            {
                Drawing drawing = drawings[i];

//                _hitPath = _hitPath.AddChild(SvgObject.GetUniqueId(drawing));

                if (TryCast.Cast(drawing, out geometryDrawing))
                {
                    if (HitTestDrawing(geometryDrawing, pt))
                    {
//                        _hitPath = _hitPath.AddChild(SvgObject.GetUniqueId(geometryDrawing));

                        hitDrawing = drawing;
                        int orderNumber = SvgObject.GetOrder(drawing);
                        if (orderNumber >= 0)
                        {
                            _hitList[orderNumber]  = drawing;
                            _hitPaths[orderNumber] = _hitPath.AddChild(SvgObject.GetUniqueId(geometryDrawing));
                            isHit = false;
                        }
                        else
                        {
                            orderNumber = SvgObject.GetOrder(group);
                            if (orderNumber >= 0)
                            {
                                _hitList[orderNumber]  = group;
                                _hitPaths[orderNumber] = _hitPath.AddChild(SvgObject.GetUniqueId(group));
                            }
                            if (!string.IsNullOrWhiteSpace(SvgObject.GetUniqueId(group)))
                            {
                                _hitGroup = group;
                            }
                            return(true);
                        }
                    }
                }
                else if (TryCast.Cast(drawing, out groupDrawing))
                {
                    _hitPath = groupHitPath.AddChild(SvgObject.GetUniqueId(groupDrawing));

                    SvgObjectType objectType = SvgObject.GetType(groupDrawing);
//                    if (objectType == SvgObjectType.Text && groupDrawing.Bounds.Contains(pt))
                    if (objectType == SvgObjectType.Text && this.HitTestText(groupDrawing, pt, out hitDrawing))
//                    if (objectType == SvgObjectType.Text)
                    {
                        hitDrawing = drawing;
                        int orderNumber = SvgObject.GetOrder(drawing);
                        if (orderNumber >= 0)
                        {
                            _hitList[orderNumber]  = drawing;
                            _hitPaths[orderNumber] = _hitPath;
                            isHit = false;
                        }
                        else
                        {
                            return(true);
                        }
                    }
                    else
                    {
                        //                        _hitPath = _hitPath.AddChild(SvgObject.GetUniqueId(hitDrawing));

                        var currentPath = _hitPath;
                        try
                        {
                            if (HitTestDrawing(groupDrawing, pt, out hitDrawing))
                            {
//                                int orderNumber = SvgObject.GetOrder(drawing);
                                int orderNumber = SvgObject.GetOrder(hitDrawing);
                                if (orderNumber >= 0)
                                {
                                    _hitList[orderNumber]  = drawing;
                                    _hitPaths[orderNumber] = _hitPath.AddChild(SvgObject.GetUniqueId(hitDrawing));
                                    isHit = false;
                                }
                                else
                                {
                                    orderNumber = SvgObject.GetOrder(groupDrawing);
                                    if (orderNumber >= 0)
                                    {
                                        _hitList[orderNumber]  = groupDrawing;
                                        _hitPaths[orderNumber] = _hitPath.AddChild(SvgObject.GetUniqueId(groupDrawing));
                                    }
                                    return(true);
                                }
                            }
                        }
                        finally
                        {
                            _hitPath = currentPath;
                        }
                    }
                }
                else if (TryCast.Cast(drawing, out glyRunDrawing))
                {
                    if (HitTestDrawing(glyRunDrawing, pt))
                    {
//                        _hitPath = _hitPath.AddChild(SvgObject.GetUniqueId(glyRunDrawing));

                        hitDrawing = glyRunDrawing;
                        int orderNumber = SvgObject.GetOrder(drawing);
                        if (orderNumber >= 0)
                        {
                            _hitList[orderNumber]  = drawing;
                            _hitPaths[orderNumber] = _hitPath.AddChild(SvgObject.GetUniqueId(glyRunDrawing));
                            isHit = false;
                        }
                        else
                        {
                            return(true);
                        }
                    }
                }
            }
            string uniqueId = SvgObject.GetUniqueId(group);

            if (!string.IsNullOrWhiteSpace(uniqueId))
            {
                _hitGroup = group;
            }

            return(isHit);
        }
        public override void AfterRender(WpfDrawingRenderer renderer)
        {
            if (_horzRenderer != null)
            {
                _horzRenderer.Uninitialize();
                _horzRenderer = null;
            }
            if (_vertRenderer != null)
            {
                _vertRenderer.Uninitialize();
                _vertRenderer = null;
            }
            if (_pathRenderer != null)
            {
                _pathRenderer.Uninitialize();
                _pathRenderer = null;
            }

            if (_drawContext != null)
            {
                _drawContext.Close();
                _drawContext = null;
            }

            WpfDrawingContext context = renderer.Context;

            // TODO-PAUL: Testing this for validity...
            // Remove the GuidelineSet from the groups added by the FormattedText to reduced the
            // size of output XAML...
            if (_drawGroup != null)
            {
                ResetGuidelineSet(_drawGroup);
            }

            if (context.IncludeRuntime)
            {
                if (_drawGroup != null)
                {
                    // Add the element/object type...
                    SvgObject.SetType(_drawGroup, SvgObjectType.Text);

                    // Add title for tooltips, if any...
                    SvgTitleElement titleElement = _svgElement.SelectSingleNode("title") as SvgTitleElement;
                    if (titleElement != null)
                    {
                        string titleValue = titleElement.InnerText;
                        if (!string.IsNullOrWhiteSpace(titleValue))
                        {
                            SvgObject.SetTitle(_drawGroup, titleValue);
                        }
                    }
                }
            }

            if (!_isGroupAdded)
            {
                if (_drawGroup != null)
                {
                    if (_isTextPath || _drawGroup.Transform != null || _drawGroup.ClipGeometry != null)
                    {
                        DrawingGroup curGroup = _context.Peek();
                        Debug.Assert(curGroup != null);
                        if (curGroup != null)
                        {
                            curGroup.Children.Add(_drawGroup);
                        }
                    }
                    else if (_drawGroup.Children.Count != 0)
                    {
                        DrawingGroup firstGroup = _drawGroup.Children[0] as DrawingGroup;
                        if (firstGroup != null && firstGroup.Children.Count != 0)
                        {
                            //Drawing firstDrawing = firstGroup.Children[0];

                            DrawingGroup curGroup = _context.Peek();
                            Debug.Assert(curGroup != null);
                            if (curGroup != null)
                            {
                                curGroup.Children.Add(_drawGroup);
                            }
                        }
                    }
                }
            }
            else
            {
                if (_drawGroup != null)
                {
                    DrawingGroup currentGroup = context.Peek();

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

                    context.Pop();
                }
            }

            _context   = null;
            _drawGroup = null;

            base.AfterRender(renderer);
        }
        private Drawing PerformHitTest(Rect rect, IntersectionDetail detail)
        {
            if (_svgDrawing == null)
            {
                return(null);
            }

            var rectDisplay = _displayTransform.TransformBounds(rect);
            var geomDisplay = new RectangleGeometry(rectDisplay);

            DrawingGroup    groupDrawing    = null;
            GlyphRunDrawing glyRunDrawing   = null;
            GeometryDrawing geometryDrawing = null;

            Drawing foundDrawing = null;

            DrawingCollection drawings = _svgDrawing.Children;

            for (int i = drawings.Count - 1; i >= 0; i--)
            {
                Drawing drawing = drawings[i];
                if (TryCast.Cast(drawing, out geometryDrawing))
                {
                    if (HitTestDrawing(geometryDrawing, geomDisplay, detail))
                    {
                        string uniqueId = SvgObject.GetUniqueId(drawing);
                        if (!string.IsNullOrWhiteSpace(uniqueId))
                        {
                            foundDrawing = drawing;
                            break;
                        }
                    }
                }
                else if (TryCast.Cast(drawing, out groupDrawing))
                {
                    if (SvgObject.GetType(groupDrawing) == SvgObjectType.Text)
                    {
                        var textBounds = new RectangleGeometry(groupDrawing.Bounds);
                        if (textBounds.FillContainsWithDetail(geomDisplay) == detail)
                        {
                            string uniqueId = SvgObject.GetUniqueId(drawing);
                            if (!string.IsNullOrWhiteSpace(uniqueId))
                            {
                                foundDrawing = drawing;
                                break;
                            }
                        }
                    }
                    if (HitTestDrawing(groupDrawing, geomDisplay, out foundDrawing, detail))
                    {
                        string uniqueId = SvgObject.GetUniqueId(drawing);
                        if (!string.IsNullOrWhiteSpace(uniqueId))
                        {
                            foundDrawing = drawing;
                            break;
                        }
                    }
                }
                else if (TryCast.Cast(drawing, out glyRunDrawing))
                {
                    if (HitTestDrawing(glyRunDrawing, geomDisplay, detail))
                    {
                        foundDrawing = drawing;
                        break;
                    }
                }
            }

            return(foundDrawing);
        }
        public override void Render(WpfDrawingRenderer renderer)
        {
            WpfDrawingContext context      = renderer.Context;
            SvgImageElement   imageElement = (SvgImageElement)_svgElement;

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

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

            ImageSource imageSource = null;

            if (imageElement.IsSvgImage)
            {
                if (imageElement.IsRootReferenced(imageElement.OwnerDocument.BaseURI))
                {
                    return;
                }

                SvgWindow wnd = GetSvgWindow();
                if (wnd == null)
                {
                    return;
                }
                //_embeddedRenderer.BackColor = Color.Empty;
                _embeddedRenderer.Render(wnd.Document);

                DrawingGroup imageGroup = _embeddedRenderer.Drawing as DrawingGroup;
                if (imageGroup != null &&
                    (imageGroup.Children != null && imageGroup.Children.Count == 1))
                {
                    DrawingGroup imageDrawing = imageGroup.Children[0] as DrawingGroup;
                    if (imageDrawing != null)
                    {
                        imageDrawing.ClipGeometry = null;

                        imageSource = new DrawingImage(imageDrawing);
                    }
                    else
                    {
                        imageGroup.ClipGeometry = null;

                        imageSource = new DrawingImage(imageGroup);
                    }
                }
                else
                {
                    imageSource = new DrawingImage(_embeddedRenderer.Drawing);
                }

                if (_embeddedRenderer != null)
                {
                    _embeddedRenderer.Dispose();
                    _embeddedRenderer = null;
                }
            }
            else
            {
                imageSource = GetBitmapSource(imageElement, context);
            }

            if (imageSource == null)
            {
                return;
            }

            //TODO--PAUL: Set the DecodePixelWidth/DecodePixelHeight?

            // Freeze the DrawingImage for performance benefits.
            //imageSource.Freeze();

            DrawingGroup drawGroup = null;

            ISvgAnimatedPreserveAspectRatio animatedAspectRatio = imageElement.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)
                {
                    double imageWidth  = imageSource.Width;
                    double imageHeight = imageSource.Height;

                    double viewWidth  = destRect.Width;
                    double viewHeight = destRect.Height;

                    SvgMeetOrSlice meetOrSlice = aspectRatio.MeetOrSlice;
                    if (meetOrSlice == SvgMeetOrSlice.Meet)
                    {
                        if (imageWidth <= viewWidth && imageHeight <= viewHeight)
                        {
                            if (this.Transform == null)
                            {
                                if (!aspectRatio.IsDefaultAlign) // Cacxa
                                {
                                    destRect = this.GetBounds(destRect, new Size(imageWidth, imageHeight), aspectRatioType);
                                }
                                else
                                {
                                    Transform viewTransform = this.GetAspectRatioTransform(aspectRatio,
                                                                                           new SvgRect(0, 0, imageWidth, imageHeight),
                                                                                           new SvgRect(destRect.X, destRect.Y, destRect.Width, destRect.Height));

                                    if (viewTransform != null)
                                    {
                                        drawGroup           = new DrawingGroup();
                                        drawGroup.Transform = viewTransform;

                                        DrawingGroup lastGroup = context.Peek();
                                        Debug.Assert(lastGroup != null);

                                        if (lastGroup != null)
                                        {
                                            lastGroup.Children.Add(drawGroup);
                                        }

                                        destRect = this.GetBounds(destRect,
                                                                  new Size(imageWidth, imageHeight), aspectRatioType);

                                        // The origin is already handled by the view transform...
                                        destRect.X = 0;
                                        destRect.Y = 0;
                                    }
                                }
                            }
                            else
                            {
                                destRect = new Rect(0, 0, viewWidth, viewHeight);
                            }
                        }
                        else
                        {
                            if (this.Transform == null)
                            {
                                Transform viewTransform = this.GetAspectRatioTransform(aspectRatio,
                                                                                       new SvgRect(0, 0, imageWidth, imageHeight),
                                                                                       new SvgRect(destRect.X, destRect.Y, destRect.Width, destRect.Height));

                                if (viewTransform != null)
                                {
                                    drawGroup           = new DrawingGroup();
                                    drawGroup.Transform = viewTransform;

                                    DrawingGroup lastGroup = context.Peek();
                                    Debug.Assert(lastGroup != null);

                                    if (lastGroup != null)
                                    {
                                        lastGroup.Children.Add(drawGroup);
                                    }

                                    destRect = this.GetBounds(destRect,
                                                              new Size(imageWidth, imageHeight), aspectRatioType);

                                    // The origin is already handled by the view transform...
                                    destRect.X = 0;
                                    destRect.Y = 0;
                                }
                            }
                        }
                    }
                    else if (meetOrSlice == SvgMeetOrSlice.Slice)
                    {
                        var       fScaleX       = viewWidth / imageWidth;
                        var       fScaleY       = viewHeight / imageHeight;
                        Transform viewTransform = this.GetAspectRatioTransform(aspectRatio,
                                                                               new SvgRect(0, 0, imageWidth, imageHeight),
                                                                               new SvgRect(destRect.X, destRect.Y, destRect.Width, destRect.Height));

                        DrawingGroup sliceGroup = new DrawingGroup();
                        sliceGroup.ClipGeometry = new RectangleGeometry(clipRect);

                        DrawingGroup lastGroup = context.Peek();
                        Debug.Assert(lastGroup != null);

                        if (lastGroup != null)
                        {
                            lastGroup.Children.Add(sliceGroup);
                        }

                        if (viewTransform != null)
                        {
                            drawGroup           = new DrawingGroup();
                            drawGroup.Transform = viewTransform;

                            sliceGroup.Children.Add(drawGroup);

                            destRect = this.GetBounds(destRect,
                                                      new Size(imageWidth, imageHeight), aspectRatioType);

                            // The origin is already handled by the view transform...
                            destRect.X = 0;
                            destRect.Y = 0;
                        }
                        else
                        {
                            drawGroup = sliceGroup;
                        }
                    }
                }
            }

            ImageDrawing drawing = new ImageDrawing(imageSource, destRect);

            float opacityValue = -1;

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

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

            Geometry  clipGeom  = this.ClipGeometry;
            Transform transform = this.Transform;

            bool ownedGroup = true;

            if (drawGroup == null)
            {
                drawGroup  = context.Peek();
                ownedGroup = false;
            }

            Debug.Assert(drawGroup != null);
            if (drawGroup != null)
            {
                if ((opacityValue >= 0 && opacityValue < 1) || (clipGeom != null && !clipGeom.IsEmpty()) ||
                    (transform != null && !transform.Value.IsIdentity))
                {
                    DrawingGroup clipGroup = ownedGroup ? drawGroup : new DrawingGroup();
                    if (opacityValue >= 0 && opacityValue < 1)
                    {
                        clipGroup.Opacity = opacityValue;
                    }
                    if (clipGeom != null)
                    {
                        SvgUnitType clipUnits = this.ClipUnits;
                        if (clipUnits == SvgUnitType.ObjectBoundingBox)
                        {
                            Rect drawingBounds = drawing.Bounds;

                            TransformGroup transformGroup = new TransformGroup();

                            // Scale the clip region (at (0, 0)) and translate to the top-left corner of the target.
                            transformGroup.Children.Add(
                                new ScaleTransform(drawingBounds.Width, drawingBounds.Height));
                            transformGroup.Children.Add(
                                new TranslateTransform(drawingBounds.X, drawingBounds.Y));

                            clipGeom.Transform = transformGroup;
                        }

                        clipGroup.ClipGeometry = clipGeom;
                    }
                    if (transform != null)
                    {
                        Transform curTransform = clipGroup.Transform;
                        if (curTransform != null && curTransform.Value.IsIdentity == false)
                        {
                            TransformGroup transformGroup = new TransformGroup();
                            transformGroup.Children.Add(curTransform);
                            transformGroup.Children.Add(transform);
                            clipGroup.Transform = transformGroup;
                        }
                        else
                        {
                            clipGroup.Transform = transform;
                        }
                    }

                    clipGroup.Children.Add(drawing);
                    if (!ownedGroup)
                    {
                        drawGroup.Children.Add(clipGroup);
                    }
                }
                else
                {
                    drawGroup.Children.Add(drawing);
                }

                string elementId = this.GetElementName();
                if (ownedGroup)
                {
                    string sVisibility = imageElement.GetPropertyValue("visibility");
                    string sDisplay    = imageElement.GetPropertyValue("display");
                    if (string.Equals(sVisibility, "hidden") || string.Equals(sDisplay, "none"))
                    {
                        drawGroup.Opacity = 0;
                    }

                    if (!_idAssigned && !string.IsNullOrWhiteSpace(elementId) && !context.IsRegisteredId(elementId))
                    {
                        context.RegisterId(elementId);

                        if (context.IncludeRuntime)
                        {
                            SvgObject.SetName(drawGroup, elementId);

                            SvgObject.SetId(drawGroup, elementId);
                        }
                    }

                    // Register this drawing with the Drawing-Document...
                    this.Rendered(drawGroup);
                }
                else if (!_idAssigned)
                {
                    if (!_idAssigned && !string.IsNullOrWhiteSpace(elementId) && !context.IsRegisteredId(elementId))
                    {
                        context.RegisterId(elementId);

                        if (context.IncludeRuntime)
                        {
                            SvgObject.SetName(imageSource, elementId);

                            SvgObject.SetId(imageSource, elementId);
                        }
                    }

                    // Register this drawing with the Drawing-Document...
                    this.Rendered(drawing);
                }
            }
        }
Beispiel #30
0
        public override void Render(WpfDrawingRenderer renderer)
        {
            _isAggregated = false;

            if (_isLayer)
            {
                base.Render(renderer);

                return;
            }

            WpfDrawingContext context = renderer.Context;

            Geometry  clipGeom  = this.ClipGeometry;
            Transform transform = this.Transform;

            float opacityValue = -1;

            SvgAElement element = (SvgAElement)_svgElement;
            string      opacity = element.GetPropertyValue("opacity");

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

            WpfLinkVisitor linkVisitor = context.LinkVisitor;

            if (linkVisitor != null || clipGeom != null || transform != null || opacityValue >= 0)
            {
                _drawGroup = new DrawingGroup();

                string elementId = this.GetElementName();
                if (!string.IsNullOrWhiteSpace(elementId) && !context.IsRegisteredId(elementId))
                {
                    _drawGroup.SetValue(FrameworkElement.NameProperty, elementId);

                    context.RegisterId(elementId);

                    if (context.IncludeRuntime)
                    {
                        SvgObject.SetId(_drawGroup, elementId);
                    }
                }

                string elementClass = this.GetElementClass();
                if (!string.IsNullOrWhiteSpace(elementClass) && context.IncludeRuntime)
                {
                    SvgObject.SetClass(_drawGroup, elementClass);
                }

                DrawingGroup currentGroup = context.Peek();

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

                if (linkVisitor != null && linkVisitor.Aggregates && context.Links != null)
                {
                    if (!linkVisitor.Exists(elementId))
                    {
                        context.Links.Children.Add(_drawGroup);
                    }
                }
                else
                {
                    currentGroup.Children.Add(_drawGroup);
                }

                context.Push(_drawGroup);

                if (clipGeom != null)
                {
                    _drawGroup.ClipGeometry = clipGeom;
                }

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

                if (opacityValue >= 0)
                {
                    _drawGroup.Opacity = opacityValue;
                }

                string sVisibility = element.GetPropertyValue("visibility");
                string sDisplay    = element.GetPropertyValue("display");
                if (string.Equals(sVisibility, "hidden") || string.Equals(sDisplay, "none"))
                {
                    opacityValue       = 0;
                    _drawGroup.Opacity = 0;
                }

                if (linkVisitor != null)
                {
                    linkVisitor.Visit(_drawGroup, element, context, opacityValue);

                    _isAggregated = linkVisitor.IsAggregate;
                }
            }

            base.Render(renderer);
        }