예제 #1
0
        protected void SetClip(WpfDrawingContext context)
        {
            _clipPathUnits = SvgUnitType.UserSpaceOnUse;

            if (_svgElement == null)
            {
                return;
            }

            #region Clip with clip

            // see http://www.w3.org/TR/SVG/masking.html#OverflowAndClipProperties
            if (_svgElement is ISvgSvgElement || _svgElement is ISvgMarkerElement ||
                _svgElement is ISvgSymbolElement || _svgElement is ISvgPatternElement)
            {
                // check overflow property
                CssValue overflow = _svgElement.GetComputedCssValue("overflow", string.Empty) as CssValue;
                // TODO: clip can have "rect(10 10 auto 10)"
                CssPrimitiveValue clip = _svgElement.GetComputedCssValue("clip", string.Empty) as CssPrimitiveValue;

                string sOverflow = null;

                if (overflow != null && !string.IsNullOrWhiteSpace(overflow.CssText))
                {
                    sOverflow = overflow.CssText;
                }
                else
                {
                    if (this is ISvgSvgElement)
                    {
                        sOverflow = "hidden";
                    }
                }

                if (sOverflow != null)
                {
                    // "If the 'overflow' property has a value other than hidden or scroll,
                    // the property has no effect (i.e., a clipping rectangle is not created)."
                    if (sOverflow == "hidden" || sOverflow == "scroll")
                    {
                        Rect clipRect = Rect.Empty;
                        if (clip != null && clip.PrimitiveType == CssPrimitiveType.Rect)
                        {
                            if (_svgElement is ISvgSvgElement)
                            {
                                ISvgSvgElement svgElement = (ISvgSvgElement)_svgElement;
                                SvgRect        viewPort   = svgElement.Viewport as SvgRect;
                                clipRect = WpfConvert.ToRect(viewPort);
                                ICssRect clipShape = (CssRect)clip.GetRectValue();
                                if (clipShape.Top.PrimitiveType != CssPrimitiveType.Ident)
                                {
                                    clipRect.Y += clipShape.Top.GetFloatValue(CssPrimitiveType.Number);
                                }
                                if (clipShape.Left.PrimitiveType != CssPrimitiveType.Ident)
                                {
                                    clipRect.X += clipShape.Left.GetFloatValue(CssPrimitiveType.Number);
                                }
                                if (clipShape.Right.PrimitiveType != CssPrimitiveType.Ident)
                                {
                                    clipRect.Width = (clipRect.Right - clipRect.X) - clipShape.Right.GetFloatValue(CssPrimitiveType.Number);
                                }
                                if (clipShape.Bottom.PrimitiveType != CssPrimitiveType.Ident)
                                {
                                    clipRect.Height = (clipRect.Bottom - clipRect.Y) - clipShape.Bottom.GetFloatValue(CssPrimitiveType.Number);
                                }
                            }
                        }
                        else if (clip == null || (clip.PrimitiveType == CssPrimitiveType.Ident && clip.GetStringValue() == "auto"))
                        {
                            if (_svgElement is ISvgSvgElement)
                            {
                                ISvgSvgElement svgElement = (ISvgSvgElement)_svgElement;
                                SvgRect        viewPort   = svgElement.Viewport as SvgRect;
                                clipRect = WpfConvert.ToRect(viewPort);
                            }
                            else if (_svgElement is ISvgMarkerElement ||
                                     _svgElement is ISvgSymbolElement ||
                                     _svgElement is ISvgPatternElement)
                            {
                                // TODO: what to do here?
                            }
                        }
                        if (clipRect != Rect.Empty)
                        {
                            _clipGeometry = new RectangleGeometry(clipRect);
                            //gr.SetClip(clipRect);
                        }
                    }
                }
            }
            #endregion

            #region Clip with clip-path

            SvgRenderingHint hint = _svgElement.RenderingHint;

            if (hint == SvgRenderingHint.Image)
            {
            }

            // see: http://www.w3.org/TR/SVG/masking.html#EstablishingANewClippingPath

            if (hint == SvgRenderingHint.Shape || hint == SvgRenderingHint.Text ||
                hint == SvgRenderingHint.Clipping || hint == SvgRenderingHint.Masking ||
                hint == SvgRenderingHint.Containment || hint == SvgRenderingHint.Image)
            {
                CssPrimitiveValue clipPath = _svgElement.GetComputedCssValue("clip-path", string.Empty) as CssPrimitiveValue;

                if (clipPath != null && clipPath.PrimitiveType == CssPrimitiveType.Uri)
                {
                    string absoluteUri = _svgElement.ResolveUri(clipPath.GetStringValue());

                    SvgClipPathElement eClipPath = _svgElement.OwnerDocument.GetNodeByUri(absoluteUri) as SvgClipPathElement;

                    if (eClipPath != null)
                    {
                        GeometryCollection geomColl = CreateClippingRegion(eClipPath, context);
                        if (geomColl == null || geomColl.Count == 0)
                        {
                            return;
                        }
                        Geometry gpClip    = geomColl[0];
                        int      geomCount = geomColl.Count;
                        if (geomCount > 1)
                        {
                            //GeometryGroup clipGroup = new GeometryGroup();
                            //clipGroup.Children.Add(gpClip);
                            for (int k = 1; k < geomCount; k++)
                            {
                                gpClip = Geometry.Combine(gpClip, geomColl[k],
                                                          GeometryCombineMode.Union, null);
                                //clipGroup.Children.Add(geomColl[k]);
                            }

                            //clipGroup.Children.Reverse();

                            //gpClip = clipGroup;
                        }

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

                        _clipPathUnits = (SvgUnitType)eClipPath.ClipPathUnits.AnimVal;

                        //if (_clipPathUnits == SvgUnitType.ObjectBoundingBox)
                        //{
                        //    SvgTransformableElement transElement = _svgElement as SvgTransformableElement;

                        //    if (transElement != null)
                        //    {
                        //        ISvgRect bbox = transElement.GetBBox();

                        //        // scale clipping path
                        //        gpClip.Transform = new ScaleTransform(bbox.Width, bbox.Height);
                        //        //gr.SetClip(gpClip);

                        //        // offset clip
                        //        //TODO--PAUL gr.TranslateClip((float)bbox.X, (float)bbox.Y);

                        //        _clipGeometry = gpClip;
                        //    }
                        //    else
                        //    {
                        //        throw new NotImplementedException("clip-path with SvgUnitType.ObjectBoundingBox "
                        //          + "not supported for this type of element: " + _svgElement.GetType());
                        //    }
                        //}
                        //else
                        {
                            //gr.SetClip(gpClip);

                            _clipGeometry = gpClip;
                        }
                    }
                }
            }

            #endregion
        }
