Пример #1
0
        public override Brush GetBrush(Rect elementBounds, WpfDrawingContext context, Transform viewTransform)
        {
            Rect bounds = elementBounds;

            DrawingGroup image = this.GetImage(context, bounds);

            if (image == null || image.Bounds.Width.Equals(0) || image.Bounds.Height.Equals(0))
            {
                return(null);
            }

            bool isUserSpace = true;

            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 DrawingGroupGuidelineSetExample()
        {
            //
            // Create a DrawingGroup
            // that has no guideline set
            //
            GeometryDrawing drawing1 = new GeometryDrawing(
                Brushes.Black,
                null,
                new RectangleGeometry(new Rect(0, 20, 30, 80))
                );

            GeometryGroup whiteRectangles = new GeometryGroup();

            whiteRectangles.Children.Add(new RectangleGeometry(new Rect(5.5, 25, 20, 20)));
            whiteRectangles.Children.Add(new RectangleGeometry(new Rect(5.5, 50, 20, 20)));
            whiteRectangles.Children.Add(new RectangleGeometry(new Rect(5.5, 75, 20, 20)));

            GeometryDrawing drawing2 = new GeometryDrawing(
                Brushes.White,
                null,
                whiteRectangles
                );

            // Create a DrawingGroup
            DrawingGroup drawingGroupWithoutGuidelines = new DrawingGroup();

            drawingGroupWithoutGuidelines.Children.Add(drawing1);
            drawingGroupWithoutGuidelines.Children.Add(drawing2);

            // Use an Image control and a DrawingImage to
            // display the drawing.
            DrawingImage drawingImage01 = new DrawingImage(drawingGroupWithoutGuidelines);

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

            Image image01 = new Image();

            image01.Source              = drawingImage01;
            image01.Stretch             = Stretch.None;
            image01.HorizontalAlignment = HorizontalAlignment.Left;
            image01.Margin              = new Thickness(10);

            //
            // Create another DrawingGroup and apply
            // a blur effect to it.
            //

            // Create a clone of the first DrawingGroup.
            DrawingGroup drawingGroupWithGuidelines =
                drawingGroupWithoutGuidelines.Clone();

            // Create a guideline set.
            GuidelineSet guidelines = new GuidelineSet();

            guidelines.GuidelinesX.Add(5.5);
            guidelines.GuidelinesX.Add(25.5);
            guidelines.GuidelinesY.Add(25);
            guidelines.GuidelinesY.Add(50);
            guidelines.GuidelinesY.Add(75);

            // Apply it to the drawing group.
            drawingGroupWithGuidelines.GuidelineSet = guidelines;

            // Use another Image control and DrawingImage
            // to display the drawing.
            DrawingImage drawingImage02 = new DrawingImage(drawingGroupWithGuidelines);

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

            Image image02 = new Image();

            image02.Source              = drawingImage02;
            image02.Stretch             = Stretch.None;
            image02.HorizontalAlignment = HorizontalAlignment.Left;
            image02.Margin              = new Thickness(50, 10, 10, 10);

            StackPanel mainPanel = new StackPanel();

            mainPanel.Orientation         = Orientation.Horizontal;
            mainPanel.HorizontalAlignment = HorizontalAlignment.Left;
            mainPanel.Margin = new Thickness(20);
            mainPanel.Children.Add(image01);
            mainPanel.Children.Add(image02);

            //
            // Use a DrawingBrush to create a grid background.
            //
            GeometryDrawing backgroundRectangleDrawing =
                new GeometryDrawing(
                    Brushes.White,
                    null,
                    new RectangleGeometry(new Rect(0, 0, 1, 1))
                    );
            PolyLineSegment backgroundLine1 = new PolyLineSegment();

            backgroundLine1.Points.Add(new Point(1, 0));
            backgroundLine1.Points.Add(new Point(1, 0.1));
            backgroundLine1.Points.Add(new Point(0, 0.1));
            PathFigure line1Figure = new PathFigure();

            line1Figure.Segments.Add(backgroundLine1);
            PathGeometry backgroundLine1Geometry = new PathGeometry();

            backgroundLine1Geometry.Figures.Add(line1Figure);
            GeometryDrawing backgroundLineDrawing1 = new GeometryDrawing(
                new SolidColorBrush(Color.FromArgb(255, 204, 204, 255)),
                null,
                backgroundLine1Geometry
                );
            PolyLineSegment backgroundLine2 = new PolyLineSegment();

            backgroundLine2.Points.Add(new Point(0, 1));
            backgroundLine2.Points.Add(new Point(0.1, 1));
            backgroundLine2.Points.Add(new Point(0.1, 0));
            PathFigure line2Figure = new PathFigure();

            line2Figure.Segments.Add(backgroundLine2);
            PathGeometry backgroundLine2Geometry = new PathGeometry();

            backgroundLine2Geometry.Figures.Add(line2Figure);
            GeometryDrawing backgroundLineDrawing2 = new GeometryDrawing(
                new SolidColorBrush(Color.FromArgb(255, 204, 204, 255)),
                null,
                backgroundLine2Geometry
                );

            DrawingGroup backgroundGroup = new DrawingGroup();

            backgroundGroup.Children.Add(backgroundRectangleDrawing);
            backgroundGroup.Children.Add(backgroundLineDrawing1);
            backgroundGroup.Children.Add(backgroundLineDrawing2);

            DrawingBrush gridPatternBrush = new DrawingBrush(backgroundGroup);

            gridPatternBrush.Viewport      = new Rect(0, 0, 10, 10);
            gridPatternBrush.ViewportUnits = BrushMappingMode.Absolute;
            gridPatternBrush.TileMode      = TileMode.Tile;
            gridPatternBrush.Freeze();

            Border mainBorder = new Border();

            mainBorder.Background          = gridPatternBrush;
            mainBorder.BorderThickness     = new Thickness(1);
            mainBorder.BorderBrush         = Brushes.Gray;
            mainBorder.HorizontalAlignment = HorizontalAlignment.Left;
            mainBorder.VerticalAlignment   = VerticalAlignment.Top;
            mainBorder.Margin = new Thickness(20);
            mainBorder.Child  = mainPanel;

            //
            // Add the items to the page.
            //
            this.Content    = mainBorder;
            this.Background = Brushes.White;
        }
Пример #3
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;
            }
        }
Пример #4
0
        ///<summary>生成图元Brush</summary>
        protected void genSymbolBrush()
        {
            SolidColorBrush defaultbrush = new SolidColorBrush(Colors.Lime);
            Brush           brush;



            foreach (IGrouping <string, DataRow> g in dtsymbol.AsEnumerable().GroupBy(p => p.Field <string>("svgsymbolid")))
            {
                string sid  = g.Key;
                string name = g.First().Field <string>("name");

                DrawingGroup    drawgroup = new DrawingGroup();
                GeometryDrawing aDrawing;


                double sizeX = 10;
                double sizeY = 10;
                int    idx   = 0;
                foreach (DataRow item in dtsymbol.AsEnumerable().Where(p => p.Field <string>("svgsymbolid") == sid))
                {
                    if (idx == 0)//获取尺寸
                    {
                        Rect tmp = Rect.Parse(item["viewbox"].ToString());
                        sizeX = tmp.Width;
                        sizeY = tmp.Height;
                    }


                    string shapetype = item["shapetype"].ToString();
                    string data      = item["data"].ToString();
                    if (shapetype == "circle")
                    {
                        Regex regex = new Regex("(\\d*.?\\d*,\\d*.?\\d*)\\|(\\d*.?\\d*)", RegexOptions.Multiline);
                        Match m     = regex.Match(data);
                        if (m.Success)
                        {
                            Point  pc = Point.Parse(m.Groups[1].Value);
                            double r  = double.Parse(m.Groups[2].Value);

                            EllipseGeometry geo = new EllipseGeometry(pc, r, r);
                            aDrawing          = new GeometryDrawing();
                            aDrawing.Geometry = geo;

                            Pen    pen       = new Pen();
                            double thickness = double.Parse(item["width"].ToString());
                            thickness     = thickness < 2 ? 2 : thickness;
                            pen.Thickness = thickness;
                            brush         = defaultbrush;//强制缺省用黄色//brush = anaBrush(item["fill"].ToString());
                            pen.Brush     = brush;
                            aDrawing.Pen  = pen;
                            drawgroup.Children.Add(aDrawing);
                        }
                    }
                    else if (shapetype == "path")
                    {
                        Geometry geo = PathGeometry.Parse(data);
                        aDrawing          = new GeometryDrawing();
                        aDrawing.Geometry = geo;

                        brush          = defaultbrush;//强制缺省用黄色//brush = anaBrush(item["fill"].ToString());
                        aDrawing.Brush = brush;
                        Pen pen = new Pen();
                        pen.Thickness = double.Parse(item["width"].ToString());
                        brush         = defaultbrush;
                        pen.Brush     = brush;
                        aDrawing.Pen  = pen;
                        drawgroup.Children.Add(aDrawing);
                    }
                    idx++;
                }

                DrawingBrush myDrawingBrush = new DrawingBrush();
                myDrawingBrush.Drawing = drawgroup;


                pSymbol sym = new pSymbol()
                {
                    id = sid, sizeX = sizeX, sizeY = sizeY, brush = myDrawingBrush, name = name
                };
                //可选以文件生成材质, 否则以brush生成材质
                //if (sid == "SubstationEntityDisH")
                //    sym.texturefile = "SubstationEntityDisH.dds";
                //if (sid == "SwitchStationOpen")
                //    sym.texturefile = "SwitchStationOpen.dds";
                //if (sid == "Pole")
                //    sym.texturefile = "Pole.dds";

                uc.objManager.zSymbols.Add(sid, sym);
            }
        }
Пример #5
0
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="adornedElement">The adorned InkCanvas</param>
        internal InkCanvasSelectionAdorner(UIElement adornedElement)
            : base(adornedElement)
        {
            Debug.Assert(adornedElement is InkCanvasInnerCanvas,
                         "InkCanvasSelectionAdorner only should be used by InkCanvas internally");

            // Initialize the internal data.
            _adornerBorderPen = new Pen(Brushes.Black, 1.0);
            DoubleCollection dashes = new DoubleCollection();

            dashes.Add(4.5);
            dashes.Add(4.5);
            _adornerBorderPen.DashStyle = new DashStyle(dashes, 2.25);
            _adornerBorderPen.DashCap   = PenLineCap.Flat;
            _adornerBorderPen.Freeze();

            _adornerPenBrush = new Pen(new SolidColorBrush(Color.FromRgb(132, 146, 222)), 1);
            _adornerPenBrush.Freeze();

            _adornerFillBrush = new LinearGradientBrush(Color.FromRgb(240, 242, 255), //start color
                                                        Color.FromRgb(180, 207, 248), //end color
                                                        45f                           //angle
                                                        );
            _adornerFillBrush.Freeze();

            // Create a hatch pen
            DrawingGroup   hatchDG = new DrawingGroup();
            DrawingContext dc      = null;

            try
            {
                dc = hatchDG.Open();

                dc.DrawRectangle(
                    Brushes.Transparent,
                    null,
                    new Rect(0.0, 0.0, 1f, 1f));

                Pen squareCapPen = new Pen(Brushes.Black, LineThickness);
                squareCapPen.StartLineCap = PenLineCap.Square;
                squareCapPen.EndLineCap   = PenLineCap.Square;

                dc.DrawLine(squareCapPen,
                            new Point(1f, 0f), new Point(0f, 1f));
            }
            finally
            {
                if (dc != null)
                {
                    dc.Close();
                }
            }
            hatchDG.Freeze();

            DrawingBrush tileBrush = new DrawingBrush(hatchDG);

            tileBrush.TileMode      = TileMode.Tile;
            tileBrush.Viewport      = new Rect(0, 0, HatchBorderMargin, HatchBorderMargin);
            tileBrush.ViewportUnits = BrushMappingMode.Absolute;
            tileBrush.Freeze();

            _hatchPen = new Pen(tileBrush, HatchBorderMargin);
            _hatchPen.Freeze();

            _elementsBounds = new List <Rect>();
            _strokesBounds  = Rect.Empty;
        }
Пример #6
0
        ///<summary>解析svg文件</summary>
        void loadFromSvg(string filename)
        {
            //示例从svg中读取非地理数据展现

            XmlReaderSettings settings = new XmlReaderSettings();

            settings.ConformanceLevel = ConformanceLevel.Document;
            settings.IgnoreWhitespace = true;
            settings.IgnoreComments   = false;

            ;
            //settings.LineNumberOffset = 2;
            XmlReader reader = XmlReader.Create(filename, settings);
            string    elename;
            string    id, fill, stroke, width, height, data, layer, symbol, translate, rotate, scale, zclass, shapetype, layerid;

            id = layerid = "";
            int depth;

            //解析图元用
            bool            istext    = false;
            Brush           brush     = null;
            DrawingGroup    drawgroup = new DrawingGroup();
            GeometryDrawing aDrawing;

            WpfEarthLibrary.pSymbol psymbol = null;
            //层
            WpfEarthLibrary.pLayer player = null;

            while (reader.Read())
            {
                if (reader.NodeType == XmlNodeType.CDATA)
                {
                    string   tmp = reader.Value;
                    string[] stringSeparators = new string[] { "\n" };
                    string[] ss = tmp.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries);
                    foreach (string s in ss)
                    {
                        Regex regex = new Regex(".(.*?) {stroke:(.*?); fill:(.*?) }", RegexOptions.Multiline);
                        Match m     = regex.Match(s);
                        if (m.Success)
                        {
                            string stylename = m.Groups[1].Value;
                            stroke = m.Groups[2].Value;
                            fill   = m.Groups[3].Value;

                            //zh注:style暂未实现
                        }
                    }
                }

                if (reader.IsStartElement())
                {
                    elename = reader.Name;
                    switch (elename)
                    {
                    case "svg":      //  svg
                        string tmp2 = getPropertyValue(reader, "viewBox");
                        if (tmp2 != null)
                        {
                            Rect svgviewbox = Rect.Parse(tmp2);
                            uc.earthManager.planeViewBox = svgviewbox;     //必须设置,方能自动调整相机到适当位置,若显现看起来没居中,是图形与viewbox不完全匹配,可手动调整这个viewbox数值以居中
                        }
                        break;

                    case "symbol":      //  图元符号
                        depth = reader.Depth;
                        if (reader.HasAttributes)
                        {
                            string symbolid = getPropertyValue(reader, "id");
                            string viewbox  = getPropertyValue(reader, "viewBox");
                            reader.MoveToElement();

                            //开始一个图元的处理,创建一个图元对象并加入到uc.objmanager的图元字典中,以便框架生成公用材质供厂站使用,在本示例中,仅breakor使用到了公用图元
                            drawgroup = new DrawingGroup();
                            Rect symbolviewbox = new Rect(0, 0, 2, 2);
                            if (!string.IsNullOrWhiteSpace(viewbox))
                            {
                                symbolviewbox = Rect.Parse(viewbox);
                            }
                            psymbol = new pSymbol()
                            {
                                id = symbolid, name = symbolid, sizeX = symbolviewbox.Width, sizeY = symbolviewbox.Height
                            };
                            uc.objManager.zSymbols.Add(symbolid, psymbol);
                            istext = false;
                        }

                        while (reader.Read())
                        {
                            if (reader.Depth == depth && reader.NodeType == XmlNodeType.EndElement)
                            {
                                //结束一个图元处理,对图元的brush赋值
                                if (!istext)
                                {
                                    DrawingBrush myDrawingBrush = new DrawingBrush();
                                    myDrawingBrush.Drawing = drawgroup;
                                    psymbol.brush          = myDrawingBrush;
                                }

                                break;
                            }
                            switch (reader.Name)
                            {
                            case "circle":
                                if (reader.HasAttributes)
                                {
                                    fill   = getPropertyValue(reader, "fill");
                                    stroke = "rgb(0, 0, 0)";
                                    width  = getPropertyValue(reader, "stroke-width");
                                    data   = getPropertyValue(reader, "cx") + "," + getPropertyValue(reader, "cy") + "|" + getPropertyValue(reader, "r");
                                    reader.MoveToElement();
                                    //绘图元元素
                                    Regex regex = new Regex("(\\d*.?\\d*,\\d*.?\\d*)\\|(\\d*.?\\d*)", RegexOptions.Multiline);
                                    Match m     = regex.Match(data);
                                    if (m.Success)
                                    {
                                        Point  pc = Point.Parse(m.Groups[1].Value);
                                        double r  = double.Parse(m.Groups[2].Value);

                                        EllipseGeometry geo = new EllipseGeometry(pc, r, r);
                                        aDrawing          = new GeometryDrawing();
                                        aDrawing.Geometry = geo;

                                        Pen    pen       = new Pen();
                                        double thickness = double.Parse(width);
                                        thickness     = thickness < 2 ? 2 : thickness;
                                        pen.Thickness = thickness;
                                        //brush = ;//defaultbrush;//强制缺省用黄色//brush = anaBrush(item["fill"].ToString());
                                        brush        = new SolidColorBrush(Colors.Red);
                                        pen.Brush    = brush;
                                        aDrawing.Pen = pen;
                                        drawgroup.Children.Add(aDrawing);
                                    }
                                }
                                break;

                            case "ellipse":
                                if (reader.HasAttributes)
                                {
                                    fill   = getPropertyValue(reader, "fill");
                                    stroke = "rgb(0, 0, 0)";
                                    width  = getPropertyValue(reader, "stroke-width");
                                    double cx = double.Parse(getPropertyValue(reader, "cx"));
                                    double cy = double.Parse(getPropertyValue(reader, "cy"));
                                    double rx = double.Parse(getPropertyValue(reader, "rx"));
                                    double ry = double.Parse(getPropertyValue(reader, "ry"));

                                    reader.MoveToElement();
                                    //绘图元元素
                                    Point           pc  = new Point(cx, cy);
                                    EllipseGeometry geo = new EllipseGeometry(pc, rx, ry);
                                    aDrawing          = new GeometryDrawing();
                                    aDrawing.Geometry = geo;

                                    Pen    pen       = new Pen();
                                    double thickness = double.Parse(width);
                                    thickness     = thickness < 2 ? 2 : thickness;
                                    pen.Thickness = thickness;
                                    brush         = Brushes.Yellow;  //注,色彩应从fill取,示例没做转换,直接使用黄色
                                    pen.Brush     = brush;
                                    aDrawing.Pen  = pen;
                                    drawgroup.Children.Add(aDrawing);
                                }
                                break;

                            case "rect":
                                if (reader.HasAttributes)
                                {
                                    fill   = getPropertyValue(reader, "fill");
                                    stroke = "rgb(0, 0, 0)";
                                    width  = getPropertyValue(reader, "width");
                                    height = getPropertyValue(reader, "height");
                                    data   = getPropertyValue(reader, "cx") + "," + getPropertyValue(reader, "cy") + "|" + getPropertyValue(reader, "r");
                                    reader.MoveToElement();
                                    //绘图元元素
                                    RectangleGeometry geo = new RectangleGeometry();
                                    geo.Rect = new Rect(0, 0, double.Parse(width), double.Parse(height));

                                    aDrawing          = new GeometryDrawing();
                                    aDrawing.Geometry = geo;

                                    aDrawing.Brush = new SolidColorBrush(Colors.Aqua);
                                    drawgroup.Children.Add(aDrawing);
                                }
                                break;

                            case "path":
                                if (reader.HasAttributes)
                                {
                                    fill   = getPropertyValue(reader, "fill");
                                    stroke = "rgb(0, 0, 0)";
                                    width  = getPropertyValue(reader, "stroke-width");
                                    data   = getPropertyValue(reader, "d");
                                    reader.MoveToElement();
                                    //绘图元元素
                                    Geometry geo = PathGeometry.Parse(data);
                                    aDrawing          = new GeometryDrawing();
                                    aDrawing.Geometry = geo;

                                    brush          = Brushes.Orange;
                                    aDrawing.Brush = brush;
                                    Pen pen = new Pen();
                                    pen.Thickness = double.Parse(width);
                                    brush         = Brushes.Blue;
                                    pen.Brush     = brush;
                                    aDrawing.Pen  = pen;
                                    drawgroup.Children.Add(aDrawing);
                                }
                                break;

                            case "line":
                                if (reader.HasAttributes)
                                {
                                    //<line stroke="rgb(0, 0, 0)" stroke-width="1.000000" x1="50.000000" y1="7.499999" x2="13.193920" y2="71.250001" />
                                    stroke = getPropertyValue(reader, "stroke");
                                    width  = getPropertyValue(reader, "stroke-width");
                                    data   = string.Format("M {0} {1} L {2} {3}", getPropertyValue(reader, "x1"), getPropertyValue(reader, "y1"), getPropertyValue(reader, "x2"), getPropertyValue(reader, "y2"));
                                    reader.MoveToElement();
                                    //绘图元元素
                                }
                                break;

                            case "text":
                                if (reader.HasAttributes)
                                {
                                    stroke = getPropertyValue(reader, "stroke");


                                    reader.MoveToElement();
                                    //绘图元元素
                                    psymbol.brush = Brushes.SkyBlue;
                                    istext        = true;
                                }
                                break;
                            }
                        }
                        break;

                    case "g":
                        depth = reader.Depth;
                        if (reader.HasAttributes)
                        {
                            reader.MoveToAttribute("id");
                            layer = reader.Value;
                            reader.MoveToElement();

                            //开始一个层,在uc.objmanager中创建一个层
                            player = uc.objManager.AddLayer(layer, layer, layer);
                        }
                        while (reader.Read())
                        {
                            if (reader.Depth == depth && reader.NodeType == XmlNodeType.EndElement)
                            {
                                break;
                            }

                            if (reader.Name == "use" && reader.NodeType == XmlNodeType.Element)
                            {
                                shapetype = "dot";
                                id        = getPropertyValue(reader, "id");
                                fill      = getPropertyValue(reader, "fill");
                                stroke    = getPropertyValue(reader, "stroke");
                                symbol    = getPropertyValue(reader, "xlink:href");
                                zclass    = getPropertyValue(reader, "class");
                                //data = getPropertyValue(reader, "transform");
                                double x = double.Parse(getPropertyValue(reader, "x"));
                                double y = double.Parse(getPropertyValue(reader, "y"));
                                double w = double.Parse(getPropertyValue(reader, "width"));
                                double h = double.Parse(getPropertyValue(reader, "height"));
                                reader.MoveToElement();



                                //点类对象,此处示例代码假定点对象使用了图元
                                symbol = symbol.Replace("#", "");
                                double aspect = uc.objManager.zSymbols[symbol].sizeX / uc.objManager.zSymbols[symbol].sizeY;      //从图元取宽高比

                                pSymbolObject obj = new pSymbolObject(player)
                                {
                                    id            = id,
                                    name          = id,
                                    planeLocation = (new Point(x + w / 2, y + h / 2)).ToString(), //注:应赋值到planeLocation(平面坐标用),而不是location(经纬度坐标用),另外,校验位置到中心点
                                    symbolid      = symbol,
                                    scaleX        = 0.005f,                                       //  0.005为从svg平面空间到3D空间的缩放系数,可自行调整大小
                                    scaleY        = (float)(0.005 * aspect),
                                    color         = Colors.LightBlue,
                                    isH           = true
                                };
                                player.AddObject(id, obj);
                            }
                            else if (reader.Name == "path" && reader.NodeType == XmlNodeType.Element)
                            {
                                shapetype = "path";
                                id        = getPropertyValue(reader, "id");
                                fill      = getPropertyValue(reader, "fill");
                                stroke    = getPropertyValue(reader, "stroke");
                                width     = getPropertyValue(reader, "stroke-width");
                                data      = getPropertyValue(reader, "d");
                                zclass    = getPropertyValue(reader, "class");
                                reader.MoveToElement();

                                //线对象
                                if (!string.IsNullOrWhiteSpace(id))
                                {
                                    pPowerLine obj = new pPowerLine(player)
                                    {
                                        id        = id,
                                        name      = id,
                                        color     = Color.FromRgb(0xFF, 0x66, 0x00),
                                        isFlow    = true,   //是否显示潮流
                                        thickness = 0.002f, //线宽
                                        arrowSize = 0.005f  //潮流箭头大小
                                    };
                                    // 处理path短写,生成点集,对更复杂的短写,需借助path对象生成点集
                                    string tmp = data;
                                    tmp = tmp.Replace("M", "");
                                    string[] ps     = tmp.Split('L');
                                    string   points = "";
                                    int      idx    = 0;
                                    foreach (string s in ps)
                                    {
                                        if (idx != 0)
                                        {
                                            points += " ";
                                        }
                                        Point pt = Point.Parse(s);
                                        points += pt.ToString();
                                        idx++;
                                    }

                                    //zh注:对不合理的过近的相邻点进行处理,必须进行此步检查,否则在3D空间不能正常生成3D线条
                                    PointCollection pc    = PointCollection.Parse(points);
                                    PointCollection newpc = new PointCollection();
                                    newpc.Add(pc[0]);
                                    for (int i = 1; i < pc.Count; i++)
                                    {
                                        if ((pc[i] - pc[i - 1]).Length > 20)
                                        {
                                            if (i < pc.Count - 1)
                                            {
                                                Vector v1 = pc[i] - pc[i - 1]; v1.Normalize();
                                                Vector v2 = pc[i + 1] - pc[i]; v2.Normalize();
                                                if (v1 != v2)
                                                {
                                                    newpc.Add(pc[i]);
                                                }
                                            }
                                            else
                                            {
                                                newpc.Add(pc[i]);
                                            }
                                        }
                                    }
                                    (obj as pPowerLine).strPoints = newpc.ToString();

                                    obj.planeStrPoints = newpc.ToString();     // //注:应赋值到planeStrPoints,而不是strPoints
                                    if (newpc.Count > 1)
                                    {
                                        player.pModels.Add(id, obj);
                                    }


                                    //处理潮流,在本demo中,ConnectNode_Layer层中的线不显示潮流箭头
                                    if (player.id == "ConnectNode_Layer")
                                    {
                                        obj.isFlow = false;
                                    }
                                }
                            }
                            else if (reader.Name == "text" && reader.NodeType == XmlNodeType.Element)
                            {
                                stroke = getPropertyValue(reader, "stroke");
                                double x          = double.Parse(getPropertyValue(reader, "x"));
                                double y          = double.Parse(getPropertyValue(reader, "y"));
                                string fontfamily = getPropertyValue(reader, "font-family");
                                string fontsize   = getPropertyValue(reader, "font-size");
                                zclass = getPropertyValue(reader, "class");
                                reader.Read();
                                string text = reader.Value;

                                reader.MoveToElement();
                                if (text == "线")
                                {
                                }

                                //文字对象
                                double w       = 40; // w 和 h用来修正位置
                                double h       = -10;
                                float  scalexy = float.Parse(fontsize) / 16f * 0.8f;
                                if (player.id == "Text_Layer")
                                {
                                    pText obj = new pText(player)
                                    {
                                        id            = Helpler.getGUID(), //生成guid串,确保key值唯一
                                        name          = text,
                                        text          = text,
                                        planeLocation = (new Point(x + w / 2, y + h / 2)).ToString(), //注:应赋值到planeLocation(平面坐标用),而不是location(经纬度坐标用),另外,校验位置到中心点
                                        isH           = true,                                         //是否水平放置
                                        color         = Colors.White,
                                        scaleX        = scalexy,
                                        scaleY        = scalexy,
                                    };
                                    player.AddObject(text, obj);
                                }
                            }
                            else if (reader.Name == "rect" && reader.NodeType == XmlNodeType.Element)
                            {
                                fill   = getPropertyValue(reader, "fill");
                                stroke = getPropertyValue(reader, "stroke");
                                double x = double.Parse(getPropertyValue(reader, "x"));
                                double y = double.Parse(getPropertyValue(reader, "y"));
                                double w = double.Parse(getPropertyValue(reader, "width"));
                                double h = double.Parse(getPropertyValue(reader, "height"));

                                reader.Read();

                                reader.MoveToElement();

                                //厂站对象
                                if (player.id == "Other_Layer")
                                {
                                    pSymbolObject obj = new pSymbolObject(player)
                                    {
                                        id            = Helpler.getGUID(),                            //生成guid串,确保key值唯一
                                        planeLocation = (new Point(x + w / 2, y + h / 2)).ToString(), //注:应赋值到planeLocation(平面坐标用),而不是location(经纬度坐标用),另外,校验位置到中心点
                                        isH           = true,
                                        brush         = Brushes.White,
                                        color         = Colors.Red,
                                        scaleX        = (float)(w * 0.0005), //0.0005为映射到3D空间的尺寸调整系数
                                        scaleY        = (float)(h * 0.0005)
                                    };
                                    player.AddObject(obj.id, obj);
                                }
                            }
                        }

                        break;
                    }
                }
            }

            //==============清理空白层
            int idxi = 0;

            while (idxi < uc.objManager.zLayers.Count)
            {
                if (uc.objManager.zLayers.Values.ElementAt(idxi).pModels.Count == 0)
                {
                    uc.objManager.zLayers.Remove(uc.objManager.zLayers.Keys.ElementAt(idxi));
                }
                else
                {
                    idxi++;
                }
            }
        }