예제 #2
0
        public void RenderMarker0(WpfDrawingRenderer renderer, WpfDrawingContext gr,
                                  SvgMarkerPosition markerPos, SvgStyleableElement refElement)
        {
            //PathGeometry g;
            //g.GetPointAtFractionLength(

            ISharpMarkerHost markerHostElm = (ISharpMarkerHost)refElement;
            SvgMarkerElement markerElm     = (SvgMarkerElement)_svgElement;

            SvgPointF[] vertexPositions = markerHostElm.MarkerPositions;
            int         start;
            int         len;

            // Choose which part of the position array to use
            switch (markerPos)
            {
            case SvgMarkerPosition.Start:
                start = 0;
                len   = 1;
                break;

            case SvgMarkerPosition.Mid:
                start = 1;
                len   = vertexPositions.Length - 2;
                break;

            default:
                // == MarkerPosition.End
                start = vertexPositions.Length - 1;
                len   = 1;
                break;
            }

            for (int i = start; i < start + len; i++)
            {
                SvgPointF point = vertexPositions[i];

                Matrix m = GetTransformMatrix(_svgElement);

                //GraphicsContainer gc = gr.BeginContainer();

                this.BeforeRender(renderer);

                //gr.TranslateTransform(point.X, point.Y);

                //PAUL:
                //m.Translate(point.X, point.Y);

                if (markerElm.OrientType.AnimVal.Equals((ushort)SvgMarkerOrient.Angle))
                {
                    m.Rotate(markerElm.OrientAngle.AnimVal.Value);
                    //gr.RotateTransform((double)markerElm.OrientAngle.AnimVal.Value);
                }
                else
                {
                    double angle;

                    switch (markerPos)
                    {
                    case SvgMarkerPosition.Start:
                        angle = markerHostElm.GetStartAngle(i + 1);
                        break;

                    case SvgMarkerPosition.Mid:
                        //angle = (markerHostElm.GetEndAngle(i) + markerHostElm.GetStartAngle(i + 1)) / 2;
                        angle = SvgNumber.CalcAngleBisection(markerHostElm.GetEndAngle(i), markerHostElm.GetStartAngle(i + 1));
                        break;

                    default:
                        angle = markerHostElm.GetEndAngle(i);
                        break;
                    }
                    //gr.RotateTransform(angle);
                    m.Rotate(angle);
                }

                if (markerElm.MarkerUnits.AnimVal.Equals((ushort)SvgMarkerUnit.StrokeWidth))
                {
                    string propValue = refElement.GetPropertyValue("stroke-width");
                    if (propValue.Length == 0)
                    {
                        propValue = "1";
                    }

                    SvgLength strokeWidthLength = new SvgLength("stroke-width", propValue, refElement, SvgLengthDirection.Viewport);
                    double    strokeWidth       = strokeWidthLength.Value;
                    //gr.ScaleTransform(strokeWidth, strokeWidth);
                    m.Scale(strokeWidth, strokeWidth);
                }

                SvgPreserveAspectRatio spar = (SvgPreserveAspectRatio)markerElm.PreserveAspectRatio.AnimVal;
                double[] translateAndScale  = spar.FitToViewBox(
                    (SvgRect)markerElm.ViewBox.AnimVal, new SvgRect(0, 0,
                                                                    markerElm.MarkerWidth.AnimVal.Value, markerElm.MarkerHeight.AnimVal.Value));


                //PAUL:
                //m.Translate(-(double)markerElm.RefX.AnimVal.Value * translateAndScale[2], -(double)markerElm.RefY.AnimVal.Value * translateAndScale[3]);

                //PAUL:
                m.Scale(translateAndScale[2], translateAndScale[3]);
                m.Translate(point.X, point.Y);

                //Matrix oldTransform = TransformMatrix;
                //TransformMatrix = m;
                //try
                //{
                //newTransform.Append(m);
                //TransformGroup tg = new TransformGroup();

                //renderer.Canvas.re

                //gr.TranslateTransform(
                //    -(double)markerElm.RefX.AnimVal.Value * translateAndScale[2],
                //    -(double)markerElm.RefY.AnimVal.Value * translateAndScale[3]
                //    );

                //gr.ScaleTransform(translateAndScale[2], translateAndScale[3]);

                renderer.RenderChildren(markerElm);
                //                markerElm.RenderChildren(renderer);
                //}
                //finally
                //{
                //    TransformMatrix = oldTransform;
                //}
                //    //gr.EndContainer(gc);

                _matrix = m;
                this.Render(renderer);

                //gr.EndContainer(gc);

                this.AfterRender(renderer);
            }
        }
예제 #3
0
        protected static void RenderMarkers(WpfDrawingRenderer renderer,
                                            SvgStyleableElement styleElm, WpfDrawingContext gr)
        {
            // OPTIMIZE
            if (styleElm is ISharpMarkerHost)
            {
                string markerStartUrl  = ExtractMarkerUrl(styleElm.GetPropertyValue("marker-start", "marker"));
                string markerMiddleUrl = ExtractMarkerUrl(styleElm.GetPropertyValue("marker-mid", "marker"));
                string markerEndUrl    = ExtractMarkerUrl(styleElm.GetPropertyValue("marker-end", "marker"));
                string markerAll       = ExtractMarkerUrl(styleElm.GetPropertyValue("marker", "marker"));

                //  The SVG specification defines three properties to reference markers: marker-start,
                // marker -mid, marker-end. It also provides a shorthand property,marker. Using the marker
                // property from a style sheet is equivalent to using all three (start, mid, end).
                // However, shorthand properties cannot be used as presentation attributes.
                if (!string.IsNullOrWhiteSpace(markerAll) && !IsPresentationMarker(styleElm))
                {
                    if (string.IsNullOrWhiteSpace(markerStartUrl))
                    {
                        markerStartUrl = markerAll;
                    }
                    if (string.IsNullOrWhiteSpace(markerMiddleUrl))
                    {
                        markerMiddleUrl = markerAll;
                    }
                    if (string.IsNullOrWhiteSpace(markerEndUrl))
                    {
                        markerEndUrl = markerAll;
                    }
                }

                if (markerStartUrl.Length > 0)
                {
                    WpfMarkerRendering markerRenderer = CreateByUri(styleElm.OwnerDocument,
                                                                    styleElm.BaseURI, markerStartUrl) as WpfMarkerRendering;
                    if (markerRenderer != null)
                    {
                        markerRenderer.RenderMarker(renderer, gr, SvgMarkerPosition.Start, styleElm);
                    }
                }

                if (markerMiddleUrl.Length > 0)
                {
                    // TODO markerMiddleUrl != markerStartUrl
                    WpfMarkerRendering markerRenderer = CreateByUri(styleElm.OwnerDocument,
                                                                    styleElm.BaseURI, markerMiddleUrl) as WpfMarkerRendering;
                    if (markerRenderer != null)
                    {
                        markerRenderer.RenderMarker(renderer, gr, SvgMarkerPosition.Mid, styleElm);
                    }
                }

                if (markerEndUrl.Length > 0)
                {
                    // TODO: markerEndUrl != markerMiddleUrl
                    WpfMarkerRendering markerRenderer = CreateByUri(styleElm.OwnerDocument,
                                                                    styleElm.BaseURI, markerEndUrl) as WpfMarkerRendering;
                    if (markerRenderer != null)
                    {
                        markerRenderer.RenderMarker(renderer, gr, SvgMarkerPosition.End, styleElm);
                    }
                }
            }
        }
        private BitmapSource GetBitmap(SvgImageElement element, WpfDrawingContext context)
        {
            if (element.IsSvgImage)
            {
                return(null);
            }

            if (!element.Href.AnimVal.StartsWith("data:"))
            {
                SvgUriReference svgUri      = element.UriReference;
                string          absoluteUri = svgUri.AbsoluteUri;
                if (String.IsNullOrEmpty(absoluteUri))
                {
                    return(null); // most likely, the image does not exist...
                }

                Uri imageUri = new Uri(svgUri.AbsoluteUri);
                if (imageUri.IsFile)
                {
                    if (File.Exists(imageUri.LocalPath))
                    {
                        BitmapImage imageSource = new BitmapImage();

                        imageSource.BeginInit();
                        imageSource.CacheOption   = BitmapCacheOption.OnLoad;
                        imageSource.CreateOptions = BitmapCreateOptions.IgnoreImageCache
                                                    | BitmapCreateOptions.PreservePixelFormat;
                        imageSource.UriSource = imageUri;
                        imageSource.EndInit();

                        return(imageSource);
                    }

                    return(null);
                }
                else
                {
                    Stream stream = svgUri.ReferencedResource.GetResponseStream();

                    BitmapImage imageSource = new BitmapImage();
                    imageSource.BeginInit();
                    imageSource.CacheOption   = BitmapCacheOption.OnLoad;
                    imageSource.CreateOptions = BitmapCreateOptions.IgnoreImageCache
                                                | BitmapCreateOptions.PreservePixelFormat;
                    imageSource.StreamSource = stream;
                    imageSource.EndInit();

                    return(imageSource);
                }
            }
            else
            {
                WpfEmbeddedImageVisitor imageVisitor = context.ImageVisitor;
                if (imageVisitor != null)
                {
                    BitmapSource visitorSource = imageVisitor.Visit(element, context);
                    if (visitorSource != null)
                    {
                        return(visitorSource);
                    }
                }

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

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

                string sContent = sURI.Substring(nComma + 1);
                byte[] bResult  = Convert.FromBase64CharArray(sContent.ToCharArray(),
                                                              0, sContent.Length);

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

                return(imageSource);
            }
        }