Пример #7
0
        private void UpdateProfileStackBackground(FrameworkElement item)
        {
            selected_item = item;

            if (selected_item != null)
            {
                DrawingBrush    mask           = new DrawingBrush();
                GeometryDrawing visible_region =
                    new GeometryDrawing(
                        new SolidColorBrush(Color.FromArgb(64, 0, 0, 0)),
                        null,
                        new RectangleGeometry(new Rect(0, 0, profiles_background.ActualWidth, profiles_background.ActualHeight)));

                DrawingGroup drawingGroup = new DrawingGroup();
                drawingGroup.Children.Add(visible_region);

                Point relativePoint = selected_item.TransformToAncestor(profiles_background)
                                      .Transform(new Point(0, 0));

                double x      = 0.0D;
                double y      = relativePoint.Y - 2.0D;
                double width  = profiles_background.ActualWidth;
                double height = selected_item.ActualHeight + 4.0D;

                if (item.Parent != null && item.Parent.Equals(profiles_stack))
                {
                    Point relativePointWithinStack = profiles_stack.TransformToAncestor(profiles_background)
                                                     .Transform(new Point(0, 0));

                    if (y < relativePointWithinStack.Y)
                    {
                        height -= relativePointWithinStack.Y - y;
                        y       = 0;
                    }
                    else if (y + height > profiles_background.ActualHeight - 40)
                    {
                        height -= (y + height) - (profiles_background.ActualHeight - 40);
                    }
                }
                else
                {
                    x      = 0.0D;
                    y      = relativePoint.Y - 2.0D;
                    width  = profiles_background.ActualWidth;
                    height = selected_item.ActualHeight + 4.0D;

                    if (y + height > profiles_background.ActualHeight - 40)
                    {
                        height -= (y + height) - (profiles_background.ActualHeight - 40);
                    }
                }

                if (height > 0 && width > 0)
                {
                    GeometryDrawing transparent_region =
                        new GeometryDrawing(
                            new SolidColorBrush((Color)current_color),
                            null,
                            new RectangleGeometry(new Rect(x, y, width, height)));

                    drawingGroup.Children.Add(transparent_region);
                }

                mask.Drawing = drawingGroup;

                profiles_background.Background = mask;
            }
        }
Пример #8
0
        private void UpdateUIRepresentation()
        {
            if (isUpdating)
            {
                return;
            }

            if (plotter == null)
            {
                return;
            }

            IPointDataSource dataSource = DataSource;

            if (dataSource == null)
            {
                return;
            }

            visibleWhileUpdate = plotter.Viewport.Visible;

            isUpdating = true;

            panel.Children.Clear();

            DependencyObject dependencyDataSource = dataSource as DependencyObject;

            if (dependencyDataSource != null)
            {
                DataSource2dContext.SetVisibleRect(dependencyDataSource, plotter.Viewport.Visible);
                DataSource2dContext.SetScreenRect(dependencyDataSource, plotter.Viewport.Output);
            }

            IEnumerable <Point> viewportPoints = dataSource;

            var transform = plotter.Viewport.Transform;

            if (!(transform.DataTransform is IdentityTransform))
            {
                viewportPoints = dataSource.DataToViewport(transform.DataTransform);
            }

            var screenPoints   = viewportPoints.ViewportToScreen(transform);
            var filteredPoints = filters.Filter(screenPoints, plotter.Viewport);

            DataRect bounds = DataRect.Empty;

            double strokeThickness = 3;

            bool  first = true;
            Point lastPointOfPrevLine = new Point();

            int overallCount = 0;

            panel.BeginBatchAdd();

            const int ptsInPolyline = 500;

            foreach (var pointGroup in filteredPoints.Split(ptsInPolyline))
            {
                int ptsCount = ptsInPolyline;

                if (!first)
                {
                    ptsCount++;
                }

                PointCollection pointCollection = new PointCollection(ptsCount);

                if (!first)
                {
                    pointCollection.Add(lastPointOfPrevLine);
                }
                else
                {
                    first = false;
                }

                pointCollection.AddMany(pointGroup);

                overallCount += pointCollection.Count - 1;

                if (pointCollection.Count == 0)
                {
                    break;
                }

                lastPointOfPrevLine = pointCollection[pointCollection.Count - 1];

                pointCollection.Freeze();

                DataRect ithBounds = BoundsHelper.GetViewportBounds(pointCollection.ScreenToViewport(transform));
#if geom
                UIElement line = null;

                StreamGeometry geometry = new StreamGeometry();
                using (var dc = geometry.Open())
                {
                    dc.BeginFigure(pointCollection[0], false, false);
                    dc.PolyLineTo(pointCollection, true, false);
                }
                geometry.Freeze();
                GeometryDrawing drawing = new GeometryDrawing {
                    Geometry = geometry, Pen = new Pen(Brushes.Blue, 1)
                };
                drawing.Freeze();
                DrawingBrush brush = new DrawingBrush {
                    Drawing = drawing
                };
                brush.Freeze();

                var rectangle = new Rectangle {
                    Fill = brush, IsHitTestVisible = false
                };
                Rect ithScreenBounds = ithBounds.ViewportToScreen(transform);
                if (true || ithScreenBounds.Width > 2000 || ithScreenBounds.Height > 2000 || ithScreenBounds.Width < 1 || ithScreenBounds.Height < 1)
                {
                    line = rectangle;
                }
                else
                {
                    Size intSize = new Size((int)ithScreenBounds.Width, (int)ithScreenBounds.Height);
                    rectangle.Measure(intSize);
                    rectangle.Arrange(new Rect(intSize));

                    RenderTargetBitmap renderBitmap = new RenderTargetBitmap((int)ithScreenBounds.Width, (int)ithScreenBounds.Height, 96, 96, PixelFormats.Pbgra32);
                    renderBitmap.Render(rectangle);
                    renderBitmap.Freeze();
                    line = new Image {
                        Source = renderBitmap
                    };
                }
#else
                var line = CreateLine();
                line.Points = pointCollection;
#endif

                bounds.Union(ithBounds);

                ViewportRectPanel.SetViewportBounds(line, ithBounds);
#if !geom
                ViewportMarginPanel.SetScreenMargin(line, new Size(strokeThickness / 2, strokeThickness / 2));
#endif
                panel.Children.Add(line);

                isUpdating = false;
            }

            panel.EndBatchAdd();

            Debug.WriteLine("OverallCount = " + (overallCount + 1));

            Viewport2D.SetContentBounds(this, bounds);

            isUpdating = false;
        }
Пример #9
0
        public void NextFrame(object sender, EventArgs e)
        {
            frameTimer.Stop();
            if (_numberOfFrames == 0)
            {
                return;
            }
            if (_frameList[_frameCounter].disposalMethod == 2)
            {
                // dispose = background, tricky code to make transparent last frames region
                for (int fc = 0; fc < _frameCounter; fc++)
                {
                    if (_frameList[fc].Visibility == Visibility.Visible)
                    {
                        GifFrame          gf  = _frameList[_frameCounter];
                        RectangleGeometry rg2 = new RectangleGeometry(new Rect(gf.left, gf.top, gf.width, gf.height));
                        totalTransparentGeometry = new CombinedGeometry(GeometryCombineMode.Union, totalTransparentGeometry, rg2);

                        GifFrame          gfBack = _frameList[fc];
                        RectangleGeometry rgBack = new RectangleGeometry(new Rect(gfBack.left, gfBack.top, gfBack.width, gfBack.height));
                        CombinedGeometry  cg     = new CombinedGeometry(GeometryCombineMode.Exclude, rgBack, totalTransparentGeometry);
                        GeometryDrawing   gd     = new GeometryDrawing(Brushes.Black, new Pen(Brushes.Black, 0), cg);
                        DrawingBrush      db     = new DrawingBrush(gd);
                        _frameList[fc].OpacityMask = db;
                    }
                }

                _frameList[_frameCounter].Visibility = Visibility.Hidden;
            }
            if (_frameList[_frameCounter].disposalMethod >= 3)
            {
                _frameList[_frameCounter].Visibility = Visibility.Hidden;
            }
            _frameCounter++;

            if (_frameCounter < _numberOfFrames)
            {
                _frameList[_frameCounter].Visibility = Visibility.Visible;
                frameTimer.Interval = new TimeSpan(0, 0, 0, 0, _frameList[_frameCounter].delayTime * 10);
                frameTimer.Start();
            }
            else
            {
                if (_numberOfLoops != 0)
                {
                    _currentLoop++;
                }
                if (_currentLoop < _numberOfLoops || _numberOfLoops == 0)
                {
                    for (int f = 0; f < _frameList.Count; f++)
                    {
                        _frameList[f].Visibility  = Visibility.Hidden;
                        _frameList[f].OpacityMask = null;
                    }
                    totalTransparentGeometry             = null;
                    _frameCounter                        = 0;
                    _frameList[_frameCounter].Visibility = Visibility.Visible;
                    frameTimer.Interval                  = new TimeSpan(0, 0, 0, 0, _frameList[_frameCounter].delayTime * 10);
                    frameTimer.Start();
                }
            }
        }
Пример #10
0
 public static void SetDeselectedDrawingBrush(DependencyObject obj, DrawingBrush value)
 {
     obj.SetValue(Icon.DeselectedDrawingBrushProperty, (object)value);
 }
Пример #11
0
 /// <summary>
 /// Sets the selected drawing brush</summary>
 /// <param name="obj">Dependency object to query for the property</param>
 /// <param name="value">Value to set</param>
 public static void SetSelectedDrawingBrush(DependencyObject obj, DrawingBrush value)
 {
     obj.SetValue(SelectedDrawingBrushProperty, value);
 }
Пример #12
0
        public override void Render(WpfDrawingRenderer renderer)
        {
            WpfDrawingContext context = renderer.Context;

            SvgRenderingHint hint = _svgElement.RenderingHint;

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

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

            SvgStyleableElement styleElm = (SvgStyleableElement)_svgElement;

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

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

            DrawingGroup drawGroup = context.Peek();

            Debug.Assert(drawGroup != null);

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

            string elementId = this.GetElementName();

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

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

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

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

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

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

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

                    if (!string.IsNullOrWhiteSpace(elementId) && !context.IsRegisteredId(elementId))
                    {
                        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)
                        {
                            DrawingBrush drawingBrush = (DrawingBrush)maskBrush;

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

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

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

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

                                    Matrix matrix = new Matrix();
                                    matrix.Scale(drawingBounds.Width, drawingBounds.Height);
                                    matrix.Translate(drawingBounds.X, drawingBounds.Y);

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

                                    drawingBrush.Stretch = Stretch.Uniform;

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

                            clipMaskGroup.OpacityMask = maskBrush;
                        }

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

            // If this is not the child of a "marker", then try rendering a marker...
            if (!string.Equals(parentNode.LocalName, "marker"))
            {
                RenderMarkers(renderer, styleElm, context);
            }
        }
Пример #13
0
        internal static Bitmap GetBitmapFromResource(string resourceString)
        {
            DrawingBrush drawingBrush = IconHelper.GetBrushFromResource(resourceString);

            return(CreateBitmapFromDrawingBrush(drawingBrush));
        }
Пример #14
0
        private void Hyperlink_Click(object sender, RoutedEventArgs e)
        {
            var hyperlink = (Hyperlink)sender;
            var vm        = (TaskAreaItemsViewModel)hyperlink.DataContext;

            var contextMenu = new ContextMenu {
                PlacementTarget = (UIElement)hyperlink.Parent, Placement = PlacementMode.Right, HorizontalOffset = 14, DataContext = vm,
                Style           = (Style)FindResource("TaskAreaContextMenuStyle")
            };

            bool prevWasGroup = false;

            foreach (TaskAreaViewModelBase item in vm.Items)
            {
                var group = item as TaskAreaCommandGroupViewModel;
                if (group != null)
                {
                    if (contextMenu.Items.Count > 0)
                    {
                        contextMenu.Items.Add(new Separator {
                            Style = (Style)FindResource("TaskAreaSeparatorStyle")
                        });
                    }

                    foreach (TaskAreaCommandViewModel command in group.Commands)
                    {
                        var menuItem = new MenuItem {
                            Header = command.DisplayName, Command = command.Command, DataContext = command, Tag = group, Style = (Style)FindResource("TaskAreaMenuItemStyle")
                        };
                        menuItem.Click += menuItem_Click;
                        if (command == group.SelectedCommand)
                        {
                            var geometry     = new EllipseGeometry(new Point(0, 0), 3, 3);
                            var drawingBrush = new DrawingBrush(new GeometryDrawing {
                                Brush = Brushes.Black, Geometry = geometry
                            })
                            {
                                Stretch = Stretch.None
                            };
                            menuItem.Icon = new Image {
                                Source = new DrawingImage(drawingBrush.Drawing)
                            };
                        }
                        contextMenu.Items.Add(menuItem);
                    }
                    prevWasGroup = true;
                }
                else
                {
                    if (prevWasGroup)
                    {
                        contextMenu.Items.Add(new Separator {
                            Style = (Style)FindResource("TaskAreaSeparatorStyle")
                        });
                    }

                    prevWasGroup = false;
                    var command = item as TaskAreaCommandViewModel;
                    if (command != null)
                    {
                        var menuItem = new MenuItem {
                            Header = command.DisplayName, Command = command.Command, DataContext = command, Style = (Style)FindResource("TaskAreaMenuItemStyle")
                        };
                        contextMenu.Items.Add(menuItem);
                    }
                    else
                    {
                        var booleanItem = item as TaskAreaBooleanViewModel;
                        if (booleanItem != null)
                        {
                            var menuItem = new MenuItem {
                                Header = booleanItem.DisplayName, DataContext = booleanItem, Style = (Style)FindResource("TaskAreaMenuItemStyle"), IsCheckable = true
                            };
                            menuItem.SetBinding(MenuItem.IsCheckedProperty, "Value");
                            contextMenu.Items.Add(menuItem);
                        }
                    }
                }
            }
            contextMenu.IsOpen = true;
        }
Пример #15
0
        public void build()
        {
            if (string.IsNullOrWhiteSpace(serialName) || string.IsNullOrWhiteSpace(argumentName) || string.IsNullOrWhiteSpace(valueName) || dataSource == null || !this.IsLoaded)
            {
                return;
            }

            this.Children.Clear();

            //背景板
            this.Children.Add(panel);
            //标题
            this.Children.Add(title);

            this.Children.Add(rect);
            drawingGroup          = new DrawingGroup();
            drawingBrush          = new DrawingBrush(drawingGroup);
            rect.Background       = drawingBrush;
            rect.IsHitTestVisible = false;

            double edgeLength = Math.Min(this.ActualHeight, this.ActualWidth) - padding;
            Vector orgpoint   = new Vector(edgeLength / 2, edgeLength / 2);

            rect.Width = rect.Height = edgeLength;

            List <string> argues = dataSource.GroupBy(p => p.argu).Select(p => p.Key).ToList(); //所有的argu

            foreach (var item in dataSource)                                                    //计算项点位置
            {
                item.idx = argues.IndexOf(item.argu);
                double angle = Math.PI * 2 * item.idx / argues.Count;
                item.pnt = new Point(edgeLength * item.value / item.maxvalue * Math.Cos(angle), edgeLength * item.value / item.maxvalue * Math.Sin(angle)) + orgpoint;
            }

            List <string> sorts = dataSource.GroupBy(p => p.sort).Select(p => p.Key).ToList();

            //绘制网格
            GeometryDrawing gd;
            PathGeometry    geo;

            gd = new GeometryDrawing();
            RectangleGeometry geo2 = new RectangleGeometry();

            geo2.Rect   = new Rect(0, 0, edgeLength, edgeLength);
            gd.Brush    = Brushes.Transparent;
            gd.Geometry = geo2;
            drawingGroup.Children.Add(gd);

            //=== 背板
            gd          = new GeometryDrawing();
            geo         = new PathGeometry();
            gd.Geometry = geo;
            {
                PathFigure pf = new PathFigure();
                geo.Figures.Add(pf);
                PolyLineSegment ps = new PolyLineSegment();
                pf.Segments.Add(ps);

                for (int j = 0; j < argues.Count; j++)
                {
                    double angle = Math.PI * 2 * j / argues.Count + Math.PI / 2;
                    Point  pnt   = new Point(edgeLength / 2 * Math.Cos(angle), edgeLength / 2 * Math.Sin(angle)) + orgpoint;
                    if (j == 0)
                    {
                        pf.StartPoint = pnt;
                    }
                    else
                    {
                        ps.Points.Add(pnt);
                    }
                }
                ps.Points.Add(pf.StartPoint);
            }
            gd.Pen = new Pen()
            {
                Thickness = 1, Brush = Brushes.Green
            };
            gd.Brush = new SolidColorBrush(Color.FromArgb(0x80, 0x00, 0x34, 0x00));
            drawingGroup.Children.Add(gd);
            //=== 网格线
            gd          = new GeometryDrawing();
            geo         = new PathGeometry();
            gd.Geometry = geo;
            for (int i = 2; i < 3; i++)
            {
                PathFigure pf = new PathFigure();
                geo.Figures.Add(pf);
                PolyLineSegment ps = new PolyLineSegment();
                pf.Segments.Add(ps);

                for (int j = 0; j < argues.Count; j++)
                {
                    double angle = Math.PI * 2 * j / argues.Count + Math.PI / 2;
                    Point  pnt   = new Point(edgeLength / 2 * i * 0.25 * Math.Cos(angle), edgeLength / 2 * i * 0.25 * Math.Sin(angle)) + orgpoint;
                    if (j == 0)
                    {
                        pf.StartPoint = pnt;
                    }
                    else
                    {
                        ps.Points.Add(pnt);
                    }
                }
                ps.Points.Add(pf.StartPoint);
            }
            gd.Pen = new Pen()
            {
                Thickness = 1, Brush = Brushes.Green
            };
            drawingGroup.Children.Add(gd);
            //===放射线
            {
                gd          = new GeometryDrawing();
                geo         = new PathGeometry();
                gd.Geometry = geo;

                for (int j = 0; j < argues.Count; j++)
                {
                    PathFigure pf = new PathFigure();
                    geo.Figures.Add(pf);
                    LineSegment ps = new LineSegment();
                    pf.Segments.Add(ps);
                    pf.StartPoint = (Point)orgpoint;
                    double angle = Math.PI * 2 * j / argues.Count + Math.PI / 2;
                    ps.Point = new Point(edgeLength / 2 * Math.Cos(angle), edgeLength / 2 * Math.Sin(angle)) + orgpoint;

                    //----- 添加标签 -----
                    TextBlock txt = new TextBlock()
                    {
                        Text             = argues[j],
                        Foreground       = new SolidColorBrush(Colors.LawnGreen),
                        IsHitTestVisible = false
                    };
                    txt.Measure(new Size(0, 0));
                    txt.Arrange(new System.Windows.Rect(0, 0, 0, 0));
                    this.Children.Add(txt);
                    var       tmp  = dataSource.First(p => p.argu == argues[j]);
                    TextBlock txt2 = new TextBlock()
                    {
                        Text             = string.Format(tmp.format, tmp.maxvalue),
                        Foreground       = Brushes.Green,
                        IsHitTestVisible = false
                    };
                    txt2.Measure(new Size(0, 0));
                    txt2.Arrange(new System.Windows.Rect(0, 0, 0, 0));
                    this.Children.Add(txt2);
                    double offsetx, offsety;
                    offsetx = offsety = 0;
                    double maxtextlen = Math.Max(txt.ActualWidth, txt2.ActualWidth);
                    if (ps.Point.Y < orgpoint.Y - (edgeLength / 10))
                    {
                        offsety = -txt.ActualHeight - 1;
                    }
                    else if (ps.Point.Y > orgpoint.Y + (edgeLength / 10))
                    {
                        offsety = txt.ActualHeight + 1;
                    }
                    if (ps.Point.X < orgpoint.X - (edgeLength / 10))
                    {
                        offsetx = -maxtextlen / 2 - 1;
                    }
                    else if (ps.Point.X > orgpoint.X + (edgeLength / 10))
                    {
                        offsetx = maxtextlen / 2 + 1;
                    }
                    txt.Margin  = new Thickness(ps.Point.X - txt.ActualWidth / 2 + (this.ActualWidth - edgeLength) / 2 + offsetx, ps.Point.Y + (this.ActualHeight - edgeLength) / 2 + offsety, 0, 0);
                    txt2.Margin = new Thickness(ps.Point.X - txt2.ActualWidth / 2 + (this.ActualWidth - edgeLength) / 2 + offsetx, ps.Point.Y - txt2.ActualHeight + (this.ActualHeight - edgeLength) / 2 + offsety, 0, 0);
                    //----- 添加热线以显示tooltips -----
                    string tip = "【" + argues[j] + "】\r\n";
                    foreach (string sort in sorts)
                    {
                        RadarDataItem rad = dataSource.First(p => p.sort == sort && p.argu == argues[j]);
                        tip += (sort + ":" + string.Format(rad.format, rad.value));
                        if (sort != sorts.Last())
                        {
                            tip += "\r\n";
                        }
                    }
                    Line lin = new Line()
                    {
                        Stroke          = Brushes.Transparent,
                        StrokeThickness = 20,
                        X1      = orgpoint.X + (this.ActualWidth - edgeLength) / 2,
                        Y1      = orgpoint.Y + (this.ActualHeight - edgeLength) / 2,
                        X2      = ps.Point.X + (this.ActualWidth - edgeLength) / 2,
                        Y2      = ps.Point.Y + (this.ActualHeight - edgeLength) / 2,
                        ToolTip = tip,
                    };
                    this.Children.Add(lin);
                }


                gd.Pen = new Pen()
                {
                    Thickness = 1, Brush = Brushes.Green
                };
                drawingGroup.Children.Add(gd);
            }
            //===业务图形
            StackPanel spanel = new StackPanel() //图例容器
            {
                Orientation         = Orientation.Horizontal,
                VerticalAlignment   = System.Windows.VerticalAlignment.Bottom,
                HorizontalAlignment = System.Windows.HorizontalAlignment.Center,
                Margin = new Thickness(0, 0, 0, 5),
            };

            this.Children.Add(spanel);


            int idx = 0;

            foreach (string sort in sorts)
            {
                gd          = new GeometryDrawing();
                geo         = new PathGeometry();
                gd.Geometry = geo;
                PathFigure pf = new PathFigure();
                geo.Figures.Add(pf);
                PolyLineSegment ps = new PolyLineSegment();
                pf.Segments.Add(ps);
                foreach (var item in dataSource.Where(p => p.sort == sort).OrderBy(p => p.idx))
                {
                    double angle = Math.PI * 2 * item.idx / argues.Count + Math.PI / 2;
                    Point  pnt   = new Point(edgeLength / 2 * item.value / item.maxvalue * Math.Cos(angle), edgeLength / 2 * item.value / item.maxvalue * Math.Sin(angle)) + orgpoint;
                    if (item.idx == 0)
                    {
                        pf.StartPoint = pnt;
                    }
                    else
                    {
                        ps.Points.Add(pnt);
                    }
                }

                ps.Points.Add(pf.StartPoint);
                gd.Pen = idx < pens.Count ? pens[idx] :(new Pen()
                {
                    Thickness = 1, Brush = Brushes.Lime
                });
                drawingGroup.Children.Add(gd);
                //----- 图例
                spanel.Children.Add(new Rectangle()
                {
                    Width             = 10,
                    Height            = 10,
                    VerticalAlignment = System.Windows.VerticalAlignment.Center,
                    Fill   = idx < pens.Count ? pens[idx].Brush : Brushes.Lime,
                    Stroke = Brushes.Silver,
                    Margin = new Thickness(12, 0, 3, 0)
                });
                spanel.Children.Add(new TextBlock()
                {
                    Text       = sort,
                    Foreground = Brushes.Silver,
                });



                idx++;
            }
            //----- 标志点 -----
            idx = 0;
            foreach (string sort in sorts)
            {
                foreach (var item in dataSource.Where(p => p.sort == sort).OrderBy(p => p.idx))
                {
                    double angle = Math.PI * 2 * item.idx / argues.Count + Math.PI / 2;
                    Point  pnt   = new Point(edgeLength / 2 * item.value / item.maxvalue * Math.Cos(angle), edgeLength / 2 * item.value / item.maxvalue * Math.Sin(angle)) + orgpoint;

                    GeometryDrawing gddot  = new GeometryDrawing();
                    EllipseGeometry geodot = new EllipseGeometry();
                    gddot.Geometry = geodot;
                    geodot.Center  = pnt;
                    geodot.RadiusX = geodot.RadiusY = 2;
                    gddot.Brush    = Brushes.Red;
                    gddot.Pen      = new Pen()
                    {
                        Thickness = 1, Brush = Brushes.White
                    };
                    drawingGroup.Children.Add(gddot);
                }
            }
        }