예제 #5
0
        public override void Render(WpfDrawingRenderer renderer)
        {
            WpfDrawingContext context = renderer.Context;

            SvgRenderingHint hint = _svgElement.RenderingHint;

            if (hint != SvgRenderingHint.Shape || 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;
            }

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

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

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

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

                Brush brush = fillPaint.GetBrush(geometry);

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

                if (brush != null || pen != null)
                {
                    Transform transform = this.Transform;
                    if (transform != null && !transform.Value.IsIdentity)
                    {
                        geometry.Transform = transform;
                        if (brush != null)
                        {
                            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);

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

                        context.RegisterId(elementId);

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

                    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)
                        {
                            SvgUnitType maskUnits = this.MaskUnits;
                            if (maskUnits == 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));

                                DrawingGroup maskGroup = ((DrawingBrush)maskBrush).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 (transformGroup != null)
                                //{
                                //    drawingBounds = transformGroup.TransformBounds(drawingBounds);
                                //}

                                //maskBrush.Viewbox = drawingBounds;
                                //maskBrush.ViewboxUnits = BrushMappingMode.Absolute;

                                //maskBrush.Stretch = Stretch.Uniform;

                                //maskBrush.Viewport = drawingBounds;
                                //maskBrush.ViewportUnits = BrushMappingMode.Absolute;

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

                            clipMaskGroup.OpacityMask = maskBrush;
                        }

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

            RenderMarkers(renderer, styleElm, context);
        }
예제 #6
0
        protected void SetTransform(WpfDrawingContext context)
        {
            _transformMatrix = null;

            ISvgTransformable transElm = _svgElement as ISvgTransformable;

            if (transElm != null)
            {
                SvgTransformList transformList = (SvgTransformList)transElm.Transform.AnimVal;
                if (transformList.NumberOfItems > 1 && _combineTransforms == false)
                {
                    TransformGroup   transformGroup = new TransformGroup();
                    List <Transform> transforms     = new List <Transform>();

                    for (uint i = 0; i < transformList.NumberOfItems; i++)
                    {
                        ISvgTransform transform = transformList.GetItem(i);
                        double[]      values    = transform.InputValues;
                        switch (transform.TransformType)
                        {
                        case SvgTransformType.Translate:
                            if (values.Length == 1)
                            {
                                // SetTranslate(values[0], 0);
                                //transformGroup.Children.Add(new TranslateTransform(values[0], 0));
                                transforms.Add(new TranslateTransform(values[0], 0));
                            }
                            else if (values.Length == 2)
                            {
                                // SetTranslate(values[0], values[1]);
                                //transformGroup.Children.Add(new TranslateTransform(values[0], values[1]));
                                transforms.Add(new TranslateTransform(values[0], values[1]));
                            }
                            break;

                        case SvgTransformType.Rotate:
                            if (values.Length == 1)
                            {
                                // SetRotate(values[0]);
                                //transformGroup.Children.Add(new RotateTransform(values[0]));
                                transforms.Add(new RotateTransform(values[0]));
                            }
                            else if (values.Length == 3)
                            {
                                // SetRotate(values[0], values[1], values[2]);
                                //transformGroup.Children.Add(new RotateTransform(values[0], values[1], values[2]));
                                transforms.Add(new RotateTransform(values[0], values[1], values[2]));
                            }
                            break;

                        case SvgTransformType.Scale:
                            if (values.Length == 1)
                            {
                                //SetScale(values[0], values[0]);
                                transformGroup.Children.Add(new ScaleTransform(values[0], values[0]));
                            }
                            else if (values.Length == 2)
                            {
                                //SetScale(values[0], values[1]);
                                //transformGroup.Children.Add(new ScaleTransform(values[0], values[1]));
                                transforms.Add(new ScaleTransform(values[0], values[1]));
                            }
                            break;

                        case SvgTransformType.SkewX:
                            if (values.Length == 1)
                            {
                                //SetSkewX(values[0]);
                                //transformGroup.Children.Add(new SkewTransform(values[0], 0));
                                transforms.Add(new SkewTransform(values[0], 0));
                            }
                            break;

                        case SvgTransformType.SkewY:
                            if (values.Length == 1)
                            {
                                //SetSkewY(values[0]);
                                //transformGroup.Children.Add(new SkewTransform(0, values[0]));
                                transforms.Add(new SkewTransform(0, values[0]));
                            }
                            break;

                        case SvgTransformType.Matrix:
                            if (values.Length == 6)
                            {
                                //SetMatrix(new SvgMatrix(values[0], values[1], values[2], values[3], values[4], values[5]));
                                //transformGroup.Children.Add(new MatrixTransform(values[0], values[1], values[2], values[3], values[4], values[5]));
                                transforms.Add(new MatrixTransform(values[0], values[1], values[2], values[3], values[4], values[5]));
                            }
                            break;
                        }
                    }

                    transforms.Reverse();
                    transformGroup.Children = new TransformCollection(transforms);
                    _transformMatrix        = transformGroup;
                    //_transformMatrix = new MatrixTransform(transformGroup.Value);
                    return;
                }
                SvgMatrix svgMatrix = transformList.TotalMatrix;

                if (svgMatrix.IsIdentity)
                {
                    return;
                }

                _transformMatrix = new MatrixTransform(Math.Round(svgMatrix.A, 4), Math.Round(svgMatrix.B, 4),
                                                       Math.Round(svgMatrix.C, 4), Math.Round(svgMatrix.D, 4),
                                                       Math.Round(svgMatrix.E, 4), Math.Round(svgMatrix.F, 4));
            }
        }