Пример #16
0
 /// <summary>Inspects a drawing brush and replaces dynamically bound Brush resources with the provided ones</summary>
 /// <param name="drawing">Drawing Brush</param>
 /// <param name="replacementBrushes">Dictionary of replacement brushes</param>
 /// <remarks>This helper function is useful for loading assets such as icons and make them take on the local brushes</remarks>
 public static void ReplaceDynamicDrawingBrushResources(DrawingBrush drawing, Dictionary <object, Brush> replacementBrushes)
 {
     If.Real <DrawingGroup>(drawing.Drawing, group => InspectDrawingGroup(@group, replacementBrushes));
 }
        public BitmapEffectExample()
        {
            //
            // Create a DrawingGroup
            // that has no BitmapEffect
            //
            PathFigure pLineFigure = new PathFigure();

            pLineFigure.StartPoint = new Point(25, 25);
            PolyLineSegment pLineSegment = new PolyLineSegment();

            pLineSegment.Points.Add(new Point(0, 50));
            pLineSegment.Points.Add(new Point(25, 75));
            pLineSegment.Points.Add(new Point(50, 50));
            pLineSegment.Points.Add(new Point(25, 25));
            pLineSegment.Points.Add(new Point(25, 0));
            pLineFigure.Segments.Add(pLineSegment);
            PathGeometry pGeometry = new PathGeometry();

            pGeometry.Figures.Add(pLineFigure);

            GeometryDrawing drawing1 = new GeometryDrawing(
                Brushes.Lime,
                new Pen(Brushes.Black, 10),
                pGeometry
                );

            GeometryDrawing drawing2 = new GeometryDrawing(
                Brushes.Lime,
                new Pen(Brushes.Black, 2),
                new EllipseGeometry(new Point(10, 10), 5, 5)
                );

            // Create a DrawingGroup
            DrawingGroup drawingGroupWithoutBitmapEffect = new DrawingGroup();

            drawingGroupWithoutBitmapEffect.Children.Add(drawing1);
            drawingGroupWithoutBitmapEffect.Children.Add(drawing2);

            // Use an Image control and a DrawingImage to
            // display the drawing.
            DrawingImage drawingImage01 = new DrawingImage(drawingGroupWithoutBitmapEffect);

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

            Image image01 = new Image();

            image01.Source              = drawingImage01;
            image01.Stretch             = Stretch.None;
            image01.HorizontalAlignment = HorizontalAlignment.Left;

            //
            // Create another DrawingGroup and apply
            // a blur effect to it.
            //

            // Create a clone of the first DrawingGroup.
            DrawingGroup drawingGroupWithBitmapEffect =
                drawingGroupWithoutBitmapEffect.Clone();

            // Create a blur effect.
            BlurBitmapEffect blurEffect = new BlurBitmapEffect();

            blurEffect.Radius = 3.0;

            // Apply it to the drawing group.
            drawingGroupWithBitmapEffect.BitmapEffect = blurEffect;

            // Use another Image control and DrawingImage
            // to display the drawing.
            DrawingImage drawingImage02 = new DrawingImage(drawingGroupWithBitmapEffect);

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

            Image image02 = new Image();

            image02.Source              = drawingImage02;
            image02.Stretch             = Stretch.None;
            image02.HorizontalAlignment = HorizontalAlignment.Left;

            // Create borders around the images and add them to the
            // page.
            Border border01 = new Border();

            border01.BorderBrush       = Brushes.Gray;
            border01.BorderThickness   = new Thickness(1);
            border01.VerticalAlignment = VerticalAlignment.Top;
            border01.Margin            = new Thickness(10);
            border01.Child             = image01;

            Border border02 = new Border();

            border02.BorderBrush       = Brushes.Gray;
            border02.BorderThickness   = new Thickness(1);
            border02.VerticalAlignment = VerticalAlignment.Top;
            border02.Margin            = new Thickness(50, 10, 10, 10);
            border02.Child             = image02;

            StackPanel mainPanel = new StackPanel();

            mainPanel.Orientation         = Orientation.Horizontal;
            mainPanel.HorizontalAlignment = HorizontalAlignment.Left;
            mainPanel.VerticalAlignment   = VerticalAlignment.Top;
            mainPanel.Children.Add(border01);
            mainPanel.Children.Add(border02);

            //
            // Use a DrawingBrush to create a checkered background for the page.
            //
            GeometryDrawing backgroundSquareDrawing =
                new GeometryDrawing(
                    Brushes.White,
                    null,
                    new RectangleGeometry(new Rect(0, 0, 1, 1)));
            GeometryGroup twoRectangles = new GeometryGroup();

            twoRectangles.Children.Add(new RectangleGeometry(new Rect(0, 0, 0.5, 0.5)));
            twoRectangles.Children.Add(new RectangleGeometry(new Rect(0.5, 0.5, 0.5, 0.5)));
            SolidColorBrush squaresBrush =
                new SolidColorBrush(Color.FromArgb(102, 204, 204, 204));

            squaresBrush.Opacity = 0.4;
            GeometryDrawing checkerDrawing =
                new GeometryDrawing(
                    squaresBrush,
                    null,
                    twoRectangles);
            DrawingGroup checkerDrawings = new DrawingGroup();

            checkerDrawings.Children.Add(backgroundSquareDrawing);
            checkerDrawings.Children.Add(checkerDrawing);
            DrawingBrush checkerBrush = new DrawingBrush(checkerDrawings);

            checkerBrush.Viewport      = new Rect(0, 0, 10, 10);
            checkerBrush.ViewportUnits = BrushMappingMode.Absolute;
            checkerBrush.TileMode      = TileMode.Tile;
            checkerBrush.Freeze();

            this.Background = checkerBrush;
            this.Content    = mainPanel;
        }
Пример #18
0
 public ConvertibleDrawingBrush(DrawingBrush drawingBrush, string projectPath)
     : base(drawingBrush.Drawing, projectPath)
 {
     this.startDrawingBrush = drawingBrush;
 }
Пример #19
0
        public TileBrushAlignmentExample()
        {
            // <SnippetTileBrushTopLeftAlignmentInline>
            //
            // Create a TileBrush and align its
            // content to the top-left of its tile.
            //
            DrawingBrush topLeftAlignedTileBrush = new DrawingBrush();

            topLeftAlignedTileBrush.AlignmentX = AlignmentX.Left;
            topLeftAlignedTileBrush.AlignmentY = AlignmentY.Top;

            // Set Stretch to None so that the brush's
            // content doesn't automatically expand to
            // fill the entire tile.
            topLeftAlignedTileBrush.Stretch = Stretch.None;

            // Define the brush's content.
            GeometryGroup ellipses = new GeometryGroup();

            ellipses.Children.Add(new EllipseGeometry(new Point(50, 50), 20, 45));
            ellipses.Children.Add(new EllipseGeometry(new Point(50, 50), 45, 20));
            Pen             drawingPen     = new Pen(Brushes.Gray, 10);
            GeometryDrawing ellipseDrawing = new GeometryDrawing(Brushes.Blue, drawingPen, ellipses);

            topLeftAlignedTileBrush.Drawing = ellipseDrawing;

            // Use the brush to paint a rectangle.
            Rectangle rectangle1 = new Rectangle();

            rectangle1.Width           = 150;
            rectangle1.Height          = 150;
            rectangle1.Stroke          = Brushes.Red;
            rectangle1.StrokeThickness = 2;
            rectangle1.Margin          = new Thickness(20);
            rectangle1.Fill            = topLeftAlignedTileBrush;

            // </SnippetTileBrushTopLeftAlignmentInline>

            // <SnippetTileBrushBottomRightAlignmentInline>
            //
            // Create a TileBrush and align its
            // content to the bottom-right of its tile.
            //
            DrawingBrush bottomRightAlignedTileBrush = new DrawingBrush();

            bottomRightAlignedTileBrush.AlignmentX = AlignmentX.Right;
            bottomRightAlignedTileBrush.AlignmentY = AlignmentY.Bottom;
            bottomRightAlignedTileBrush.Stretch    = Stretch.None;

            // Define the brush's content.
            bottomRightAlignedTileBrush.Drawing = ellipseDrawing;

            // Use the brush to paint a rectangle.
            Rectangle rectangle2 = new Rectangle();

            rectangle2.Width           = 150;
            rectangle2.Height          = 150;
            rectangle2.Stroke          = Brushes.Red;
            rectangle2.StrokeThickness = 2;
            rectangle2.Margin          = new Thickness(20);
            rectangle2.Fill            = bottomRightAlignedTileBrush;

            // </SnippetTileBrushBottomRightAlignmentInline>

            // <SnippetTileBrushTopLeftAlignmentTiledInline>
            //
            // Create a TileBrush that generates a
            // tiled pattern and align its
            // content to the top-left of its tile.
            //
            DrawingBrush tiledTopLeftAlignedTileBrush = new DrawingBrush();

            tiledTopLeftAlignedTileBrush.AlignmentX = AlignmentX.Left;
            tiledTopLeftAlignedTileBrush.AlignmentY = AlignmentY.Top;
            tiledTopLeftAlignedTileBrush.Stretch    = Stretch.Uniform;

            // Set the brush's Viewport and TileMode to produce a
            // tiled pattern.
            tiledTopLeftAlignedTileBrush.Viewport = new Rect(0, 0, 0.25, 0.5);
            tiledTopLeftAlignedTileBrush.TileMode = TileMode.Tile;

            // Define the brush's content.
            tiledTopLeftAlignedTileBrush.Drawing = ellipseDrawing;

            // Use the brush to paint a rectangle.
            Rectangle rectangle3 = new Rectangle();

            rectangle3.Width           = 150;
            rectangle3.Height          = 150;
            rectangle3.Stroke          = Brushes.Black;
            rectangle3.StrokeThickness = 2;
            rectangle3.Margin          = new Thickness(20);
            rectangle3.Fill            = tiledTopLeftAlignedTileBrush;

            // </SnippetTileBrushTopLeftAlignmentTiledInline>

            // <SnippetTileBrushBottomRightAlignmentTiledInline>
            //
            // Create a TileBrush that generates a
            // tiled pattern and align its
            // content to the bottom-right of its tile.
            //
            DrawingBrush tiledBottomRightAlignedTileBrush = new DrawingBrush();

            tiledBottomRightAlignedTileBrush.AlignmentX = AlignmentX.Right;
            tiledBottomRightAlignedTileBrush.AlignmentY = AlignmentY.Bottom;
            tiledBottomRightAlignedTileBrush.Stretch    = Stretch.Uniform;

            // Set the brush's Viewport and TileMode to produce a
            // tiled pattern.
            tiledBottomRightAlignedTileBrush.Viewport = new Rect(0, 0, 0.25, 0.5);
            tiledBottomRightAlignedTileBrush.TileMode = TileMode.Tile;

            // Define the brush's content.
            tiledBottomRightAlignedTileBrush.Drawing = ellipseDrawing;

            // Use the brush to paint a rectangle.
            Rectangle rectangle4 = new Rectangle();

            rectangle4.Width           = 150;
            rectangle4.Height          = 150;
            rectangle4.Stroke          = Brushes.Black;
            rectangle4.StrokeThickness = 2;
            rectangle4.Margin          = new Thickness(20);
            rectangle4.Fill            = tiledBottomRightAlignedTileBrush;

            // </SnippetTileBrushBottomRightAlignmentTiledInline>

            StackPanel mainPanel = new StackPanel();

            mainPanel.Children.Add(rectangle1);
            mainPanel.Children.Add(rectangle2);
            mainPanel.Children.Add(rectangle3);
            mainPanel.Children.Add(rectangle4);
            Content    = mainPanel;
            Background = Brushes.White;
            Margin     = new Thickness(20);
            Title      = "Alignment Example";
        }
Пример #20
0
        /// <summary>
        /// Registers any attributed resource keys found on the type</summary>
        /// <param name="type">Type, usually a static set of keys</param>
        /// <param name="resourcePath">Path to resources</param>
        public static void Register(Type type, string resourcePath)
        {
            if (s_registeredTypes.Contains(type))
            {
                return;
            }

            s_registeredTypes.Add(type);

            // Generate packUri
            AssemblyName assmName            = type.Assembly.GetName();
            string       relativePackUriBase = "/" + assmName.Name + ";component/" + resourcePath;
            string       absolutePackUriBase = "pack://application:,,," + relativePackUriBase;

            ResourceDictionary imageResources = null;

            FieldInfo[] fields = type.GetFields(BindingFlags.Static | BindingFlags.Public);
            foreach (FieldInfo field in fields)
            {
                // Get Image attributes
                object[] attributes = field.GetCustomAttributes(typeof(WpfImageResourceAttribute), false);

                if (attributes.Length > 0)
                {
                    if (!field.FieldType.IsAssignableFrom(typeof(ResourceKey)))
                    {
                        System.Diagnostics.Debug.WriteLine("Warning: WpfImageResourceAttribute used on a field which is not a ResourceKey");
                    }

                    var       attribute = (WpfImageResourceAttribute)attributes[0];
                    Freezable img       = null;
                    string    extension = System.IO.Path.GetExtension(attribute.ImageName).ToLower();

                    if (extension == ".bmp" || extension == ".png" || extension == ".ico")
                    {
                        var uri = new Uri(absolutePackUriBase + attribute.ImageName);
                        try
                        {
                            img = new BitmapImage(uri);
                        }
                        catch (IOException ex)
                        {
                            System.Diagnostics.Debug.WriteLine(ex.Message);
                        }
                    }
                    else if (extension == ".xaml")
                    {
                        var uri = new Uri(relativePackUriBase + attribute.ImageName, UriKind.Relative);
                        img = Application.LoadComponent(uri) as Freezable;

                        if (img == null)
                        {
                            throw new InvalidOperationException("Invalid xaml image resource: " + attribute.ImageName);
                        }
                    }
                    else if (extension == ".cur")
                    {
                        var uri = new Uri(relativePackUriBase + attribute.ImageName, UriKind.Relative);

                        try
                        {
                            var info = Application.GetResourceStream(uri);
                            img = new FreezableCursor {
                                Cursor = new System.Windows.Input.Cursor(info.Stream)
                            };
                        }
                        catch (IOException ex)
                        {
                            System.Diagnostics.Debug.WriteLine(ex.Message);
                        }
                    }
                    else
                    {
                        throw new InvalidOperationException("Unrecognized Wpf image resource file extension for file: " + attribute.ImageName);
                    }

                    if (img != null)
                    {
                        // Might it be better to keep the img as a DrawingGroup and then assign to relevant Image type later?
                        if (img is DrawingGroup)
                        {
                            var brush = new DrawingBrush(img as DrawingGroup);
                            brush.Stretch = Stretch.Uniform;
                            img           = brush;
                        }

                        if (img.CanFreeze && !img.IsFrozen)
                        {
                            img.Freeze();
                        }

                        object imageKey = type.FullName + "." + attribute.ImageName;

                        if (field.FieldType.IsAssignableFrom(typeof(ResourceKey)))
                        {
                            imageKey = new ComponentResourceKey(type, imageKey);
                        }

                        field.SetValue(type, imageKey);

                        if (imageResources == null)
                        {
                            imageResources = new ResourceDictionary();
                        }

                        imageResources.Add(imageKey, img);
                    }
                }

                // Get ResourceDictionary attributes
                if (field.FieldType == typeof(string))
                {
                    attributes = field.GetCustomAttributes(typeof(ResourceDictionaryResourceAttribute), false);

                    if (attributes.Length > 0)
                    {
                        var attribute = attributes[0] as ResourceDictionaryResourceAttribute;

                        var    dictionary = new ResourceDictionary();
                        string uri        = absolutePackUriBase + attribute.Path;
                        dictionary.Source = new Uri(uri, UriKind.RelativeOrAbsolute);

                        Application.Current.Resources.MergedDictionaries.Add(dictionary);
                    }
                }
            }

            if (imageResources != null)
            {
                Application.Current.Resources.MergedDictionaries.Add(imageResources);
            }
        }
        public ImageDrawingWithDrawingBrushExample()
        {
            // Create a DrawingGroup to combine the ImageDrawing objects.
            DrawingGroup imageDrawings = new DrawingGroup();

            // Create a 100 by 100 image with an upper-left point of (75,75).
            ImageDrawing bigKiwi = new ImageDrawing();

            bigKiwi.Rect        = new Rect(75, 75, 100, 100);
            bigKiwi.ImageSource = new BitmapImage(
                new Uri(@"sampleImages\kiwi.png", UriKind.Relative));

            imageDrawings.Children.Add(bigKiwi);

            // Create a 25 by 25 image with an upper-left point of (0,150).
            ImageDrawing smallKiwi1 = new ImageDrawing();

            smallKiwi1.Rect        = new Rect(0, 150, 25, 25);
            smallKiwi1.ImageSource = new BitmapImage(new Uri(@"sampleImages\kiwi.png", UriKind.Relative));
            imageDrawings.Children.Add(smallKiwi1);

            // Create a 25 by 25 image with an upper-left point of (150,0).
            ImageDrawing smallKiwi2 = new ImageDrawing();

            smallKiwi2.Rect        = new Rect(150, 0, 25, 25);
            smallKiwi2.ImageSource = new BitmapImage(new Uri(@"sampleImages\kiwi.png", UriKind.Relative));
            imageDrawings.Children.Add(smallKiwi2);

            // Create a 75 by 75 image with an upper-left point of (0,0).
            ImageDrawing wholeKiwi = new ImageDrawing();

            wholeKiwi.Rect        = new Rect(0, 0, 75, 75);
            wholeKiwi.ImageSource = new BitmapImage(new Uri(@"sampleImages\wholekiwi.png", UriKind.Relative));
            imageDrawings.Children.Add(wholeKiwi);

            //
            // Use a DrawingBrush to paint a rectangle with
            // the drawings.
            //
            DrawingBrush dBrush = new DrawingBrush(imageDrawings);

            dBrush.Viewport = new Rect(0, 0, 0.5, 0.5);
            dBrush.TileMode = TileMode.Tile;
            dBrush.Freeze();

            Rectangle exampleRectangle = new Rectangle();

            exampleRectangle.Width  = 175;
            exampleRectangle.Height = 175;
            exampleRectangle.Fill   = dBrush;


            // Create a border to contain the rectangle.
            Border exampleBorder = new Border();

            exampleBorder.BorderBrush         = Brushes.Gray;
            exampleBorder.BorderThickness     = new Thickness(1);
            exampleBorder.HorizontalAlignment = HorizontalAlignment.Left;
            exampleBorder.VerticalAlignment   = VerticalAlignment.Top;
            exampleBorder.Margin = new Thickness(20);
            exampleBorder.Child  = exampleRectangle;

            this.Background = Brushes.White;
            this.Margin     = new Thickness(20);
            this.Content    = exampleBorder;
        }
Пример #22
0
        private void OuterBorder_MouseUp(object sender, MouseButtonEventArgs e)
        {
            WebModelingStaticClass.IsMainGridClik = true;
            Point pt = e.GetPosition(this);

            pt.Y = pt.Y;
            if (WebModelingStaticClass.ul.NewButton.IsSelected || IsUIChecked[0] == true)
            {
                UI_Button my = new UI_Button("Button", "이태릭체", "없음", 10);
                Rectangle r  = new Rectangle();
                Button    mq = new Button();
                r.RadiusX = 0;
                r.RadiusY = 0;
                //ImageBrush myBrush = new ImageBrush();
                //myBrush.ImageSource =
                //    new BitmapImage(new Uri(@"C:\Users\inhye\Desktop\1497330714590.jpg", UriKind.Relative));
                //r.Fill = myBrush;
                // r.Fill = new SolidColorBrush(Colors.Black);
                VisualBrush myBrush = new VisualBrush();
                StackPanel  aPanel  = new StackPanel();
                // Create a DrawingBrush and use it to
                // paint the panel.
                DrawingBrush  myDrawingBrushBrush = new DrawingBrush();
                GeometryGroup aGeometryGroup      = new GeometryGroup();
                aGeometryGroup.Children.Add(new RectangleGeometry(new Rect(0, 0, 50, 50)));
                //aGeometryGroup.Children.Add(new RectangleGeometry(new Rect(50, 50, 50, 50)));
                RadialGradientBrush checkerBrush = new RadialGradientBrush();
                checkerBrush.GradientStops.Add(new GradientStop(Colors.Gray, 0.0));
                //checkerBrush.GradientStops.Add(new GradientStop(Colors.White, 1.0));
                GeometryDrawing checkers = new GeometryDrawing(checkerBrush, null, aGeometryGroup);
                myDrawingBrushBrush.Drawing = checkers;
                aPanel.Background           = myDrawingBrushBrush;

                // Create some text.
                TextBlock someText = new TextBlock();
                someText.Text = "Button";
                FontSizeConverter fSizeConverter = new FontSizeConverter();
                someText.FontSize = (double)fSizeConverter.ConvertFromString("10pt");
                someText.Margin   = new Thickness(10);
                aPanel.Children.Add(someText);
                myBrush.Visual = aPanel;
                r.Fill         = myBrush;
                r.Fill.Opacity = 0.8;
                this.Add(r, my, pt);
                WebModelingStaticClass.ul.NewButton.IsSelected = false;
            }

            else if ((WebModelingStaticClass.ul.NewCheckBox.IsSelected) || IsUIChecked[1] == true)
            {
                UI_TextBox my = new UI_TextBox("TextBox", "이태릭체", "없음", 10);
                Rectangle  r  = new Rectangle();
                r.RadiusX = 0;
                r.RadiusY = 0;

                VisualBrush   myBrush             = new VisualBrush();
                StackPanel    aPanel              = new StackPanel();
                DrawingBrush  myDrawingBrushBrush = new DrawingBrush();
                GeometryGroup aGeometryGroup      = new GeometryGroup();
                aGeometryGroup.Children.Add(new RectangleGeometry(new Rect(0, 0, 50, 50)));
                RadialGradientBrush checkerBrush = new RadialGradientBrush();
                checkerBrush.GradientStops.Add(new GradientStop(Colors.LightCyan, 0.0));
                GeometryDrawing checkers = new GeometryDrawing(checkerBrush, null, aGeometryGroup);
                myDrawingBrushBrush.Drawing = checkers;
                aPanel.Background           = myDrawingBrushBrush;

                // Create some text.
                TextBlock someText = new TextBlock();
                someText.Text = "텍스트박스";
                FontSizeConverter fSizeConverter = new FontSizeConverter();
                someText.FontSize = (double)fSizeConverter.ConvertFromString("10pt");
                someText.Margin   = new Thickness(10);
                aPanel.Children.Add(someText);
                myBrush.Visual = aPanel;

                r.Fill         = myBrush;
                r.Fill.Opacity = 0.8;
                this.Add(r, my, pt);
                WebModelingStaticClass.ul.NewCheckBox.IsSelected = false;
            }
            for (int i = 0; i < IsUIChecked.Length; i++)
            {
                IsUIChecked[i] = false;
            }
            WebModelingStaticClass.IsMainGridClik = false;
        }