예제 #7
0
        private GeometryCollection CreateClippingRegion(SvgClipPathElement clipPath,
                                                        WpfDrawingContext context)
        {
            GeometryCollection geomColl = new GeometryCollection();

            foreach (XmlNode node in clipPath.ChildNodes)
            {
                if (node.NodeType != XmlNodeType.Element)
                {
                    continue;
                }

                // Handle a case where the clip element has "use" element as a child...
                if (string.Equals(node.LocalName, "use"))
                {
                    SvgUseElement useElement = (SvgUseElement)node;

                    XmlElement refEl = useElement.ReferencedElement;
                    if (refEl != null)
                    {
                        XmlElement refElParent = (XmlElement)refEl.ParentNode;
                        useElement.OwnerDocument.Static = true;
                        useElement.CopyToReferencedElement(refEl);
                        refElParent.RemoveChild(refEl);
                        useElement.AppendChild(refEl);

                        foreach (XmlNode useChild in useElement.ChildNodes)
                        {
                            if (useChild.NodeType != XmlNodeType.Element)
                            {
                                continue;
                            }

                            SvgStyleableElement element = useChild as SvgStyleableElement;
                            if (element != null && element.RenderingHint == SvgRenderingHint.Shape)
                            {
                                Geometry childPath = CreateGeometry(element, context.OptimizePath);

                                if (childPath != null)
                                {
                                    geomColl.Add(childPath);
                                }
                            }
                        }

                        useElement.RemoveChild(refEl);
                        useElement.RestoreReferencedElement(refEl);
                        refElParent.AppendChild(refEl);
                        useElement.OwnerDocument.Static = false;
                    }
                }
                else
                {
                    SvgStyleableElement element = node as SvgStyleableElement;
                    if (element != null)
                    {
                        if (element.RenderingHint == SvgRenderingHint.Shape)
                        {
                            Geometry childPath = CreateGeometry(element, context.OptimizePath);

                            if (childPath != null)
                            {
                                geomColl.Add(childPath);
                            }
                        }
                        else if (element.RenderingHint == SvgRenderingHint.Text)
                        {
                            GeometryCollection textGeomColl = GetTextClippingRegion(element, context);
                            if (textGeomColl != null)
                            {
                                for (int i = 0; i < textGeomColl.Count; i++)
                                {
                                    geomColl.Add(textGeomColl[i]);
                                }
                            }
                        }
                    }
                }
            }

            return(geomColl);
        }
예제 #8
0
        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);
        }
예제 #9
0
        public override void BeforeRender(WpfDrawingRenderer renderer)
        {
            base.BeforeRender(renderer);

            WpfDrawingContext context = renderer.Context;

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

            SvgUseElement useElement = (SvgUseElement)_svgElement;

            string elementId = this.GetElementName();

            float opacityValue = -1;

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

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

            _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 || transform != null || (opacityValue >= 0 && opacityValue < 1) ||
                (!string.IsNullOrWhiteSpace(elementId) && !context.IsRegisteredId(elementId)))
            {
                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);
                    }
                }
            }
        }
예제 #10
0
 public abstract Brush GetBrush(WpfDrawingContext context);
예제 #11
0
        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;
            }

            var comparer = StringComparison.OrdinalIgnoreCase;

            // We do not directly render the contents of the clip-path, unless specifically requested...
            if (string.Equals(_svgElement.ParentNode.LocalName, "clipPath", comparer) &&
                !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", comparer) || string.Equals(sDisplay, "none", comparer))
            {
                _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);
        }
예제 #12
0
        public void RenderMarkerEx0(WpfDrawingRenderer renderer, WpfDrawingContext gr,
                                    SvgMarkerPosition markerPos, SvgStyleableElement refElement)
        {
            //ISharpMarkerHost markerHostElm = (ISharpMarkerHost)refElement;
            //SvgMarkerElement markerElm     = (SvgMarkerElement)element;

            //SvgPointF[] vertexPositions = markerHostElm.MarkerPositions;
            //int start;
            //int len;

            //// Choose which part of the position array to use
            //switch (markerPos)
            //{
            //    case SvgMarkerPosition.Start:
            //        start = 0;
            //        len   = 1;
            //        break;
            //    case SvgMarkerPosition.Mid:
            //        start = 1;
            //        len   = vertexPositions.Length - 2;
            //        break;
            //    default:
            //        // == MarkerPosition.End
            //        start = vertexPositions.Length - 1;
            //        len   = 1;
            //        break;
            //}

            //for (int i = start; i < start + len; i++)
            //{
            //    SvgPointF point = vertexPositions[i];

            //    GdiGraphicsContainer gc = gr.BeginContainer();

            //    gr.TranslateTransform(point.X, point.Y);

            //    if (markerElm.OrientType.AnimVal.Equals((ushort)SvgMarkerOrient.Angle))
            //    {
            //        gr.RotateTransform((float)markerElm.OrientAngle.AnimVal.Value);
            //    }
            //    else
            //    {
            //        float angle;

            //        switch (markerPos)
            //        {
            //            case SvgMarkerPosition.Start:
            //                angle = markerHostElm.GetStartAngle(i + 1);
            //                break;
            //            case SvgMarkerPosition.Mid:
            //                //angle = (markerHostElm.GetEndAngle(i) + markerHostElm.GetStartAngle(i + 1)) / 2;
            //                angle = SvgNumber.CalcAngleBisection(markerHostElm.GetEndAngle(i), markerHostElm.GetStartAngle(i + 1));
            //                break;
            //            default:
            //                angle = markerHostElm.GetEndAngle(i);
            //                break;
            //        }
            //        gr.RotateTransform(angle);
            //    }

            //    if (markerElm.MarkerUnits.AnimVal.Equals((ushort)SvgMarkerUnit.StrokeWidth))
            //    {
            //        SvgLength strokeWidthLength = new SvgLength(refElement,
            //            "stroke-width", SvgLengthSource.Css, SvgLengthDirection.Viewport, "1");
            //        float strokeWidth = (float)strokeWidthLength.Value;
            //        gr.ScaleTransform(strokeWidth, strokeWidth);
            //    }

            //    SvgPreserveAspectRatio spar =
            //        (SvgPreserveAspectRatio)markerElm.PreserveAspectRatio.AnimVal;
            //    float[] translateAndScale = spar.FitToViewBox((SvgRect)markerElm.ViewBox.AnimVal,
            //        new SvgRect(0, 0, markerElm.MarkerWidth.AnimVal.Value,
            //            markerElm.MarkerHeight.AnimVal.Value));


            //    gr.TranslateTransform(-(float)markerElm.RefX.AnimVal.Value * translateAndScale[2],
            //        -(float)markerElm.RefY.AnimVal.Value * translateAndScale[3]);

            //    gr.ScaleTransform(translateAndScale[2], translateAndScale[3]);

            //    Clip(gr);

            //    renderer.RenderChildren(markerElm);

            //    gr.EndContainer(gc);
            //}
        }
예제 #13
0
        public void RenderMarker2(WpfDrawingRenderer renderer, WpfDrawingContext gr,
                                  SvgMarkerPosition markerPos, SvgStyleableElement refElement)
        {
            ISharpMarkerHost markerHostElm = (ISharpMarkerHost)refElement;
            SvgMarkerElement markerElm     = (SvgMarkerElement)_svgElement;

            SvgPointF[] vertexPositions = markerHostElm.MarkerPositions;
            int         start;
            int         len;

            // Choose which part of the position array to use
            switch (markerPos)
            {
            case SvgMarkerPosition.Start:
                start = 0;
                len   = 1;
                break;

            case SvgMarkerPosition.Mid:
                start = 1;
                len   = vertexPositions.Length - 2;
                break;

            default:
                // == MarkerPosition.End
                start = vertexPositions.Length - 1;
                len   = 1;
                break;
            }

            for (int i = start; i < start + len; i++)
            {
                SvgPointF point = vertexPositions[i];

                //GdiGraphicsContainer gc = gr.BeginContainer();

                this.BeforeRender(renderer);

                //Matrix matrix = Matrix.Identity;

                Matrix matrix = GetTransformMatrix(_svgElement);

                if (markerElm.OrientType.AnimVal.Equals((ushort)SvgMarkerOrient.Angle))
                {
                    matrix.Rotate(markerElm.OrientAngle.AnimVal.Value);
                }
                else
                {
                    double angle = 0;

                    switch (markerPos)
                    {
                    case SvgMarkerPosition.Start:
                        angle = markerHostElm.GetStartAngle(i + 1);
                        break;

                    case SvgMarkerPosition.Mid:
                        //angle = (markerHostElm.GetEndAngle(i) + markerHostElm.GetStartAngle(i + 1)) / 2;
                        angle = SvgNumber.CalcAngleBisection(markerHostElm.GetEndAngle(i), markerHostElm.GetStartAngle(i + 1));
                        break;

                    default:
                        angle = markerHostElm.GetEndAngle(i);
                        break;
                    }
                    matrix.Rotate(angle);
                }

                if (markerElm.MarkerUnits.AnimVal.Equals((ushort)SvgMarkerUnit.StrokeWidth))
                {
                    SvgLength strokeWidthLength = new SvgLength(refElement,
                                                                "stroke-width", SvgLengthSource.Css, SvgLengthDirection.Viewport, "1");
                    double strokeWidth = strokeWidthLength.Value;
                    matrix.Scale(strokeWidth, strokeWidth);
                }

                SvgPreserveAspectRatio spar =
                    (SvgPreserveAspectRatio)markerElm.PreserveAspectRatio.AnimVal;
                double[] translateAndScale = spar.FitToViewBox((SvgRect)markerElm.ViewBox.AnimVal,
                                                               new SvgRect(0, 0, markerElm.MarkerWidth.AnimVal.Value,
                                                                           markerElm.MarkerHeight.AnimVal.Value));


                matrix.Translate(-markerElm.RefX.AnimVal.Value * translateAndScale[2],
                                 -markerElm.RefY.AnimVal.Value * translateAndScale[3]);

                matrix.Scale(translateAndScale[2], translateAndScale[3]);

                matrix.Translate(point.X, point.Y);

                _matrix = matrix;
                this.Render(renderer);

                //Clip(gr);

                renderer.RenderChildren(markerElm);

                //gr.EndContainer(gc);

                this.AfterRender(renderer);
            }
        }
예제 #14
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);
                }
            }

            //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);
        }
예제 #15
0
        protected void SetMask(WpfDrawingContext context)
        {
            _maskUnits        = SvgUnitType.UserSpaceOnUse;
            _maskContentUnits = SvgUnitType.UserSpaceOnUse;

            CssPrimitiveValue maskPath = _svgElement.GetComputedCssValue("mask", string.Empty) as CssPrimitiveValue;

            SvgMaskElement maskElement = null;

            if (maskPath != null && maskPath.PrimitiveType == CssPrimitiveType.Uri)
            {
                string absoluteUri = _svgElement.ResolveUri(maskPath.GetStringValue());

                maskElement = _svgElement.OwnerDocument.GetNodeByUri(absoluteUri) as SvgMaskElement;
            }
            else if (string.Equals(_svgElement.ParentNode.LocalName, "use"))
            {
                var parentElement = _svgElement.ParentNode as SvgElement;

                maskPath = parentElement.GetComputedCssValue("mask", string.Empty) as CssPrimitiveValue;

                if (maskPath != null && maskPath.PrimitiveType == CssPrimitiveType.Uri)
                {
                    string absoluteUri = _svgElement.ResolveUri(maskPath.GetStringValue());

                    maskElement = _svgElement.OwnerDocument.GetNodeByUri(absoluteUri) as SvgMaskElement;
                }
            }

            if (maskElement != null)
            {
                WpfDrawingRenderer renderer = new WpfDrawingRenderer();
                renderer.Window = _svgElement.OwnerDocument.Window as SvgWindow;

                WpfDrawingSettings settings = context.Settings.Clone();
                settings.TextAsGeometry = true;
                WpfDrawingContext maskContext = new WpfDrawingContext(true, settings);

                //maskContext.Initialize(null, context.FontFamilyVisitor, null);
                maskContext.Initialize(context.LinkVisitor,
                                       context.FontFamilyVisitor, context.ImageVisitor);

                renderer.RenderMask(maskElement, maskContext);
                DrawingGroup maskDrawing = renderer.Drawing;

                Rect bounds = new Rect(0, 0, 1, 1);
                //Rect destRect = GetMaskDestRect(maskElement, bounds);

                //destRect = bounds;

                //DrawingImage drawImage = new DrawingImage(image);

                //DrawingVisual drawingVisual = new DrawingVisual();
                //DrawingContext drawingContext = drawingVisual.RenderOpen();
                //drawingContext.DrawDrawing(image);
                //drawingContext.Close();

                //RenderTargetBitmap drawImage = new RenderTargetBitmap((int)200,
                //    (int)200, 96, 96, PixelFormats.Pbgra32);
                //drawImage.Render(drawingVisual);

                //ImageBrush imageBrush = new ImageBrush(drawImage);
                //imageBrush.Viewbox = image.Bounds;
                //imageBrush.Viewport = image.Bounds;
                //imageBrush.ViewboxUnits = BrushMappingMode.Absolute;
                //imageBrush.ViewportUnits = BrushMappingMode.Absolute;
                //imageBrush.TileMode = TileMode.None;
                //imageBrush.Stretch = Stretch.None;

                //this.Masking = imageBrush;

                DrawingBrush maskBrush = new DrawingBrush(maskDrawing);
                //tb.Viewbox = new Rect(0, 0, destRect.Width, destRect.Height);
                //tb.Viewport = new Rect(0, 0, destRect.Width, destRect.Height);
                maskBrush.Viewbox       = maskDrawing.Bounds;
                maskBrush.Viewport      = maskDrawing.Bounds;
                maskBrush.ViewboxUnits  = BrushMappingMode.Absolute;
                maskBrush.ViewportUnits = BrushMappingMode.Absolute;
                maskBrush.TileMode      = TileMode.None;
                maskBrush.Stretch       = Stretch.Uniform;

                ////maskBrush.AlignmentX = AlignmentX.Center;
                ////maskBrush.AlignmentY = AlignmentY.Center;

                this.Masking = maskBrush;

                _maskUnits        = (SvgUnitType)maskElement.MaskUnits.AnimVal;
                _maskContentUnits = (SvgUnitType)maskElement.MaskContentUnits.AnimVal;
            }
        }
예제 #16
0
 public abstract string Visit(SvgElement element, WpfDrawingContext context);
예제 #17
0
        protected void SetQuality(WpfDrawingContext context)
        {
            //Graphics graphics = gr.Graphics;

            //string colorRendering = _svgElement.GetComputedStringValue("color-rendering", string.Empty);
            //switch (colorRendering)
            //{
            //    case "optimizeSpeed":
            //        graphics.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighSpeed;
            //        break;
            //    case "optimizeQuality":
            //        graphics.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
            //        break;
            //    default:
            //        // "auto"
            //        // todo: could use AssumeLinear for slightly better
            //        graphics.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.Default;
            //        break;
            //}

            //if (element is SvgTextContentElement)
            //{
            //    // Unfortunately the text rendering hints are not applied because the
            //    // text path is recorded and painted to the Graphics object as a path
            //    // not as text.
            //    string textRendering = _svgElement.GetComputedStringValue("text-rendering", string.Empty);
            //    switch (textRendering)
            //    {
            //        case "optimizeSpeed":
            //            graphics.SmoothingMode = SmoothingMode.HighSpeed;
            //            //graphics.TextRenderingHint = System.Drawing.Text.TextRenderingHint.SingleBitPerPixel;
            //            break;
            //        case "optimizeLegibility":
            //            graphics.SmoothingMode = SmoothingMode.HighQuality;
            //            //graphics.TextRenderingHint = System.Drawing.Text.TextRenderingHint.ClearTypeGridFit;
            //            break;
            //        case "geometricPrecision":
            //            graphics.SmoothingMode = SmoothingMode.AntiAlias;
            //            //graphics.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias;
            //            break;
            //        default:
            //            // "auto"
            //            graphics.SmoothingMode = SmoothingMode.AntiAlias;
            //            //graphics.TextRenderingHint = System.Drawing.Text.TextRenderingHint.SystemDefault;
            //            break;
            //    }
            //}
            //else
            //{
            //    string shapeRendering = _svgElement.GetComputedStringValue("shape-rendering", string.Empty);
            //    switch (shapeRendering)
            //    {
            //        case "optimizeSpeed":
            //            graphics.SmoothingMode = SmoothingMode.HighSpeed;
            //            break;
            //        case "crispEdges":
            //            graphics.SmoothingMode = SmoothingMode.None;
            //            break;
            //        case "geometricPrecision":
            //            graphics.SmoothingMode = SmoothingMode.HighQuality;
            //            break;
            //        default:
            //            // "auto"
            //            graphics.SmoothingMode = SmoothingMode.AntiAlias;
            //            break;
            //    }
            //}
        }