Пример #23
0
 public CardImageObject(DrawingBrush image, Card card) : this(card)
 {
     Image = image;
 }
        //==========================================================================
        public virtual Drawing Draw()
        {
            DrawingGroup drawing_group = new DrawingGroup();

            drawing_group.Opacity = Opacity.ToDouble();
            if (Transform != null)
            {
                drawing_group.Transform = Transform.ToTransform();
            }

            if (ViewBox != null)
            {
                drawing_group.Children.Add(ViewBox.Process());
            }

            foreach (SvgBaseElement child_element in Children)
            {
                SvgBaseElement element = child_element;
                if (element is SvgUseElement)
                {
                    element = (element as SvgUseElement).GetElement();
                }

                Drawing drawing = null;

                if (element is SvgDrawableBaseElement)
                {
                    if ((element as SvgDrawableBaseElement).Display != SvgDisplay.None)
                    {
                        drawing = (element as SvgDrawableBaseElement).Draw();
                    }
                }
                else if (element is SvgDrawableContainerBaseElement)
                {
                    if ((element as SvgDrawableContainerBaseElement).Display != SvgDisplay.None)
                    {
                        drawing = (element as SvgDrawableContainerBaseElement).Draw();
                    }
                }

                if (drawing != null)
                {
                    drawing_group.Children.Add(drawing);
                }
            }

            if (Filter != null)
            {
                SvgFilterElement filter_element = Document.Elements[Filter.Id] as SvgFilterElement;
                if (filter_element != null)
                {
                    drawing_group.BitmapEffect = filter_element.ToBitmapEffect();
                }
            }

            if (ClipPath != null)
            {
                SvgClipPathElement clip_path_element = Document.Elements[ClipPath.Id] as SvgClipPathElement;
                if (clip_path_element != null)
                {
                    drawing_group.ClipGeometry = clip_path_element.GetClipGeometry();
                }
            }

            if (Mask != null)
            {
                SvgMaskElement mask_element = Document.Elements[Mask.Id] as SvgMaskElement;
                if (mask_element != null)
                {
                    DrawingBrush opacity_mask = mask_element.GetOpacityMask();

                    /*
                     * if(Transform != null)
                     * opacity_mask.Transform = Transform.ToTransform();
                     */
                    drawing_group.OpacityMask = opacity_mask;
                }
            }

            return(drawing_group);
        }
        public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
        {
            //
            // Parameter Validation
            //
            Type doubleType = typeof(double);

            if (values == null ||
                (values.Length != 5) ||
                (values[0] == null) ||
                (values[1] == null) ||
                (values[2] == null) ||
                (values[3] == null) ||
                (values[4] == null) ||
                !typeof(Brush).IsAssignableFrom(values[0].GetType()) ||
                !typeof(bool).IsAssignableFrom(values[1].GetType()) ||
                !doubleType.IsAssignableFrom(values[2].GetType()) ||
                !doubleType.IsAssignableFrom(values[3].GetType()) ||
                !doubleType.IsAssignableFrom(values[4].GetType()))
            {
                return(null);
            }

            // Conversion

            Brush  brush           = (Brush)values[0];
            bool   isIndeterminate = (bool)values[1];
            double width           = (double)values[2];
            double height          = (double)values[3];
            double trackWidth      = (double)values[4];

            // if an invalid height, return a null brush
            if (width <= 0.0 || Double.IsInfinity(width) || Double.IsNaN(width) ||
                height <= 0.0 || Double.IsInfinity(height) || Double.IsNaN(height))
            {
                return(null);
            }

            DrawingBrush newBrush = new DrawingBrush();

            // Set the viewport and viewbox to the size of the progress region
            newBrush.Viewport      = newBrush.Viewbox = new Rect(0, 0, width, height);
            newBrush.ViewportUnits = newBrush.ViewboxUnits = BrushMappingMode.Absolute;

            newBrush.TileMode = TileMode.None;
            newBrush.Stretch  = Stretch.None;

            DrawingGroup   myDrawing        = new DrawingGroup();
            DrawingContext myDrawingContext = myDrawing.Open();

            double drawnWidth = 0.0; // The total width drawn to the brush so far

            double blockWidth = 6.0;
            double blockGap   = -1.5; // <-- was 2.0
            double blockTotal = blockWidth + blockGap;

            // For the indeterminate case, just draw a portion of the width
            // And animate the brush
            if (isIndeterminate)
            {
                int blocks = (int)Math.Ceiling(width / blockTotal);

                // The left (X) starting point of the brush
                double left = -blocks * blockTotal;

                // Only draw 30% of the blocks
                double indeterminateWidth = width * .3;

                // Generate the brush so it wraps correctly
                // The brush is larger than the rectangle to fill like so:
                //                +-------------+
                // [] [] [] __ __ |[] [] [] __ _|
                //                +-------------+
                // Translate Brush =>>
                // To have the marquee line up on the left as the blocks are scrolled off to the right
                // we need to have the second set of blocks offset from the first by the width of the rect
                newBrush.Viewport = newBrush.Viewbox = new Rect(left, 0, indeterminateWidth - left, height);

                // Add an animated translate transfrom
                TranslateTransform translation = new TranslateTransform();

                double milliseconds = blocks * 100; // 100 milliseconds on each position

                DoubleAnimationUsingKeyFrames animation = new DoubleAnimationUsingKeyFrames();
                animation.Duration       = new Duration(TimeSpan.FromMilliseconds(milliseconds)); // Repeat every 3 seconds
                animation.RepeatBehavior = RepeatBehavior.Forever;

                // Add a keyframe to translate by each block
                for (int i = 1; i <= blocks; i++)
                {
                    double x = i * blockTotal;
                    animation.KeyFrames.Add(new DiscreteDoubleKeyFrame(x, KeyTime.Uniform));
                }

                // Set the animation to the XProperty
                translation.BeginAnimation(TranslateTransform.XProperty, animation);

                // Set the animated translation on the brush
                newBrush.Transform = translation;

                // Draw the Blocks to the left of the brush that are translated into view
                // during the animation

                // While able to draw complete blocks,
                while ((drawnWidth + blockWidth) < indeterminateWidth)
                {
                    // Draw a block
                    myDrawingContext.DrawRectangle(brush, null, new Rect(left + drawnWidth, 0, blockWidth, height));
                    drawnWidth += blockTotal;
                }

                width      = indeterminateWidth; //only need to draw 30% of the blocks
                drawnWidth = 0.0;                //reset drawn width and draw the left blocks
            }

            // Draw as many blocks
            // While able to draw complete blocks,
            while ((drawnWidth + blockWidth) < width)
            {
                var rect = new Rect(drawnWidth, 0, blockWidth, height);

                // Snap rect to pixels
                GuidelineSet guidelines = new GuidelineSet();
                guidelines.GuidelinesX.Add(rect.Left);
                guidelines.GuidelinesX.Add(rect.Right);
                guidelines.GuidelinesY.Add(rect.Top);
                guidelines.GuidelinesY.Add(rect.Bottom);

                myDrawingContext.PushGuidelineSet(guidelines);

                // Draw a block
                myDrawingContext.DrawRectangle(brush, null, rect);
                drawnWidth += blockTotal;
            }

            double remainder = width - drawnWidth;

            // Draw portion of last block when ProgressBar is 100% (ie indicatorWidth == trackWidth)
            if (!isIndeterminate && remainder > 0.0 && Math.Abs(width - trackWidth) < 1.0e-5)
            {
                // Draw incomplete block to fill progress indicator area
                myDrawingContext.DrawRectangle(brush, null, new Rect(drawnWidth, 0, remainder, height));
            }

            myDrawingContext.Close();
            newBrush.Drawing = myDrawing;

            return(newBrush);
        }
Пример #26
0
        public TileModeExample()
        {
            Background = Brushes.White;
            Margin     = new Thickness(20);
            StackPanel mainPanel = new StackPanel();

            mainPanel.HorizontalAlignment = HorizontalAlignment.Left;

            //
            // Create a Drawing. This will be the DrawingBrushes' content.
            //
            PolyLineSegment triangleLinesSegment = new PolyLineSegment();

            triangleLinesSegment.Points.Add(new Point(50, 0));
            triangleLinesSegment.Points.Add(new Point(0, 50));
            PathFigure triangleFigure = new PathFigure();

            triangleFigure.IsClosed   = true;
            triangleFigure.StartPoint = new Point(0, 0);
            triangleFigure.Segments.Add(triangleLinesSegment);
            PathGeometry triangleGeometry = new PathGeometry();

            triangleGeometry.Figures.Add(triangleFigure);

            GeometryDrawing triangleDrawing = new GeometryDrawing();

            triangleDrawing.Geometry = triangleGeometry;
            triangleDrawing.Brush    = new SolidColorBrush(Color.FromArgb(255, 204, 204, 255));
            Pen trianglePen = new Pen(Brushes.Black, 2);

            triangleDrawing.Pen    = trianglePen;
            trianglePen.MiterLimit = 0;
            triangleDrawing.Freeze();

            //
            // Create the first TileBrush. Its content is not tiled.
            //
            DrawingBrush tileBrushWithoutTiling = new DrawingBrush();

            tileBrushWithoutTiling.Drawing  = triangleDrawing;
            tileBrushWithoutTiling.TileMode = TileMode.None;

            // Create a rectangle and paint it with the DrawingBrush.
            Rectangle noTileExampleRectangle = createExampleRectangle();

            noTileExampleRectangle.Fill = tileBrushWithoutTiling;

            // Add a header and the rectangle to the main panel.
            mainPanel.Children.Add(createExampleHeader("None"));
            mainPanel.Children.Add(noTileExampleRectangle);

            //
            // Create another TileBrush, this time with tiling.
            //
            DrawingBrush tileBrushWithTiling = new DrawingBrush();

            tileBrushWithTiling.Drawing  = triangleDrawing;
            tileBrushWithTiling.TileMode = TileMode.Tile;

            // Specify the brush's Viewport. Otherwise,
            // a single tile will be produced that fills
            // the entire output area and its TileMode will
            // have no effect.
            // This setting uses realtive values to
            // creates four tiles.
            tileBrushWithTiling.Viewport = new Rect(0, 0, 0.5, 0.5);

            // Create a rectangle and paint it with the DrawingBrush.
            Rectangle tilingExampleRectangle = createExampleRectangle();

            tilingExampleRectangle.Fill = tileBrushWithTiling;
            mainPanel.Children.Add(createExampleHeader("Tile"));
            mainPanel.Children.Add(tilingExampleRectangle);

            //
            // Create a TileBrush with FlipX tiling.
            // The brush's content is flipped horizontally as it is
            // tiled in this example
            //
            DrawingBrush tileBrushWithFlipXTiling = new DrawingBrush();

            tileBrushWithFlipXTiling.Drawing  = triangleDrawing;
            tileBrushWithFlipXTiling.TileMode = TileMode.FlipX;

            // Specify the brush's Viewport.
            tileBrushWithFlipXTiling.Viewport = new Rect(0, 0, 0.5, 0.5);

            // Create a rectangle and paint it with the DrawingBrush.
            Rectangle flipXTilingExampleRectangle = createExampleRectangle();

            flipXTilingExampleRectangle.Fill = tileBrushWithFlipXTiling;
            mainPanel.Children.Add(createExampleHeader("FlipX"));
            mainPanel.Children.Add(flipXTilingExampleRectangle);

            //
            // Create a TileBrush with FlipY tiling.
            // The brush's content is flipped vertically as it is
            // tiled in this example
            //
            DrawingBrush tileBrushWithFlipYTiling = new DrawingBrush();

            tileBrushWithFlipYTiling.Drawing  = triangleDrawing;
            tileBrushWithFlipYTiling.TileMode = TileMode.FlipY;

            // Specify the brush's Viewport.
            tileBrushWithFlipYTiling.Viewport = new Rect(0, 0, 0.5, 0.5);

            // Create a rectangle and paint it with the DrawingBrush.
            Rectangle flipYTilingExampleRectangle = createExampleRectangle();

            flipYTilingExampleRectangle.Fill = tileBrushWithFlipYTiling;
            mainPanel.Children.Add(createExampleHeader("FlipY"));
            mainPanel.Children.Add(flipYTilingExampleRectangle);

            //
            // Create a TileBrush with FlipXY tiling.
            // The brush's content is flipped vertically as it is
            // tiled in this example
            //
            DrawingBrush tileBrushWithFlipXYTiling = new DrawingBrush();

            tileBrushWithFlipXYTiling.Drawing  = triangleDrawing;
            tileBrushWithFlipXYTiling.TileMode = TileMode.FlipXY;

            // Specify the brush's Viewport.
            tileBrushWithFlipXYTiling.Viewport = new Rect(0, 0, 0.5, 0.5);

            // Create a rectangle and paint it with the DrawingBrush.
            Rectangle flipXYTilingExampleRectangle = createExampleRectangle();

            flipXYTilingExampleRectangle.Fill = tileBrushWithFlipXYTiling;
            mainPanel.Children.Add(createExampleHeader("FlipXY"));
            mainPanel.Children.Add(flipXYTilingExampleRectangle);

            Content = mainPanel;
        }
        /// <summary>
        ///     Creates the brush for the ProgressBar
        /// </summary>
        /// <param name="values">ForegroundBrush, IsIndeterminate, Width, Height</param>
        /// <param name="targetType"></param>
        /// <param name="parameter"></param>
        /// <param name="culture"></param>
        /// <returns>Brush for the ProgressBar</returns>
        public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
        {
            //
            // Parameter Validation
            //
            var doubleType = typeof(double);

            if (values == null ||
                values.Length != 3 ||
                values[0] == null ||
                values[1] == null ||
                values[2] == null ||
                !(values[0] is Brush) ||
                !doubleType.IsInstanceOfType(values[1]) ||
                !doubleType.IsInstanceOfType(values[2]))
            {
                return(null);
            }

            //
            // Conversion
            //

            var brush  = (Brush)values[0];
            var width  = (double)values[1];
            var height = (double)values[2];

            // if an invalid height, return a null brush
            if (width <= 0.0 || double.IsInfinity(width) || double.IsNaN(width) ||
                height <= 0.0 || double.IsInfinity(height) || double.IsNaN(height))
            {
                return(null);
            }

            var newBrush = new DrawingBrush();

            // Create a Drawing Brush that is 2x longer than progress bar track
            //
            // +-------------+..............
            // | highlight   | empty       :
            // +-------------+.............:
            //
            //  This brush will animate to the right.

            var twiceWidth = width * 2.0;

            // Set the viewport and viewbox to the 2*size of the progress region
            newBrush.Viewport      = newBrush.Viewbox = new Rect(-width, 0, twiceWidth, height);
            newBrush.ViewportUnits = newBrush.ViewboxUnits = BrushMappingMode.Absolute;

            newBrush.TileMode = TileMode.None;
            newBrush.Stretch  = Stretch.None;

            var myDrawing        = new DrawingGroup();
            var myDrawingContext = myDrawing.Open();

            // Draw the highlight
            myDrawingContext.DrawRectangle(brush, null, new Rect(-width, 0, width, height));


            // Animate the Translation

            var translateTime = TimeSpan.FromSeconds(twiceWidth / 200.0); // travel at 200px /second
            var pauseTime     = TimeSpan.FromSeconds(1.0);                // pause 1 second between animations

            var animation = new DoubleAnimationUsingKeyFrames
            {
                BeginTime      = TimeSpan.Zero,
                Duration       = new Duration(translateTime + pauseTime),
                RepeatBehavior = RepeatBehavior.Forever
            };

            animation.KeyFrames.Add(new LinearDoubleKeyFrame(twiceWidth, translateTime));

            var translation = new TranslateTransform();

            // Set the animation to the XProperty
            translation.BeginAnimation(TranslateTransform.XProperty, animation);

            // Set the animated translation on the brush
            newBrush.Transform = translation;


            myDrawingContext.Close();
            newBrush.Drawing = myDrawing;

            return(newBrush);
        }