예제 #18
0
        public override Brush GetBrush(Rect elementBounds, WpfDrawingContext context, Transform viewTransform)
        {
            string prop    = _solidColorElement.GetAttribute("solid-color");
            string opacity = _solidColorElement.GetAttribute("solid-opacity");      // no auto-inherit

            if (string.Equals(prop, "inherit", StringComparison.OrdinalIgnoreCase)) // if explicitly defined...
            {
                prop = _solidColorElement.GetPropertyValue("solid-color");
            }
            if (string.Equals(opacity, "inherit", StringComparison.OrdinalIgnoreCase)) // if explicitly defined...
            {
                opacity = _solidColorElement.GetPropertyValue("solid-opacity");
            }
            if (!string.IsNullOrWhiteSpace(prop))
            {
                if (string.Equals(prop, "currentColor", StringComparison.OrdinalIgnoreCase))
                {
                    var svgParent = _solidColorElement.ParentNode as SvgStyleableElement;
                    if (svgParent != null)
                    {
                        prop = svgParent.GetPropertyValue("color", "solid-color");
                    }
                }

                Color       color    = Colors.Transparent; // no auto-inherited...
                WpfSvgColor svgColor = new WpfSvgColor(_solidColorElement, "solid-color");
                color = svgColor.Color;

                if (color.A == 255)
                {
                    double alpha = 255;

                    if (!string.IsNullOrWhiteSpace(opacity))
                    {
                        alpha *= SvgNumber.ParseNumber(opacity);
                    }

                    alpha = Math.Min(alpha, 255);
                    alpha = Math.Max(alpha, 0);

                    color = Color.FromArgb((byte)Convert.ToInt32(alpha), color.R, color.G, color.B);
                }

                var    brush        = new SolidColorBrush(color);
                double opacityValue = 1;
                if (!string.IsNullOrWhiteSpace(opacity) && double.TryParse(opacity, out opacityValue))
                {
                    brush.Opacity = opacityValue;
                }

                return(brush);
            }
            else
            {
                Color  color = Colors.Black; // the default color...
                double alpha = 255;

                if (!string.IsNullOrWhiteSpace(opacity))
                {
                    alpha *= SvgNumber.ParseNumber(opacity);
                }

                alpha = Math.Min(alpha, 255);
                alpha = Math.Max(alpha, 0);

                color = Color.FromArgb((byte)Convert.ToInt32(alpha), color.R, color.G, color.B);

                return(new SolidColorBrush(color));
            }
        }
예제 #19
0
        protected void FitToViewbox(WpfDrawingContext context, SvgElement svgElement, Rect elementBounds)
        {
            if (svgElement == null)
            {
                return;
            }
            ISvgFitToViewBox fitToView = svgElement as ISvgFitToViewBox;

            if (fitToView == null)
            {
                return;
            }

            SvgPreserveAspectRatio spar = (SvgPreserveAspectRatio)fitToView.PreserveAspectRatio.AnimVal;

            SvgRect viewBox   = (SvgRect)fitToView.ViewBox.AnimVal;
            SvgRect rectToFit = new SvgRect(elementBounds.X, elementBounds.Y, elementBounds.Width, elementBounds.Height);

            double[] transformArray = spar.FitToViewBox(viewBox, rectToFit);

            double translateX = Math.Round(transformArray[0], 4);
            double translateY = Math.Round(transformArray[1], 4);
            double scaleX     = Math.Round(transformArray[2], 4);
            double scaleY     = Math.Round(transformArray[3], 4);

            Transform translateMatrix = null;
            Transform scaleMatrix     = null;

            if (!translateX.Equals(0.0) || !translateY.Equals(0.0))
            {
                translateMatrix = new TranslateTransform(translateX, translateY);
            }
            if (!scaleX.Equals(1.0) || !scaleY.Equals(1.0))
            {
                scaleMatrix = new ScaleTransform(scaleX, scaleY);
            }

            if (translateMatrix != null && scaleMatrix != null)
            {
                // Create a TransformGroup to contain the transforms
                // and add the transforms to it.
                if (translateMatrix.Value.IsIdentity && scaleMatrix.Value.IsIdentity)
                {
                    return;
                }
                if (translateMatrix.Value.IsIdentity)
                {
                    this.Transform = scaleMatrix;
                    return;
                }
                if (scaleMatrix.Value.IsIdentity)
                {
                    this.Transform = translateMatrix;
                    return;
                }
                TransformGroup transformGroup = new TransformGroup();
                transformGroup.Children.Add(scaleMatrix);
                transformGroup.Children.Add(translateMatrix);

                this.Transform = transformGroup;
            }
            else if (translateMatrix != null)
            {
                this.Transform = translateMatrix;
            }
            else if (scaleMatrix != null)
            {
                this.Transform = scaleMatrix;
            }
        }
예제 #20
0
        private DrawingGroup GetImage(WpfDrawingContext context)
        {
            PrepareTargetPattern();

            WpfDrawingRenderer renderer = new WpfDrawingRenderer();

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

//            WpfDrawingSettings settings = context.Settings.Clone();
            WpfDrawingSettings settings = context.Settings;
            bool isTextAsGeometry       = settings.TextAsGeometry;

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

            patternContext.Name = "Pattern";

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

            if (_renderedElement.PatternContentUnits.AnimVal.Equals((ushort)SvgUnitType.ObjectBoundingBox))
            {
                //                svgElm.SetAttribute("viewBox", "0 0 1 1");
            }
            else
            {
                _isUserSpace = true;
            }

            //SvgSvgElement elm = MoveIntoSvgElement();
            //renderer.Render(elm, patternContext);

            //SvgPatternElement patternElement = _patternElement.ReferencedElement;
            //if (patternElement != null)
            //{
            //    if (patternElement.ReferencedElement != null)
            //    {
            //        _renderedElement = patternElement.ReferencedElement;
            //        renderer.RenderAs(patternElement.ReferencedElement, patternContext);
            //    }
            //    else
            //    {
            //        _renderedElement = patternElement;
            //        renderer.RenderAs(patternElement, patternContext);
            //    }
            //}
            //else
            //{
            //    _renderedElement = _patternElement;
            //    renderer.RenderAs(_patternElement, patternContext);
            //}
            renderer.RenderAs(_renderedElement, patternContext);
            DrawingGroup rootGroup = renderer.Drawing;

            //MoveOutOfSvgElement(elm);

            if (_renderedElement != null && _renderedElement != _patternElement)
            {
                _patternElement.RemoveChild(_renderedElement);
            }

            settings.TextAsGeometry = isTextAsGeometry;

            if (rootGroup.Children.Count == 1)
            {
                var childGroup = rootGroup.Children[0] as DrawingGroup;
                if (childGroup != null)
                {
                    return(childGroup);
                }
            }

            return(rootGroup);
        }
예제 #21
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 (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.IsNullOrEmpty(elementId) && !context.IsRegisteredId(elementId))
                {
                    SvgObject.SetName(_drawGroup, elementId);

                    context.RegisterId(elementId);

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

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

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

                    _isAggregated = linkVisitor.IsAggregate;
                }
            }

            base.Render(renderer);
        }
예제 #22
0
        public override Brush GetBrush(Rect elementBounds, WpfDrawingContext context, Transform viewTransform)
        {
            DrawingGroup image = GetImage(context);

            if (image == null || image.Bounds.Width.Equals(0) || image.Bounds.Height.Equals(0))
            {
                return(null);
            }
            bool isUserSpace = true;
            Rect bounds      = elementBounds;

            if (_renderedElement.PatternContentUnits.AnimVal.Equals((ushort)SvgUnitType.ObjectBoundingBox))
            {
                bounds      = new Rect(0, 0, 1, 1);
                isUserSpace = false;
            }
            Rect destRect = GetDestRect(bounds);

            // Check for validity of the brush...
            if (destRect.Width.Equals(0) || destRect.Height.Equals(0) || destRect.IsEmpty)
            {
                return(null);
            }

            // Apply a scale if needed
            if (isUserSpace && image.Transform != null)
            {
                ISvgFitToViewBox fitToView = _renderedElement as ISvgFitToViewBox;
                if (fitToView != null && fitToView.ViewBox != null)
                {
                    ISvgAnimatedRect animRect = fitToView.ViewBox;
                    ISvgRect         viewRect = animRect.AnimVal;
                    if (viewRect != null)
                    {
                        Rect wpfViewRect = WpfConvert.ToRect(viewRect);
                        if (!wpfViewRect.IsEmpty && wpfViewRect.Width > 0 && wpfViewRect.Height > 0)
                        {
                            var scaleX = elementBounds.Width > 0 ? destRect.Width / wpfViewRect.Width : 1;
                            var scaleY = elementBounds.Height > 0 ? destRect.Height / wpfViewRect.Height : 1;

                            if (!scaleX.Equals(1) || !scaleY.Equals(1))
                            {
                                var currentTransform = image.Transform as ScaleTransform;
                                if (currentTransform != null)
                                {
                                    image.Transform = new ScaleTransform(scaleX, scaleY);
                                }
                            }
                        }
                    }
                }
            }

            DrawingBrush tb = new DrawingBrush(image);

            tb.Viewbox  = destRect;
            tb.Viewport = destRect;
            //tb.Viewbox = new Rect(0, 0, destRect.Width, destRect.Height);
            //tb.Viewport = new Rect(0, 0, bounds.Width, bounds.Height);
            tb.ViewboxUnits  = BrushMappingMode.Absolute;
            tb.ViewportUnits = isUserSpace ? BrushMappingMode.Absolute : BrushMappingMode.RelativeToBoundingBox;
            tb.TileMode      = TileMode.Tile;
//            tb.Stretch       = isUserSpace ? Stretch.Fill : Stretch.Uniform;

            if (isUserSpace)
            {
                MatrixTransform transform = GetTransformMatrix(image.Bounds, isUserSpace);
                if (transform != null && !transform.Matrix.IsIdentity)
                {
                    tb.Transform = transform;
                }
            }
            else
            {
                MatrixTransform transform = GetTransformMatrix(bounds, isUserSpace);
                if (transform != null && !transform.Matrix.IsIdentity)
                {
                    tb.RelativeTransform = transform;
                }
            }

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

            double width  = imageElement.Width.AnimVal.Value;
            double height = imageElement.Height.AnimVal.Value;

            Rect destRect = new Rect(imageElement.X.AnimVal.Value, imageElement.Y.AnimVal.Value,
                                     width, height);

            ImageSource imageSource = null;

            if (imageElement.IsSvgImage)
            {
                SvgWindow wnd = GetSvgWindow();
                //_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 drawImage = imageGroup.Children[0] as DrawingGroup;
                    if (drawImage != null)
                    {
                        if (drawImage.ClipGeometry != null)
                        {
                            drawImage.ClipGeometry = null;
                        }

                        imageSource = new DrawingImage(drawImage);
                    }
                    else
                    {
                        if (imageGroup.ClipGeometry != null)
                        {
                            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)
                            {
                                destRect = this.GetBounds(destRect,
                                                          new Size(imageWidth, imageHeight), aspectRatioType);
                            }
                            else
                            {
                                destRect = new Rect(0, 0, viewWidth, viewHeight);
                            }
                        }
                        else
                        {
                            Transform viewTransform = this.GetAspectRatioTransform(aspectRatio,
                                                                                   new SvgRect(0, 0, imageWidth, imageHeight),
                                                                                   new SvgRect(destRect.X, destRect.Y, destRect.Width, destRect.Height));
                            //Transform scaleTransform = this.FitToViewbox(aspectRatio,
                            //  new SvgRect(destRect.X, destRect.Y, 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)
                    {
                    }
                }
            }

            ImageDrawing drawing = new ImageDrawing(imageSource, destRect);

            float opacityValue = -1;

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

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

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

            if (drawGroup == null)
            {
                drawGroup = context.Peek();
            }
            Debug.Assert(drawGroup != null);
            if (drawGroup != null)
            {
                if (opacityValue >= 0 || (clipGeom != null && !clipGeom.IsEmpty()) ||
                    (transform != null && !transform.Value.IsIdentity))
                {
                    DrawingGroup clipGroup = new DrawingGroup();
                    if (opacityValue >= 0)
                    {
                        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)
                    {
                        clipGroup.Transform = transform;
                    }

                    clipGroup.Children.Add(drawing);
                    drawGroup.Children.Add(clipGroup);
                }
                else
                {
                    drawGroup.Children.Add(drawing);
                }
            }
        }
예제 #24
0
        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)
            {
                var baseUrl = imageElement.OwnerDocument.BaseURI;
                if (imageElement.IsRootReferenced(baseUrl) /*|| context.ContainsUrl(baseUrl)*/)
                {
                    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;

            GeometryDrawing viewportDrawing = null;

            // Support for Tiny 1.2 viewport-fill property...
            if (_svgElement.HasAttribute("viewport-fill"))
            {
                var viewportFill = _svgElement.GetAttribute("viewport-fill");
                if (!string.IsNullOrWhiteSpace(viewportFill))
                {
                    var brush = WpfFill.CreateViewportBrush(imageElement);
                    if (brush != null)
                    {
                        var viewportBounds = new RectangleGeometry(destRect);
                        viewportDrawing = new GeometryDrawing(brush, null, viewportBounds);
                    }
                }
            }

            bool ownedGroup = true;

            if (drawGroup == null)
            {
                drawGroup  = context.Peek();
                ownedGroup = false;
            }
            else
            {
                if (viewportDrawing != null)
                {
                    drawGroup.Children.Insert(0, viewportDrawing);
                }
            }

            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)
                    {
                        if (viewportDrawing != null)
                        {
                            clipGroup.Children.Insert(0, viewportDrawing);
                        }
                        drawGroup.Children.Add(clipGroup);
                    }
                }
                else
                {
                    drawGroup.Children.Add(drawing);
                }

                string elementId = this.GetElementName();
                if (ownedGroup)
                {
                    string sVisibility = imageElement.GetPropertyValue(CssConstants.PropVisibility);
                    string sDisplay    = imageElement.GetPropertyValue(CssConstants.PropDisplay);
                    if (string.Equals(sVisibility, CssConstants.ValHidden, StringComparison.OrdinalIgnoreCase) ||
                        string.Equals(sDisplay, CssConstants.ValNone, StringComparison.OrdinalIgnoreCase))
                    {
                        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);
                }
            }
        }