Пример #28
0
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            #region 角

            Grid grid = new Grid();
            grid.Width  = 30;
            grid.Height = 10;

            ColumnDefinition cd1 = new ColumnDefinition();
            cd1.Width = new GridLength(1, GridUnitType.Star);
            ColumnDefinition cd2 = new ColumnDefinition();
            cd2.Width = new GridLength(1, GridUnitType.Star);
            grid.ColumnDefinitions.Add(cd1);
            grid.ColumnDefinitions.Add(cd2);

            TextBlock textblockL = new TextBlock();
            textblockL.Width  = 15;
            textblockL.Height = 10;

            LinearGradientBrush linearBrushL = new LinearGradientBrush();

            linearBrushL.SpreadMethod = GradientSpreadMethod.Repeat;
            linearBrushL.StartPoint   = new Point(0, 0);
            linearBrushL.EndPoint     = new Point(1, 1);
            linearBrushL.GradientStops.Add(new GradientStop(Colors.White, 0.0));
            linearBrushL.GradientStops.Add(new GradientStop(Colors.White, 0.5));
            linearBrushL.GradientStops.Add(new GradientStop(Colors.LightGray, 0.5));
            linearBrushL.GradientStops.Add(new GradientStop(Colors.LightGray, 1.0));


            DrawingBrush drawingBrushL = new DrawingBrush(
                new GeometryDrawing(
                    linearBrushL,
                    new Pen(new SolidColorBrush(Colors.Black), double.NaN)
            {
                //DashStyle = dashstyle
            },
                    new RectangleGeometry(
                        new Rect(0, 0, 15, 10)
                        )
                    )
                );

            drawingBrushL.Stretch      = Stretch.Fill;
            drawingBrushL.TileMode     = TileMode.FlipXY;
            drawingBrushL.Viewbox      = new Rect(0, 0, 15, 10);
            drawingBrushL.ViewboxUnits = BrushMappingMode.Absolute;
            textblockL.Background      = drawingBrushL;
            grid.Children.Add(textblockL);
            Grid.SetColumn(textblockL, 0);
            Grid.SetRow(textblockL, 0);

            TextBlock textblockR = new TextBlock();
            textblockR.Width  = 15;
            textblockR.Height = 10;

            LinearGradientBrush linearBrushR = new LinearGradientBrush();

            linearBrushR.SpreadMethod = GradientSpreadMethod.Repeat;
            linearBrushR.StartPoint   = new Point(1, 0);
            linearBrushR.EndPoint     = new Point(0, 1);
            linearBrushR.GradientStops.Add(new GradientStop(Colors.White, 0.0));
            linearBrushR.GradientStops.Add(new GradientStop(Colors.White, 0.5));
            linearBrushR.GradientStops.Add(new GradientStop(Colors.Black, 0.5));
            linearBrushR.GradientStops.Add(new GradientStop(Colors.Black, 1.0));


            DrawingBrush drawingBrushR = new DrawingBrush(
                new GeometryDrawing(
                    linearBrushR,
                    new Pen(new SolidColorBrush(Colors.Black), double.NaN)
            {
                //DashStyle = dashstyle
            },
                    new RectangleGeometry(
                        new Rect(0, 0, 15, 10)
                        )
                    )
                );

            drawingBrushR.Stretch      = Stretch.Fill;
            drawingBrushR.TileMode     = TileMode.FlipXY;
            drawingBrushR.Viewbox      = new Rect(0, 0, 15, 10);
            drawingBrushR.ViewboxUnits = BrushMappingMode.Absolute;
            textblockR.Background      = drawingBrushR;
            grid.Children.Add(textblockR);
            Grid.SetColumn(textblockR, 1);
            Grid.SetRow(textblockR, 0);

            #endregion

            for (int i = 0; i <= 3; i++)
            {
                TextBlock tb = new TextBlock();
                tb.Width  = 10;
                tb.Height = 10;

                VisualBrush visualbrush = new VisualBrush(grid);

                DrawingBrush drawingBrushTest = new DrawingBrush(
                    new GeometryDrawing(
                        visualbrush,
                        new Pen(new SolidColorBrush(Colors.Black), double.NaN)
                {
                    //DashStyle = dashstyle
                },
                        new RectangleGeometry(
                            new Rect(0, 0, 10, 10)
                            )
                        )
                    );

                drawingBrushTest.Stretch      = Stretch.Uniform;
                drawingBrushTest.Viewbox      = new Rect(0, 0, 10, 10);
                drawingBrushTest.ViewboxUnits = BrushMappingMode.Absolute;
                tb.Background = drawingBrushTest;
                test.Children.Add(tb);
                Grid.SetRow(tb, array[i, 0]);
                Grid.SetColumn(tb, array[i, 1]);

                RotateTransform rotateTransform1 = new RotateTransform(i * 90, 5, 5);
                TransformGroup  transformGroup1  = new TransformGroup();
                transformGroup1.Children.Add(rotateTransform1);
                tb.RenderTransform = transformGroup1;
            }

            Grid gridC = new Grid();
            gridC.Width      = 10;
            gridC.Height     = 10;
            gridC.Background = new SolidColorBrush(Colors.LightGray);
            test.Children.Add(gridC);
            Grid.SetColumn(gridC, 1);
            Grid.SetRow(gridC, 1);

            Ellipse ellipse = new Ellipse();
            ellipse.Width  = 10;
            ellipse.Height = 10;
            ellipse.Fill   = new SolidColorBrush(Colors.White);
            gridC.Children.Add(ellipse);
        }
Пример #29
0
        private void RenderPath(WpfDrawingRenderer renderer)
        {
            WpfDrawingContext context = renderer.Context;

            SvgRenderingHint hint = _svgElement.RenderingHint;

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

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

            SvgStyleableElement styleElm = (SvgStyleableElement)_svgElement;

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

            DrawingGroup drawGroup = context.Peek();

            Debug.Assert(drawGroup != null);

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

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

            GeometryDrawing drawing = null;

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

            var bounds = geometry.Bounds;

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

            context.UpdateBounds(geometry.Bounds);

//                SetClip(context);

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

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

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

            if (brush == null)
            {
                WpfSvgPaint fallbackPaint = fillPaint.WpfFallback;
                if (fallbackPaint != null)
                {
                    brush = fallbackPaint.GetBrush(geometry, _setBrushOpacity);
                }
            }
            bool isFillTransmable = fillPaint.IsFillTransformable;

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

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

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

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

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

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

                    context.RegisterId(elementId);

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

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

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

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

                    Rect geometryBounds = geometry.Bounds;

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

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

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

                            TransformGroup transformGroup = new TransformGroup();

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

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

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

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

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

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

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

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

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

                                drawingBrush.Stretch = Stretch.Uniform;

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

                        clipMaskGroup.OpacityMask = maskBrush;
                    }

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

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

            // Register this drawing with the Drawing-Document...
            if (drawing != null)
            {
                this.Rendered(drawing);
            }
        }
Пример #30
0
        private DrawingBrush GetIconByVisualValue()
        {
            if (this.VisualValue != null)
            {
                DrawingBrush icon          = null;
                Type         modelItemType = this.VisualValue.ItemType;
                if (modelItemType.IsGenericType)
                {
                    // If Type is generic type, whatever T, it should display same icon, so use generic type instead.
                    modelItemType = this.VisualValue.ItemType.GetGenericTypeDefinition();
                }

                // If the user specifies the attribute, then the Designer would be providing the icon,
                // bypassing the pipeline of retrieving the icons via reflection and attached properties.
                ActivityDesignerOptionsAttribute attr = ExtensibilityAccessor.GetAttribute <ActivityDesignerOptionsAttribute>(modelItemType);
                if (attr != null && attr.OutlineViewIconProvider != null)
                {
                    icon = attr.OutlineViewIconProvider(this.VisualValue);
                }

                if (icon == null && !TreeViewItemViewModel.IconCache.TryGetValue(modelItemType, out icon))
                {
                    EditingContext      context             = this.VisualValue.GetEditingContext();
                    ViewService         service             = context.Services.GetService <ViewService>();
                    WorkflowViewService workflowViewService = service as WorkflowViewService;
                    ActivityDesigner    designer            = null;

                    // first try to create an detached view element that won't participate in the designer,
                    // if the view service is WorkflowViewService
                    if (workflowViewService != null)
                    {
                        designer = workflowViewService.CreateDetachedViewElement(this.VisualValue) as ActivityDesigner;
                        icon     = GetIconFromUnInitializedDesigner(designer);
                    }
                    else
                    {
                        // fall back if the view service is not the default implementation
                        // We only need to get the icon from the designer, so we don't need to make sure the view is parented.
                        designer = this.VisualValue.View as ActivityDesigner;
                        if (designer == null && service != null)
                        {
                            designer = service.GetView(this.VisualValue) as ActivityDesigner;
                        }

                        if (designer != null)
                        {
                            if (designer.Icon != null || designer.IsLoaded)
                            {
                                icon = designer.Icon;
                            }
                            else
                            {
                                icon = GetIconFromUnInitializedDesigner(designer);
                            }
                        }
                    }

                    // Cache even a null icon since answers found above won't change within this AppDomain
                    TreeViewItemViewModel.IconCache.Add(modelItemType, icon);
                }

                return(icon);
            }
            else
            {
                return(null);
            }
        }