예제 #25
0
 public abstract WpfFontFamilyInfo Visit(string fontName, WpfFontFamilyInfo familyInfo,
                                         WpfDrawingContext context);
예제 #26
0
        public void RenderMarker(WpfDrawingRenderer renderer, WpfDrawingContext gr,
                                 SvgMarkerPosition markerPos, SvgStyleableElement refElement)
        {
            ISharpMarkerHost markerHostElm = (ISharpMarkerHost)refElement;

            SvgPointF[] vertexPositions = markerHostElm.MarkerPositions;
            int         start           = 0;
            int         len             = 0;

            // Choose which part of the position array to use
            switch (markerPos)
            {
            case SvgMarkerPosition.Start:
                start = 0;
                len   = 1;
                break;

            case SvgMarkerPosition.Mid:
                start = 1;
                len   = vertexPositions.Length - 2;
                break;

            default:
                // == MarkerPosition.End
                start = vertexPositions.Length - 1;
                len   = 1;
                break;
            }
            int end = start + len;

            TransformGroup transform = new TransformGroup();

            for (int i = start; i < end; i++)
            {
                SvgPointF point = vertexPositions[i];

                //GdiGraphicsContainer gc = gr.BeginContainer();

                this.BeforeRender(renderer);

                //Matrix matrix = Matrix.Identity;

                Matrix matrix = GetTransformMatrix(_svgElement, transform);

                ISvgAnimatedEnumeration orientType = _markerElement.OrientType;

                if (orientType.AnimVal.Equals((ushort)SvgMarkerOrient.Angle))
                {
                    double scaleValue = _markerElement.OrientAngle.AnimVal.Value;
                    if (!scaleValue.Equals(0))
                    {
                        matrix.Rotate(scaleValue);
                        transform.Children.Add(new RotateTransform(scaleValue));
                    }
                }
                else
                {
                    bool isAutoReverse = orientType.AnimVal.Equals((ushort)SvgMarkerOrient.AutoStartReverse);

                    double angle = 0;
                    switch (markerPos)
                    {
                    case SvgMarkerPosition.Start:
                        angle = markerHostElm.GetStartAngle(i);
                        //angle = markerHostElm.GetStartAngle(i + 1);
                        if (vertexPositions.Length >= 2)
                        {
                            SvgPointF pMarkerPoint1 = vertexPositions[start];
                            SvgPointF pMarkerPoint2 = vertexPositions[end];
                            float     xDiff         = pMarkerPoint2.X - pMarkerPoint1.X;
                            float     yDiff         = pMarkerPoint2.Y - pMarkerPoint1.Y;
                            double    angleMarker   = (float)(Math.Atan2(yDiff, xDiff) * 180.0 / Math.PI);
                            if (!angleMarker.Equals(angle))
                            {
                                angle = angleMarker;
                            }
                        }
                        // A value of 'auto-start-reverse' means the same as 'auto' except that for a
                        // marker placed by 'marker-start', the orientation is 180° different from
                        // the orientation as determined by 'auto'.
                        if (isAutoReverse)
                        {
                            angle += 180;
                        }
                        break;

                    case SvgMarkerPosition.Mid:
                        //angle = (markerHostElm.GetEndAngle(i) + markerHostElm.GetStartAngle(i + 1)) / 2;
                        angle = SvgNumber.CalcAngleBisection(markerHostElm.GetEndAngle(i), markerHostElm.GetStartAngle(i + 1));
                        break;

                    default:
                        angle = markerHostElm.GetEndAngle(i - 1);
                        //angle = markerHostElm.GetEndAngle(i);
                        if (vertexPositions.Length >= 2)
                        {
                            SvgPointF pMarkerPoint1 = vertexPositions[start - 1];
                            SvgPointF pMarkerPoint2 = vertexPositions[start];
                            float     xDiff         = pMarkerPoint2.X - pMarkerPoint1.X;
                            float     yDiff         = pMarkerPoint2.Y - pMarkerPoint1.Y;
                            double    angleMarker   = (float)(Math.Atan2(yDiff, xDiff) * 180.0 / Math.PI);
                            if (!angleMarker.Equals(angle))
                            {
                                angle = angleMarker;
                            }
                        }
                        break;
                    }
                    matrix.Rotate(angle);
                    transform.Children.Add(new RotateTransform(angle));
                }

                // 'viewBox' and 'preserveAspectRatio' attributes
                // viewBox -> viewport(0, 0, markerWidth, markerHeight)
                SvgPreserveAspectRatio spar = (SvgPreserveAspectRatio)_markerElement.PreserveAspectRatio.AnimVal;
                double[] translateAndScale  = spar.FitToViewBox((SvgRect)_markerElement.ViewBox.AnimVal,
                                                                new SvgRect(0, 0, _markerElement.MarkerWidth.AnimVal.Value, _markerElement.MarkerHeight.AnimVal.Value));

                // Warning at this time, refX and refY are relative to the painted element's coordinate system.
                // We need to move the reference point to the marker's coordinate system
                double refX = _markerElement.RefX.AnimVal.Value;
                double refY = _markerElement.RefY.AnimVal.Value;

                if (!(refX.Equals(0) && refY.Equals(0)))
                {
                    var ptRef = matrix.Transform(new Point(refX, refY));

                    refX = ptRef.X;
                    refY = ptRef.Y;

                    matrix.Translate(-refX, -refY);
                    transform.Children.Add(new TranslateTransform(-refX, -refY));
                }

                //matrix.Translate(-markerElm.RefX.AnimVal.Value * translateAndScale[2],
                //    -markerElm.RefY.AnimVal.Value * translateAndScale[3]);
                //transform.Children.Add(new TranslateTransform(-markerElm.RefX.AnimVal.Value * translateAndScale[2],
                //    -markerElm.RefY.AnimVal.Value * translateAndScale[3]));

                // compute an additional transform for 'strokeWidth' coordinate system
                ISvgAnimatedEnumeration markerUnits = _markerElement.MarkerUnits;
                if (markerUnits.AnimVal.Equals((ushort)SvgMarkerUnit.StrokeWidth))
                {
                    SvgLength strokeWidthLength = new SvgLength(refElement,
                                                                "stroke-width", SvgLengthSource.Css, SvgLengthDirection.Viewport, "1");
                    double strokeWidth = strokeWidthLength.Value;
                    if (!strokeWidth.Equals(1))
                    {
                        matrix.Scale(strokeWidth, strokeWidth);
                        transform.Children.Add(new ScaleTransform(strokeWidth, strokeWidth));
                    }
                }

                if (!(translateAndScale[2].Equals(1) && translateAndScale[3].Equals(1)))
                {
                    matrix.Scale(translateAndScale[2], translateAndScale[3]);
                    transform.Children.Add(new ScaleTransform(translateAndScale[2], translateAndScale[3]));
                }

                matrix.Translate(point.X, point.Y);
                transform.Children.Add(new TranslateTransform(point.X, point.Y));

                _matrix = matrix;

                this.Transform = transform;

                this.Render(renderer);

                //Clip(gr);

                renderer.RenderChildren(_markerElement);

                //gr.EndContainer(gc);

                this.AfterRender(renderer);
            }
        }