예제 #1
0
        public override void BeforeRender(WpfDrawingRenderer renderer)
        {
            base.BeforeRender(renderer);

            WpfDrawingContext context = renderer.Context;

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

            if (transform == null &&
                (_svgElement.FirstChild != null && _svgElement.FirstChild == _svgElement.LastChild))
            {
                try
                {
                    SvgUseElement useElement = (SvgUseElement)_svgElement;

                    // If none of the following attribute exists, an exception is thrown...
                    double x      = useElement.X.AnimVal.Value;
                    double y      = useElement.Y.AnimVal.Value;
                    double width  = useElement.Width.AnimVal.Value;
                    double height = useElement.Height.AnimVal.Value;
                    if (width > 0 && height > 0)
                    {
                        Rect elementBounds = new Rect(x, y, width, height);

                        // Try handling the cases of "symbol" and "svg" sources within the "use"...
                        XmlNode childNode = _svgElement.FirstChild;
                        string  childName = childNode.Name;
                        if (String.Equals(childName, "symbol", StringComparison.OrdinalIgnoreCase))
                        {
                            SvgSymbolElement symbolElement = (SvgSymbolElement)childNode;

                            this.FitToViewbox(context, symbolElement, elementBounds);
                        }
                    }

                    transform = this.Transform;
                }
                catch
                {
                }
            }

            if (clipGeom != null || transform != null)
            {
                _drawGroup = new DrawingGroup();

                DrawingGroup currentGroup = context.Peek();

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

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

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

                if (transform != null)
                {
                    _drawGroup.Transform = transform;
                }
            }
        }
        /// <summary>
        /// Initializes a new instance of the MainWindow class.
        /// </summary>
        public MainWindow()
        {
            // one sensor is currently supported
            this.kinectSensor = KinectSensor.GetDefault();

            // get the coordinate mapper
            this.coordinateMapper = this.kinectSensor.CoordinateMapper;

            // get the depth (display) extents
            FrameDescription frameDescription = this.kinectSensor.DepthFrameSource.FrameDescription;

            // get size of joint space
            this.displayWidth  = frameDescription.Width;
            this.displayHeight = frameDescription.Height;

            // open the reader for the body frames
            this.bodyFrameReader = this.kinectSensor.BodyFrameSource.OpenReader();

            bodyMoments = new List <bodyMoment>();

            this.collect = false;

            this.fileName = "default";

            // a bone defined as a line between two joints
            this.bones = new List <Tuple <JointType, JointType> >();

            // Torso
            this.bones.Add(new Tuple <JointType, JointType>(JointType.Head, JointType.Neck));
            this.bones.Add(new Tuple <JointType, JointType>(JointType.Neck, JointType.SpineShoulder));
            this.bones.Add(new Tuple <JointType, JointType>(JointType.SpineShoulder, JointType.SpineMid));
            this.bones.Add(new Tuple <JointType, JointType>(JointType.SpineMid, JointType.SpineBase));
            this.bones.Add(new Tuple <JointType, JointType>(JointType.SpineShoulder, JointType.ShoulderRight));
            this.bones.Add(new Tuple <JointType, JointType>(JointType.SpineShoulder, JointType.ShoulderLeft));
            this.bones.Add(new Tuple <JointType, JointType>(JointType.SpineBase, JointType.HipRight));
            this.bones.Add(new Tuple <JointType, JointType>(JointType.SpineBase, JointType.HipLeft));

            // Right Arm
            this.bones.Add(new Tuple <JointType, JointType>(JointType.ShoulderRight, JointType.ElbowRight));
            this.bones.Add(new Tuple <JointType, JointType>(JointType.ElbowRight, JointType.WristRight));
            this.bones.Add(new Tuple <JointType, JointType>(JointType.WristRight, JointType.HandRight));
            this.bones.Add(new Tuple <JointType, JointType>(JointType.HandRight, JointType.HandTipRight));
            this.bones.Add(new Tuple <JointType, JointType>(JointType.WristRight, JointType.ThumbRight));

            // Left Arm
            this.bones.Add(new Tuple <JointType, JointType>(JointType.ShoulderLeft, JointType.ElbowLeft));
            this.bones.Add(new Tuple <JointType, JointType>(JointType.ElbowLeft, JointType.WristLeft));
            this.bones.Add(new Tuple <JointType, JointType>(JointType.WristLeft, JointType.HandLeft));
            this.bones.Add(new Tuple <JointType, JointType>(JointType.HandLeft, JointType.HandTipLeft));
            this.bones.Add(new Tuple <JointType, JointType>(JointType.WristLeft, JointType.ThumbLeft));

            // Right Leg
            this.bones.Add(new Tuple <JointType, JointType>(JointType.HipRight, JointType.KneeRight));
            this.bones.Add(new Tuple <JointType, JointType>(JointType.KneeRight, JointType.AnkleRight));
            this.bones.Add(new Tuple <JointType, JointType>(JointType.AnkleRight, JointType.FootRight));

            // Left Leg
            this.bones.Add(new Tuple <JointType, JointType>(JointType.HipLeft, JointType.KneeLeft));
            this.bones.Add(new Tuple <JointType, JointType>(JointType.KneeLeft, JointType.AnkleLeft));
            this.bones.Add(new Tuple <JointType, JointType>(JointType.AnkleLeft, JointType.FootLeft));

            // populate body colors, one for each BodyIndex
            this.bodyColors = new List <Pen>();

            this.bodyColors.Add(new Pen(Brushes.Red, 6));
            this.bodyColors.Add(new Pen(Brushes.Orange, 6));
            this.bodyColors.Add(new Pen(Brushes.Green, 6));
            this.bodyColors.Add(new Pen(Brushes.Blue, 6));
            this.bodyColors.Add(new Pen(Brushes.Indigo, 6));
            this.bodyColors.Add(new Pen(Brushes.Violet, 6));

            // set IsAvailableChanged event notifier
            this.kinectSensor.IsAvailableChanged += this.Sensor_IsAvailableChanged;

            // open the sensor
            this.kinectSensor.Open();

            // set the status text
            this.StatusText = this.kinectSensor.IsAvailable ? Properties.Resources.RunningStatusText
                                                            : Properties.Resources.NoSensorStatusText;

            // Create the drawing group we'll use for drawing
            this.drawingGroup = new DrawingGroup();

            // Create an image source that we can use in our image control
            this.imageSource = new DrawingImage(this.drawingGroup);

            // use the window object as the view model in this simple example
            this.DataContext = this;

            // initialize the components (controls) of the window
            this.InitializeComponent();
        }
예제 #3
0
        public override void Visit(DrawingGroup group, SvgAElement element,
                                   WpfDrawingContext context, float opacity)
        {
            _isAggregated = false;

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

            AddExtraLinkInformation(group, element);

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

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

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

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

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

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

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

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

                    drawGeometry = geomGroup;
                }

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

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

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

                group.Children.Add(drawing);
            }

            _dicLinks.Add(linkId, _isAggregated);
        }
예제 #4
0
        /////////////////////////////////////////////////////////////////////////////////////////////////////
        // PUBLIC PROCEDURES
        /////////////////////////////////////////////////////////////////////////////////////////////////////

        /// <summary>
        /// Converts a value. The data binding engine calls this method when it propagates a value from the binding source to the binding target.
        /// </summary>
        /// <param name="value">The value produced by the binding source.</param>
        /// <param name="targetType">The type of the binding target property.</param>
        /// <param name="parameter">The converter parameter to use.</param>
        /// <param name="culture">The culture to use in the converter.</param>
        /// <returns>A converted value.</returns>
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            var menuItem  = value as MenuItem;
            var themeName = (menuItem != null ? menuItem.Tag as string : null);

            var accentColor     = Colors.Transparent;
            var backgroundColor = Colors.White;
            var borderColor     = Colors.White;
            var isAccentBelow   = false;

            switch (themeName)
            {
            case ThemeNames.HighContrast:
                backgroundColor = UIColor.FromWebColor("#000000").ToColor();
                borderColor     = UIColor.FromWebColor("#00ff00").ToColor();
                break;

            case ThemeNames.Black:
            case ThemeNames.MetroBlack:
                backgroundColor = UIColor.FromWebColor("#111112").ToColor();
                borderColor     = UIColor.FromWebColor("#494c50").ToColor();
                break;

            case ThemeNames.Dark:
            case ThemeNames.MetroDark:
                backgroundColor = UIColor.FromWebColor("#2d2f32").ToColor();
                borderColor     = UIColor.FromWebColor("#575a5f").ToColor();
                break;

            case ThemeNames.Light:
            case ThemeNames.MetroLight:
            case ThemeNames.OfficeColorfulBlue:
            case ThemeNames.OfficeColorfulGreen:
            case ThemeNames.OfficeColorfulIndigo:
            case ThemeNames.OfficeColorfulOrange:
            case ThemeNames.OfficeColorfulPink:
            case ThemeNames.OfficeColorfulPurple:
            case ThemeNames.OfficeColorfulRed:
            case ThemeNames.OfficeColorfulTeal:
            case ThemeNames.OfficeColorfulYellow:
                backgroundColor = UIColor.FromWebColor("#f1f1f2").ToColor();
                borderColor     = UIColor.FromWebColor("#c7c9cb").ToColor();
                break;

            case ThemeNames.White:
            case ThemeNames.MetroWhite:
            case ThemeNames.OfficeWhiteBlue:
            case ThemeNames.OfficeWhiteGreen:
            case ThemeNames.OfficeWhiteIndigo:
            case ThemeNames.OfficeWhiteOrange:
            case ThemeNames.OfficeWhitePink:
            case ThemeNames.OfficeWhitePurple:
            case ThemeNames.OfficeWhiteRed:
            case ThemeNames.OfficeWhiteTeal:
            case ThemeNames.OfficeWhiteYellow:
                backgroundColor = UIColor.FromWebColor("#ffffff").ToColor();
                borderColor     = UIColor.FromWebColor("#d8d9da").ToColor();
                break;

            case ThemeNames.AeroNormalColor:
                accentColor     = UIColor.FromWebColor("#a5c0db").ToColor();
                backgroundColor = UIColor.FromWebColor("#dce1ed").ToColor();
                borderColor     = UIColor.FromWebColor("#abadb3").ToColor();
                break;

            case ThemeNames.Office2010Black:
                accentColor     = UIColor.FromWebColor("#767676").ToColor();
                backgroundColor = UIColor.FromWebColor("#bababa").ToColor();
                borderColor     = UIColor.FromWebColor("#abadb3").ToColor();
                break;

            case ThemeNames.Office2010Blue:
                accentColor     = UIColor.FromWebColor("#bed2e8").ToColor();
                backgroundColor = UIColor.FromWebColor("#cfdded").ToColor();
                borderColor     = UIColor.FromWebColor("#abadb3").ToColor();
                break;

            case ThemeNames.Office2010Silver:
                accentColor     = UIColor.FromWebColor("#e8ebed").ToColor();
                backgroundColor = UIColor.FromWebColor("#e5e9ee").ToColor();
                borderColor     = UIColor.FromWebColor("#abadb3").ToColor();
                break;

            default:
                // Unknown theme
                return(null);
            }

            switch (themeName)
            {
            case ThemeNames.MetroBlack:
            case ThemeNames.MetroDark:
            case ThemeNames.MetroLight:
            case ThemeNames.MetroWhite:
                accentColor = UIColor.FromWebColor("#0077ac").ToColor();
                break;

            case ThemeNames.OfficeColorfulBlue:
            case ThemeNames.OfficeWhiteBlue:
                accentColor = UIColor.FromWebColor("#106ebe").ToColor();
                break;

            case ThemeNames.OfficeColorfulGreen:
            case ThemeNames.OfficeWhiteGreen:
                accentColor = UIColor.FromWebColor("#217346").ToColor();
                break;

            case ThemeNames.OfficeColorfulIndigo:
            case ThemeNames.OfficeWhiteIndigo:
                accentColor = UIColor.FromWebColor("#2b579a").ToColor();
                break;

            case ThemeNames.OfficeColorfulOrange:
            case ThemeNames.OfficeWhiteOrange:
                accentColor = UIColor.FromWebColor("#b7472a").ToColor();
                break;

            case ThemeNames.OfficeColorfulPink:
            case ThemeNames.OfficeWhitePink:
                accentColor = UIColor.FromWebColor("#7619ab").ToColor();
                break;

            case ThemeNames.OfficeColorfulPurple:
            case ThemeNames.OfficeWhitePurple:
                accentColor = UIColor.FromWebColor("#823979").ToColor();
                break;

            case ThemeNames.OfficeColorfulRed:
            case ThemeNames.OfficeWhiteRed:
                accentColor = UIColor.FromWebColor("#c51d17").ToColor();
                break;

            case ThemeNames.OfficeColorfulTeal:
            case ThemeNames.OfficeWhiteTeal:
                accentColor = UIColor.FromWebColor("#087666").ToColor();
                break;

            case ThemeNames.OfficeColorfulYellow:
            case ThemeNames.OfficeWhiteYellow:
                accentColor = UIColor.FromWebColor("#e6aa11").ToColor();
                break;
            }

            switch (themeName)
            {
            case ThemeNames.MetroBlack:
            case ThemeNames.MetroDark:
            case ThemeNames.MetroLight:
            case ThemeNames.MetroWhite:
            case ThemeNames.OfficeColorfulBlue:
            case ThemeNames.OfficeColorfulGreen:
            case ThemeNames.OfficeColorfulIndigo:
            case ThemeNames.OfficeColorfulOrange:
            case ThemeNames.OfficeColorfulPink:
            case ThemeNames.OfficeColorfulPurple:
            case ThemeNames.OfficeColorfulRed:
            case ThemeNames.OfficeColorfulTeal:
            case ThemeNames.OfficeColorfulYellow:
            case ThemeNames.OfficeWhiteBlue:
            case ThemeNames.OfficeWhiteGreen:
            case ThemeNames.OfficeWhiteIndigo:
            case ThemeNames.OfficeWhiteOrange:
            case ThemeNames.OfficeWhitePink:
            case ThemeNames.OfficeWhitePurple:
            case ThemeNames.OfficeWhiteRed:
            case ThemeNames.OfficeWhiteTeal:
            case ThemeNames.OfficeWhiteYellow:
                borderColor = accentColor;
                break;
            }

            switch (themeName)
            {
            case ThemeNames.MetroBlack:
            case ThemeNames.MetroDark:
            case ThemeNames.MetroLight:
            case ThemeNames.MetroWhite:
            case ThemeNames.OfficeWhiteBlue:
            case ThemeNames.OfficeWhiteGreen:
            case ThemeNames.OfficeWhiteIndigo:
            case ThemeNames.OfficeWhiteOrange:
            case ThemeNames.OfficeWhitePink:
            case ThemeNames.OfficeWhitePurple:
            case ThemeNames.OfficeWhiteRed:
            case ThemeNames.OfficeWhiteTeal:
            case ThemeNames.OfficeWhiteYellow:
                isAccentBelow = true;
                break;
            }

            var accentBrush     = new SolidColorBrush(accentColor);
            var backgroundBrush = new SolidColorBrush(backgroundColor);
            var borderBrush     = new SolidColorBrush(borderColor);

            accentBrush.Freeze();
            backgroundBrush.Freeze();
            borderBrush.Freeze();

            var group = new DrawingGroup();

            var backgroundDrawing = new GeometryDrawing();

            backgroundDrawing.Brush    = backgroundBrush;
            backgroundDrawing.Pen      = new Pen(borderBrush, 1);
            backgroundDrawing.Geometry = new RectangleGeometry(new Rect(0.5, 0.5, 15, 15));
            group.Children.Add(backgroundDrawing);

            var accentDrawing = new GeometryDrawing();

            accentDrawing.Brush    = accentBrush;
            accentDrawing.Geometry = new RectangleGeometry(new Rect(1, (isAccentBelow ? 11 : 1), 14, 4));
            group.Children.Add(accentDrawing);

            var image = new Image()
            {
                Width  = 16,
                Height = 16,
                Source = new DrawingImage()
                {
                    Drawing = group
                }
            };

            return(image);
        }
예제 #5
0
 /**
  * Copy constructor used to copy drawings from read to write
  *
  * @param dgo the drawing group object
  * @param dg the drawing group
  * @param ws the workbook settings
  */
 /*protected*/
 public Comment(DrawingGroupObject dgo,
     DrawingGroup dg,
     WorkbookSettings ws)
 {
     Comment d = (Comment)dgo;
     Assert.verify(d.origin == Origin.READ);
     msoDrawingRecord = d.msoDrawingRecord;
     objRecord = d.objRecord;
     initialized = false;
     origin = Origin.READ;
     drawingData = d.drawingData;
     drawingGroup = dg;
     drawingNumber = d.drawingNumber;
     drawingGroup.addDrawing(this);
     mso = d.mso;
     txo = d.txo;
     text = d.text;
     formatting = d.formatting;
     note = d.note;
     width = d.width;
     height = d.height;
     workbookSettings = ws;
 }
예제 #6
0
        public override void Render(WpfDrawingRenderer renderer)
        {
            Geometry  clipGeom  = this.ClipGeometry;
            Transform transform = this.Transform;

            WpfDrawingContext context = renderer.Context;

            SvgSwitchElement switchElement = (SvgSwitchElement)_svgElement;

            string elementId = this.GetElementName();

            float opacityValue = -1;

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

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

            if (clipGeom != null || transform != null || (opacityValue >= 0 && opacityValue < 1) ||
                (!string.IsNullOrWhiteSpace(elementId) && !context.IsRegisteredId(elementId)))
            {
                _drawGroup = new DrawingGroup();

                DrawingGroup currentGroup = context.Peek();

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

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

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

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

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

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

                    context.RegisterId(elementId);

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

            // Register this drawing with the Drawing-Document...
            this.Rendered(_drawGroup);

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

            SvgRenderingHint hint = _svgElement.RenderingHint;

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

            SvgStyleableElement styleElm = (SvgStyleableElement)_svgElement;

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

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

            DrawingGroup drawGroup = context.Peek();

            Debug.Assert(drawGroup != null);

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

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

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

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

                Brush brush = fillPaint.GetBrush(geometry);

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

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

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

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

                        context.RegisterId(elementId);

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

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

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

                        Rect geometryBounds = geometry.Bounds;

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

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

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

                                TransformGroup transformGroup = new TransformGroup();

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

                                clipGeom.Transform = transformGroup;
                            }
                            else
                            {
                                if (transform != null)
                                {
                                    clipGeom.Transform = transform;
                                }
                            }
                        }
                        if (maskBrush != null)
                        {
                            SvgUnitType maskUnits = this.MaskUnits;
                            if (maskUnits == SvgUnitType.ObjectBoundingBox)
                            {
                                Rect drawingBounds = geometryBounds;

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

                                TransformGroup transformGroup = new TransformGroup();

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

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

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

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

                                //maskBrush.Stretch = Stretch.Uniform;

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

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

                            clipMaskGroup.OpacityMask = maskBrush;
                        }

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

            RenderMarkers(renderer, styleElm, context);
        }
        /**
         * Adds a drawing to this workbook
         *
         * @param d the drawing to add
         */
        public void addDrawing(DrawingGroupObject d)
        {
            if (drawingGroup == null)
                {
                drawingGroup = new DrawingGroup(Origin.WRITE);
                }

            drawingGroup.add(d);
        }
예제 #9
0
        public PenExample()
        {
            // Create several geometries.
            RectangleGeometry myRectangleGeometry = new RectangleGeometry();

            myRectangleGeometry.Rect = new Rect(0, 0, 50, 50);
            EllipseGeometry myEllipseGeometry = new EllipseGeometry();

            myEllipseGeometry.Center  = new Point(75, 75);
            myEllipseGeometry.RadiusX = 50;
            myEllipseGeometry.RadiusY = 50;
            LineGeometry myLineGeometry = new LineGeometry();

            myLineGeometry.StartPoint = new Point(75, 75);
            myLineGeometry.EndPoint   = new Point(75, 0);

            // Create a GeometryGroup and add the geometries to it.
            GeometryGroup myGeometryGroup = new GeometryGroup();

            myGeometryGroup.Children.Add(myRectangleGeometry);
            myGeometryGroup.Children.Add(myEllipseGeometry);
            myGeometryGroup.Children.Add(myLineGeometry);

            // Create a GeometryDrawing and use the GeometryGroup to specify
            // its geometry.
            GeometryDrawing myGeometryDrawing = new GeometryDrawing();

            myGeometryDrawing.Geometry = myGeometryGroup;

            // Add the GeometryDrawing to a DrawingGroup.
            DrawingGroup myDrawingGroup = new DrawingGroup();

            myDrawingGroup.Children.Add(myGeometryDrawing);

            // Create a Pen to add to the GeometryDrawing created above.
            Pen myPen = new Pen();

            myPen.Thickness  = 10;
            myPen.LineJoin   = PenLineJoin.Round;
            myPen.EndLineCap = PenLineCap.Round;

            // Create a gradient to use as a value for the Pen's Brush property.
            GradientStop firstStop = new GradientStop();

            firstStop.Offset = 0.0;
            Color c1 = new Color();

            c1.A            = 255;
            c1.R            = 204;
            c1.G            = 204;
            c1.B            = 255;
            firstStop.Color = c1;
            GradientStop secondStop = new GradientStop();

            secondStop.Offset = 1.0;
            secondStop.Color  = Colors.Purple;

            LinearGradientBrush myLinearGradientBrush = new LinearGradientBrush();

            myLinearGradientBrush.GradientStops.Add(firstStop);
            myLinearGradientBrush.GradientStops.Add(secondStop);

            myPen.Brush           = myLinearGradientBrush;
            myGeometryDrawing.Pen = myPen;

            // Create an Image and set its DrawingImage to the Geometry created above.
            Image myImage = new Image();

            myImage.Stretch = Stretch.None;
            myImage.Margin  = new Thickness(10);

            DrawingImage myDrawingImage = new DrawingImage();

            myDrawingImage.Drawing = myDrawingGroup;
            myImage.Source         = myDrawingImage;

            this.Content = myImage;
        }
예제 #10
0
        private ImageSource PlatedImage(BitmapImage image)
        {
            if (!string.IsNullOrEmpty(BackgroundColor))
            {
                string currentBackgroundColor;
                if (BackgroundColor == "transparent")
                {
                    // Using InvariantCulture since this is internal
                    currentBackgroundColor = SystemParameters.WindowGlassBrush.ToString(CultureInfo.InvariantCulture);
                }
                else
                {
                    currentBackgroundColor = BackgroundColor;
                }

                var padding = 8;
                var width   = image.Width + (2 * padding);
                var height  = image.Height + (2 * padding);
                var x       = 0;
                var y       = 0;

                var group     = new DrawingGroup();
                var converted = ColorConverter.ConvertFromString(currentBackgroundColor);
                if (converted != null)
                {
                    var color             = (Color)converted;
                    var brush             = new SolidColorBrush(color);
                    var pen               = new Pen(brush, 1);
                    var backgroundArea    = new Rect(0, 0, width, height);
                    var rectangleGeometry = new RectangleGeometry(backgroundArea);
                    var rectDrawing       = new GeometryDrawing(brush, pen, rectangleGeometry);
                    group.Children.Add(rectDrawing);

                    var imageArea    = new Rect(x + padding, y + padding, image.Width, image.Height);
                    var imageDrawing = new ImageDrawing(image, imageArea);
                    group.Children.Add(imageDrawing);

                    // http://stackoverflow.com/questions/6676072/get-system-drawing-bitmap-of-a-wpf-area-using-visualbrush
                    var visual  = new DrawingVisual();
                    var context = visual.RenderOpen();
                    context.DrawDrawing(group);
                    context.Close();

                    var bitmap = new RenderTargetBitmap(
                        Convert.ToInt32(width),
                        Convert.ToInt32(height),
                        _dpiScale100,
                        _dpiScale100,
                        PixelFormats.Pbgra32);

                    bitmap.Render(visual);

                    return(bitmap);
                }
                else
                {
                    ProgramLogger.Exception($"Unable to convert background string {BackgroundColor} to color for {Package.Location}", new InvalidOperationException(), GetType(), Package.Location);

                    return(new BitmapImage(new Uri(Constant.ErrorIcon)));
                }
            }
            else
            {
                // todo use windows theme as background
                return(image);
            }
        }
예제 #11
0
 public void DrawHoverSample(Map map, DrawingGroup drawingArea, double zoom, Point pixelPosition)
 {
     return;
 }
        public MainWindow()
        {
            using (StreamWriter sw = new StreamWriter("file.txt", false, System.Text.Encoding.Default)) {
            }

            IPEndPoint ipPoint = new IPEndPoint(IPAddress.Parse("192.168.0.18"), 8080);

            Socket listenSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            try {
                listenSocket.Bind(ipPoint);

                listenSocket.Listen(10);

                handler = listenSocket.Accept();

                /*byte[] data = new byte[256];
                 *
                 * string message = "message";
                 * data = Encoding.UTF8.GetBytes(message);
                 * handler.Send(data);*/
                //handler.Shutdown(SocketShutdown.Both);
                //handler.Close();
            }
            catch (Exception ex) {
                Console.WriteLine(ex.Message);
            }


            // one sensor is currently supported
            this.kinectSensor = KinectSensor.GetDefault();

            // get the coordinate mapper
            this.coordinateMapper = this.kinectSensor.CoordinateMapper;

            // get the depth (display) extents
            FrameDescription frameDescription = this.kinectSensor.DepthFrameSource.FrameDescription;

            // get size of joint space
            this.displayWidth  = frameDescription.Width;
            this.displayHeight = frameDescription.Height;

            // open the reader for the body frames
            this.bodyFrameReader = this.kinectSensor.BodyFrameSource.OpenReader();

            // a bone defined as a line between two joints
            this.bones = new List <Tuple <JointType, JointType> >();

            // Torso
            this.bones.Add(new Tuple <JointType, JointType>(JointType.Head, JointType.Neck));
            this.bones.Add(new Tuple <JointType, JointType>(JointType.Neck, JointType.SpineShoulder));
            this.bones.Add(new Tuple <JointType, JointType>(JointType.SpineShoulder, JointType.SpineMid));
            this.bones.Add(new Tuple <JointType, JointType>(JointType.SpineMid, JointType.SpineBase));
            this.bones.Add(new Tuple <JointType, JointType>(JointType.SpineShoulder, JointType.ShoulderRight));
            this.bones.Add(new Tuple <JointType, JointType>(JointType.SpineShoulder, JointType.ShoulderLeft));
            this.bones.Add(new Tuple <JointType, JointType>(JointType.SpineBase, JointType.HipRight));
            this.bones.Add(new Tuple <JointType, JointType>(JointType.SpineBase, JointType.HipLeft));

            // Right Arm
            this.bones.Add(new Tuple <JointType, JointType>(JointType.ShoulderRight, JointType.ElbowRight));
            this.bones.Add(new Tuple <JointType, JointType>(JointType.ElbowRight, JointType.WristRight));
            this.bones.Add(new Tuple <JointType, JointType>(JointType.WristRight, JointType.HandRight));
            this.bones.Add(new Tuple <JointType, JointType>(JointType.HandRight, JointType.HandTipRight));
            this.bones.Add(new Tuple <JointType, JointType>(JointType.WristRight, JointType.ThumbRight));

            // Left Arm
            this.bones.Add(new Tuple <JointType, JointType>(JointType.ShoulderLeft, JointType.ElbowLeft));
            this.bones.Add(new Tuple <JointType, JointType>(JointType.ElbowLeft, JointType.WristLeft));
            this.bones.Add(new Tuple <JointType, JointType>(JointType.WristLeft, JointType.HandLeft));
            this.bones.Add(new Tuple <JointType, JointType>(JointType.HandLeft, JointType.HandTipLeft));
            this.bones.Add(new Tuple <JointType, JointType>(JointType.WristLeft, JointType.ThumbLeft));

            // Right Leg
            this.bones.Add(new Tuple <JointType, JointType>(JointType.HipRight, JointType.KneeRight));
            this.bones.Add(new Tuple <JointType, JointType>(JointType.KneeRight, JointType.AnkleRight));
            this.bones.Add(new Tuple <JointType, JointType>(JointType.AnkleRight, JointType.FootRight));

            // Left Leg
            this.bones.Add(new Tuple <JointType, JointType>(JointType.HipLeft, JointType.KneeLeft));
            this.bones.Add(new Tuple <JointType, JointType>(JointType.KneeLeft, JointType.AnkleLeft));
            this.bones.Add(new Tuple <JointType, JointType>(JointType.AnkleLeft, JointType.FootLeft));

            // populate body colors, one for each BodyIndex
            this.bodyColors = new List <Pen>();

            this.bodyColors.Add(new Pen(Brushes.Red, 6));
            this.bodyColors.Add(new Pen(Brushes.Orange, 6));
            this.bodyColors.Add(new Pen(Brushes.Green, 6));
            this.bodyColors.Add(new Pen(Brushes.Blue, 6));
            this.bodyColors.Add(new Pen(Brushes.Indigo, 6));
            this.bodyColors.Add(new Pen(Brushes.Violet, 6));

            // set IsAvailableChanged event notifier
            this.kinectSensor.IsAvailableChanged += this.Sensor_IsAvailableChanged;

            // open the sensor
            this.kinectSensor.Open();

            // set the status text
            this.StatusText = this.kinectSensor.IsAvailable ? Properties.Resources.RunningStatusText
                                                            : Properties.Resources.NoSensorStatusText;

            // Create the drawing group we'll use for drawing
            this.drawingGroup = new DrawingGroup();

            // Create an image source that we can use in our image control
            this.imageSource = new DrawingImage(this.drawingGroup);

            // use the window object as the view model in this simple example
            this.DataContext = this;

            // initialize the components (controls) of the window
            this.InitializeComponent();
        }
예제 #13
0
        public Task <bool> LoadDocumentAsync(string svgFilePath)
        {
            if (_isLoadingDrawing || string.IsNullOrWhiteSpace(svgFilePath) || !File.Exists(svgFilePath))
            {
#if DOTNET40
                return(TaskEx.FromResult <bool>(false));
#else
                return(Task.FromResult <bool>(false));
#endif
            }

            string fileExt = Path.GetExtension(svgFilePath);

            if (!(string.Equals(fileExt, SvgConverter.SvgExt, StringComparison.OrdinalIgnoreCase) ||
                  string.Equals(fileExt, SvgConverter.CompressedSvgExt, StringComparison.OrdinalIgnoreCase)))
            {
                _svgFilePath = null;
#if DOTNET40
                return(TaskEx.FromResult <bool>(false));
#else
                return(Task.FromResult <bool>(false));
#endif
            }

            _isLoadingDrawing = true;

            this.UnloadDocument(true);

            DirectoryInfo workingDir = _workingDir;
            if (_directoryInfo != null)
            {
                workingDir = _directoryInfo;
            }

            _svgFilePath = svgFilePath;
            _saveXaml    = _optionSettings.ShowOutputFile;

            _embeddedImageVisitor.SaveImages    = !_wpfSettings.IncludeRuntime;
            _embeddedImageVisitor.SaveDirectory = _drawingDir;
            _wpfSettings.Visitors.ImageVisitor  = _embeddedImageVisitor;

            if (_fileReader == null)
            {
                _fileReader          = new FileSvgReader(_wpfSettings);
                _fileReader.SaveXaml = _saveXaml;
                _fileReader.SaveZaml = false;
            }

            var drawingStream = new MemoryStream();

            // Get the UI thread's context
            var context = TaskScheduler.FromCurrentSynchronizationContext();

            return(Task <bool> .Factory.StartNew(() =>
            {
                //                var saveXaml = _fileReader.SaveXaml;
                //                _fileReader.SaveXaml = true; // For threaded, we will save to avoid loading issue later...

                //Stopwatch stopwatch = new Stopwatch();

                //stopwatch.Start();

                //DrawingGroup drawing = _fileReader.Read(svgFilePath, workingDir);

                //stopwatch.Stop();

                //Trace.WriteLine(string.Format("FileName={0}, Time={1}",
                //    Path.GetFileName(svgFilePath), stopwatch.ElapsedMilliseconds));

                Stopwatch watch = new Stopwatch();
                watch.Start();

                DrawingGroup drawing = _fileReader.Read(svgFilePath, workingDir);

                watch.Stop();

                Debug.WriteLine("{0}: {1}", Path.GetFileName(svgFilePath), watch.ElapsedMilliseconds);

                //                _fileReader.SaveXaml = saveXaml;
                _drawingDocument = _fileReader.DrawingDocument;
                if (drawing != null)
                {
                    XamlWriter.Save(drawing, drawingStream);
                    drawingStream.Seek(0, SeekOrigin.Begin);

                    return true;
                }
                _svgFilePath = null;
                return false;
            }).ContinueWith((t) => {
                try
                {
                    if (!t.Result)
                    {
                        _isLoadingDrawing = false;
                        _svgFilePath = null;
                        return false;
                    }
                    if (drawingStream.Length != 0)
                    {
                        DrawingGroup drawing = (DrawingGroup)XamlReader.Load(drawingStream);

                        svgViewer.UnloadDiagrams();
                        svgViewer.RenderDiagrams(drawing);

                        Rect bounds = svgViewer.Bounds;

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

                        zoomPanControl.AnimatedZoomTo(bounds);
                        CommandManager.InvalidateRequerySuggested();

                        // The drawing changed, update the source...
                        _fileReader.Drawing = drawing;
                    }

                    _isLoadingDrawing = false;

                    return true;
                }
                catch
                {
                    _isLoadingDrawing = false;
                    throw;
                }
            }, context));
        }
예제 #14
0
 /**
  * Copy constructor used to copy drawings from read to write
  *
  * @param dgo the drawing group object
  * @param dg the drawing group
  * @param ws the workbook settings
  */
 public Button(DrawingGroupObject dgo,
     DrawingGroup dg,
     WorkbookSettings ws)
 {
     Button d = (Button)dgo;
     Assert.verify(d.origin == Origin.READ);
     msoDrawingRecord = d.msoDrawingRecord;
     objRecord = d.objRecord;
     initialized = false;
     origin = Origin.READ;
     drawingData = d.drawingData;
     drawingGroup = dg;
     drawingNumber = d.drawingNumber;
     drawingGroup.addDrawing(this);
     mso = d.mso;
     txo = d.txo;
     text = d.text;
     formatting = d.formatting;
     workbookSettings = ws;
 }
        //<SnippetGraphicsMMRetrieveDrawings>
        public void RetrieveDrawing(Visual v)
        {
            DrawingGroup drawingGroup = VisualTreeHelper.GetDrawing(v);

            EnumDrawingGroup(drawingGroup);
        }
예제 #16
0
 /**
  * Constructor, used when copying sheets
  *
  * @param d the image to copy
  * @param dg the drawing group
  */
 public WritableImage(DrawingGroupObject d, DrawingGroup dg)
     : base(d, dg)
 {
 }
예제 #17
0
 public CommandToolBarItem(ToolBarItemDefinition toolBarItem, CommandDefinition commandDefinition)
 {
     _toolBarItem = toolBarItem;
     _command     = commandDefinition.Command;
     _icon        = commandDefinition.Icon;
 }
예제 #18
0
        /**
         * Constructor used when reading images
         *
         * @param mso the drawing record
         * @param dd the drawing data for all drawings on this sheet
         * @param dg the drawing group
         */
        public Drawing2(MsoDrawingRecord mso,
            DrawingData dd,
            DrawingGroup dg)
        {
            drawingGroup = dg;
            msoDrawingRecord = mso;
            drawingData = dd;
            initialized = false;
            origin = Origin.READ;
            // there is no drawing number associated with this drawing
            drawingData.addRawData(msoDrawingRecord.getData());
            drawingGroup.addDrawing(this);

            Assert.verify(mso != null);

            initialize();
        }
예제 #19
0
        public bool LoadDocument(string svgFilePath)
        {
            if (string.IsNullOrWhiteSpace(svgFilePath) || !File.Exists(svgFilePath))
            {
                return(false);
            }

            DirectoryInfo workingDir = _workingDir;

            if (_directoryInfo != null)
            {
                workingDir = _directoryInfo;
            }

            this.UnloadDocument(true);

            _svgFilePath = svgFilePath;

            string fileExt = Path.GetExtension(svgFilePath);

            if (string.Equals(fileExt, SvgConverter.SvgExt, StringComparison.OrdinalIgnoreCase) ||
                string.Equals(fileExt, SvgConverter.CompressedSvgExt, StringComparison.OrdinalIgnoreCase))
            {
                if (_fileReader != null)
                {
                    _fileReader.SaveXaml = _saveXaml;
                    _fileReader.SaveZaml = false;

                    DrawingGroup drawing = _fileReader.Read(svgFilePath, workingDir);
                    if (drawing != null)
                    {
                        svgViewer.UnloadDiagrams();
                        svgViewer.RenderDiagrams(drawing);

                        Rect bounds = svgViewer.Bounds;

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

                        zoomPanControl.AnimatedZoomTo(bounds);
                        CommandManager.InvalidateRequerySuggested();

                        return(true);
                    }
                }
            }
            else if (string.Equals(fileExt, SvgConverter.XamlExt, StringComparison.OrdinalIgnoreCase) ||
                     string.Equals(fileExt, SvgConverter.CompressedXamlExt, StringComparison.OrdinalIgnoreCase))
            {
                svgViewer.LoadDiagrams(svgFilePath);

                svgViewer.InvalidateMeasure();

                return(true);
            }

            _svgFilePath = null;

            return(false);
        }
예제 #20
0
 /**
  * Copy constructor used to copy drawings from read to write
  *
  * @param dgo the drawing group object
  * @param dg the drawing group
  * @param ws the workbook settings
  */
 public ComboBox(DrawingGroupObject dgo,
     DrawingGroup dg,
     WorkbookSettings ws)
 {
     ComboBox d = (ComboBox)dgo;
     Assert.verify(d.origin == Origin.READ);
     msoDrawingRecord = d.msoDrawingRecord;
     objRecord = d.objRecord;
     initialized = false;
     origin = Origin.READ;
     drawingData = d.drawingData;
     drawingGroup = dg;
     drawingNumber = d.drawingNumber;
     drawingGroup.addDrawing(this);
     workbookSettings = ws;
 }
예제 #21
0
        public Task <bool> LoadDocumentAsync(string svgFilePath)
        {
            if (_isLoadingDrawing || string.IsNullOrWhiteSpace(svgFilePath) || !File.Exists(svgFilePath))
            {
                return(Task.FromResult <bool>(false));
            }

            DirectoryInfo workingDir = _workingDir;

            if (_directoryInfo != null)
            {
                workingDir = _directoryInfo;
            }

            string fileExt = Path.GetExtension(svgFilePath);

            if (!(string.Equals(fileExt, SvgConverter.SvgExt, StringComparison.OrdinalIgnoreCase) ||
                  string.Equals(fileExt, SvgConverter.CompressedSvgExt, StringComparison.OrdinalIgnoreCase)))
            {
                _svgFilePath = null;
                return(Task.FromResult <bool>(false));
            }

            if (_fileReader == null)
            {
                _fileReader          = new FileSvgReader(_wpfSettings);
                _fileReader.SaveXaml = _saveXaml;
                _fileReader.SaveZaml = false;
            }

            _isLoadingDrawing = true;

            this.UnloadDocument(true);

            _svgFilePath = svgFilePath;

            MemoryStream drawingStream = new MemoryStream();

            // Get the UI thread's context
            var context = TaskScheduler.FromCurrentSynchronizationContext();

            return(Task <bool> .Factory.StartNew(() =>
            {
                var saveXaml = _fileReader.SaveXaml;
                _fileReader.SaveXaml = true; // For threaded, we will save to avoid loading issue later...
                DrawingGroup drawing = _fileReader.Read(svgFilePath, workingDir);
                _fileReader.SaveXaml = saveXaml;
                if (drawing != null)
                {
                    XamlWriter.Save(drawing, drawingStream);
                    drawingStream.Seek(0, SeekOrigin.Begin);

                    return true;
                }
                _svgFilePath = null;
                return false;
            }).ContinueWith((t) => {
                try
                {
                    if (!t.Result)
                    {
                        _isLoadingDrawing = false;
                        _svgFilePath = null;
                        return false;
                    }
                    if (drawingStream.Length != 0)
                    {
                        DrawingGroup drawing = (DrawingGroup)XamlReader.Load(drawingStream);

                        svgViewer.UnloadDiagrams();
                        svgViewer.RenderDiagrams(drawing);

                        Rect bounds = svgViewer.Bounds;

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

                        zoomPanControl.AnimatedZoomTo(bounds);
                        CommandManager.InvalidateRequerySuggested();
                    }

                    _isLoadingDrawing = false;

                    return true;
                }
                catch
                {
                    _isLoadingDrawing = false;
                    throw;
                }
            }, context));
        }
        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;
        }
예제 #23
0
 public void Reload()
 {
     m_image = SVGRender.LoadDrawing(FullPath);
 }
예제 #24
0
        /// <summary>
        /// This converts the SVG resource specified by the Uri to <see cref="DrawingGroup"/>.
        /// </summary>
        /// <param name="svgSource">A <see cref="Uri"/> specifying the source of the SVG resource.</param>
        /// <returns>A <see cref="DrawingGroup"/> of the converted SVG resource.</returns>
        private DrawingGroup GetDrawing(Uri svgSource)
        {
            WpfDrawingSettings settings = new WpfDrawingSettings();

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

            StreamResourceInfo svgStreamInfo = null;

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

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

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

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

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

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

            return(null);
        }
예제 #25
0
 public static void SetSVGImage(DependencyObject obj, DrawingGroup svgimage)
 {
     obj.SetValue(SVGImageProperty, svgimage);
 }
        /// <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);
        }
예제 #27
0
        protected sealed override void OnRender(DrawingContext drawingContext)
        {
            if (Viewport == null)
            {
                return;
            }

            Rect output = Viewport.Output;

            if (output.Width == 0 || output.Height == 0)
            {
                return;
            }
            if (output.IsEmpty)
            {
                return;
            }
            if (Visibility != Visibility.Visible)
            {
                return;
            }

            if (shouldReRender || manualTranslate || renderTarget == RenderTo.Image || beforeFirstUpdate || updateCalled)
            {
                if (graphContents == null)
                {
                    graphContents = new DrawingGroup();
                }
                if (beforeFirstUpdate)
                {
                    Update();
                }

                using (DrawingContext context = graphContents.Open())
                {
                    if (renderTarget == RenderTo.Screen)
                    {
                        RenderState state = CreateRenderState(Viewport.Visible, RenderTo.Screen);
                        OnRenderCore(context, state);
                    }
                    else
                    {
                        // for future use
                    }
                }
                updateCalled = false;
            }

            // thumbnail is not created, if
            // 1) CreateThumbnail is false
            // 2) this graph has IsLayer property, set to false
            if (ShouldCreateThumbnail)
            {
                RenderThumbnail();
            }

            if (!manualClip)
            {
                drawingContext.PushClip(new RectangleGeometry(output));
            }
            bool translate = !manualTranslate && IsTranslated;

            if (translate)
            {
                drawingContext.PushTransform(new TranslateTransform(offset.X, offset.Y));
            }

            drawingContext.DrawDrawing(graphContents);

            if (translate)
            {
                drawingContext.Pop();
            }
            if (!manualClip)
            {
                drawingContext.Pop();
            }
            shouldReRender = true;
        }
예제 #28
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;
            }
        }
예제 #29
0
        private bool ConvertDocument(string filePath = null)
        {
            if (string.IsNullOrWhiteSpace(filePath) || File.Exists(filePath) == false)
            {
                filePath = _svgFilePath;
            }
            try
            {
                if (string.IsNullOrWhiteSpace(filePath) || File.Exists(filePath) == false)
                {
                    return(false);
                }

                DrawingGroup drawing = _fileReader.Read(filePath, _directoryInfo);
                if (drawing == null)
                {
                    return(false);
                }

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

                        // Delete the file after loading it...
                        File.Delete(_xamlFilePath);
                    }
                    else
                    {
                        string xamlFilePath = IoPath.Combine(_directoryInfo.FullName,
                                                             IoPath.GetFileNameWithoutExtension(filePath) + ".xaml");
                        if (File.Exists(xamlFilePath))
                        {
                            _xamlPage.LoadDocument(xamlFilePath);

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

                svgDrawing.UnloadDiagrams();

                svgDrawing.RenderDiagrams(drawing);

                zoomPanControl.InvalidateMeasure();

                Rect bounds = drawing.Bounds;

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

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

                this.ReportError(ex);

                return(false);
            }
        }
예제 #30
0
        /// <summary>
        /// Initializes a new instance of the KinectBodyView class
        /// </summary>
        /// <param name="kinectSensor">Active instance of the KinectSensor</param>
        public DrawSkeleton(KinectSensor kinectSensor, int width, int heigt)
        {
            if (kinectSensor == null)
            {
                throw new ArgumentNullException("kinectSensor");
            }

            // get the coordinate mapper
            this.coordinateMapper = kinectSensor.CoordinateMapper;

            // get the depth (display) extents
            FrameDescription frameDescription = kinectSensor.DepthFrameSource.FrameDescription;

            // get size of joint space
            this.displayWidth  = frameDescription.Width - 20;
            this.displayHeight = frameDescription.Height - 20;
            //this.displayWidth = width;
            //this.displayHeight = height;

            // a bone defined as a line between two joints
            this.bones = new List <Tuple <JointType, JointType> >();

            // Torso
            this.bones.Add(new Tuple <JointType, JointType>(JointType.Head, JointType.Neck));
            this.bones.Add(new Tuple <JointType, JointType>(JointType.Neck, JointType.SpineShoulder));
            this.bones.Add(new Tuple <JointType, JointType>(JointType.SpineShoulder, JointType.SpineMid));
            this.bones.Add(new Tuple <JointType, JointType>(JointType.SpineMid, JointType.SpineBase));
            this.bones.Add(new Tuple <JointType, JointType>(JointType.SpineShoulder, JointType.ShoulderRight));
            this.bones.Add(new Tuple <JointType, JointType>(JointType.SpineShoulder, JointType.ShoulderLeft));
            this.bones.Add(new Tuple <JointType, JointType>(JointType.SpineBase, JointType.HipRight));
            this.bones.Add(new Tuple <JointType, JointType>(JointType.SpineBase, JointType.HipLeft));

            // Right Arm
            this.bones.Add(new Tuple <JointType, JointType>(JointType.ShoulderRight, JointType.ElbowRight));
            this.bones.Add(new Tuple <JointType, JointType>(JointType.ElbowRight, JointType.WristRight));
            this.bones.Add(new Tuple <JointType, JointType>(JointType.WristRight, JointType.HandRight));
            this.bones.Add(new Tuple <JointType, JointType>(JointType.HandRight, JointType.HandTipRight));
            this.bones.Add(new Tuple <JointType, JointType>(JointType.WristRight, JointType.ThumbRight));

            // Left Arm
            this.bones.Add(new Tuple <JointType, JointType>(JointType.ShoulderLeft, JointType.ElbowLeft));
            this.bones.Add(new Tuple <JointType, JointType>(JointType.ElbowLeft, JointType.WristLeft));
            this.bones.Add(new Tuple <JointType, JointType>(JointType.WristLeft, JointType.HandLeft));
            this.bones.Add(new Tuple <JointType, JointType>(JointType.HandLeft, JointType.HandTipLeft));
            this.bones.Add(new Tuple <JointType, JointType>(JointType.WristLeft, JointType.ThumbLeft));

            // Right Leg
            this.bones.Add(new Tuple <JointType, JointType>(JointType.HipRight, JointType.KneeRight));
            this.bones.Add(new Tuple <JointType, JointType>(JointType.KneeRight, JointType.AnkleRight));
            this.bones.Add(new Tuple <JointType, JointType>(JointType.AnkleRight, JointType.FootRight));

            // Left Leg
            this.bones.Add(new Tuple <JointType, JointType>(JointType.HipLeft, JointType.KneeLeft));
            this.bones.Add(new Tuple <JointType, JointType>(JointType.KneeLeft, JointType.AnkleLeft));
            this.bones.Add(new Tuple <JointType, JointType>(JointType.AnkleLeft, JointType.FootLeft));

            // populate body colors, one for each BodyIndex
            this.bodyColors = new List <Pen>();

            //this.bodyColors.Add(new Pen(Brushes.Red, 6));
            //this.bodyColors.Add(new Pen(Brushes.Orange, 6));
            //this.bodyColors.Add(new Pen(Brushes.Green, 6));
            //this.bodyColors.Add(new Pen(Brushes.Blue, 6));
            //this.bodyColors.Add(new Pen(Brushes.Indigo, 6));
            //this.bodyColors.Add(new Pen(Brushes.Violet, 6));

            this.bodyColors.Add(new Pen(Brushes.Yellow, 4));
            this.bodyColors.Add(new Pen(Brushes.Yellow, 4));
            this.bodyColors.Add(new Pen(Brushes.Yellow, 4));
            this.bodyColors.Add(new Pen(Brushes.Yellow, 4));
            this.bodyColors.Add(new Pen(Brushes.Yellow, 4));
            this.bodyColors.Add(new Pen(Brushes.Yellow, 4));

            // Create the drawing group we'll use for drawing
            this.drawingGroup = new DrawingGroup();

            // Create an image source that we can use in our image control
            this.imageSource = new DrawingImage(this.drawingGroup);
        }
        public void Drawing()
        {
            SystemDropShadowChrome s = new SystemDropShadowChrome();

            Assert.AreEqual(s.Color, Color.FromArgb(0x71, 0, 0, 0), "Color");
            Assert.AreEqual(s.CornerRadius.BottomLeft, 0, "CornerRadius 1");
            Assert.AreEqual(s.CornerRadius.BottomRight, 0, "CornerRadius 2");
            Assert.AreEqual(s.CornerRadius.TopLeft, 0, "CornerRadius 3");
            Assert.AreEqual(s.CornerRadius.TopRight, 0, "CornerRadius 4");
            s.Width  = 100;
            s.Height = 100;
            Window w = new Window();

            w.Content = s;
            w.Show();
            DrawingGroup g = VisualTreeHelper.GetDrawing(s);

            Assert.AreEqual(g.Children.Count, 1, "1");
            g = (DrawingGroup)g.Children [0];
            Assert.AreEqual(g.Children.Count, 9, "2");
            Assert.AreEqual(((RectangleGeometry)((GeometryDrawing)g.Children [0]).Geometry).Rect, new Rect(5, 5, 5, 5), "3");
            Assert.AreEqual(((RadialGradientBrush)((GeometryDrawing)g.Children [0]).Brush).Center, new Point(1, 1), "3 brush center");
            Assert.AreEqual(((RadialGradientBrush)((GeometryDrawing)g.Children [0]).Brush).GradientOrigin, new Point(1, 1), "3 gradient origin");
            Assert.AreEqual(((RadialGradientBrush)((GeometryDrawing)g.Children [0]).Brush).RadiusX, 1, "3 radius x");
            Assert.AreEqual(((RadialGradientBrush)((GeometryDrawing)g.Children [0]).Brush).RadiusY, 1, "3 radius y");

            Assert.AreEqual(((RectangleGeometry)((GeometryDrawing)g.Children [1]).Geometry).Rect, new Rect(10, 5, 90, 5), "4");
            Assert.AreEqual(((LinearGradientBrush)((GeometryDrawing)g.Children [1]).Brush).StartPoint, new Point(0, 1), "4 brush start point");
            Assert.AreEqual(((LinearGradientBrush)((GeometryDrawing)g.Children [1]).Brush).EndPoint, new Point(0, 0), "4 brush end point");

            Assert.AreEqual(((RectangleGeometry)((GeometryDrawing)g.Children [2]).Geometry).Rect, new Rect(100, 5, 5, 5), "5");
            Assert.AreEqual(((RadialGradientBrush)((GeometryDrawing)g.Children [2]).Brush).Center, new Point(0, 1), "5 brush center");
            Assert.AreEqual(((RadialGradientBrush)((GeometryDrawing)g.Children [2]).Brush).GradientOrigin, new Point(0, 1), "5 gradient origin");
            Assert.AreEqual(((RadialGradientBrush)((GeometryDrawing)g.Children [2]).Brush).RadiusX, 1, "5 radius x");
            Assert.AreEqual(((RadialGradientBrush)((GeometryDrawing)g.Children [2]).Brush).RadiusY, 1, "5 radius y");

            Assert.AreEqual(((RectangleGeometry)((GeometryDrawing)g.Children [3]).Geometry).Rect, new Rect(5, 10, 5, 90), "6");
            Assert.AreEqual(((LinearGradientBrush)((GeometryDrawing)g.Children [3]).Brush).StartPoint, new Point(1, 0), "6 brush start point");
            Assert.AreEqual(((LinearGradientBrush)((GeometryDrawing)g.Children [3]).Brush).EndPoint, new Point(0, 0), "6 brush end point");

            Assert.AreEqual(((RectangleGeometry)((GeometryDrawing)g.Children [4]).Geometry).Rect, new Rect(100, 10, 5, 90), "7");
            Assert.AreEqual(((LinearGradientBrush)((GeometryDrawing)g.Children [4]).Brush).StartPoint, new Point(0, 0), "7 brush start point");
            Assert.AreEqual(((LinearGradientBrush)((GeometryDrawing)g.Children [4]).Brush).EndPoint, new Point(1, 0), "7 brush end point");

            Assert.AreEqual(((RectangleGeometry)((GeometryDrawing)g.Children [5]).Geometry).Rect, new Rect(5, 100, 5, 5), "8");
            Assert.AreEqual(((RadialGradientBrush)((GeometryDrawing)g.Children [5]).Brush).Center, new Point(1, 0), "8 brush center");
            Assert.AreEqual(((RadialGradientBrush)((GeometryDrawing)g.Children [5]).Brush).GradientOrigin, new Point(1, 0), "8 gradient origin");
            Assert.AreEqual(((RadialGradientBrush)((GeometryDrawing)g.Children [5]).Brush).RadiusX, 1, "8 radius x");
            Assert.AreEqual(((RadialGradientBrush)((GeometryDrawing)g.Children [5]).Brush).RadiusY, 1, "8 radius y");

            Assert.AreEqual(((RectangleGeometry)((GeometryDrawing)g.Children [6]).Geometry).Rect, new Rect(10, 100, 90, 5), "9");
            Assert.AreEqual(((LinearGradientBrush)((GeometryDrawing)g.Children [6]).Brush).StartPoint, new Point(0, 0), "9 brush start point");
            Assert.AreEqual(((LinearGradientBrush)((GeometryDrawing)g.Children [6]).Brush).EndPoint, new Point(0, 1), "9 brush end point");

            Assert.AreEqual(((RectangleGeometry)((GeometryDrawing)g.Children [7]).Geometry).Rect, new Rect(100, 100, 5, 5), "10");
            Assert.AreEqual(((RadialGradientBrush)((GeometryDrawing)g.Children [7]).Brush).Center, new Point(0, 0), "10 brush center");
            Assert.AreEqual(((RadialGradientBrush)((GeometryDrawing)g.Children [7]).Brush).GradientOrigin, new Point(0, 0), "10 gradient origin");
            Assert.AreEqual(((RadialGradientBrush)((GeometryDrawing)g.Children [7]).Brush).RadiusX, 1, "10 radius x");
            Assert.AreEqual(((RadialGradientBrush)((GeometryDrawing)g.Children [7]).Brush).RadiusY, 1, "10 radius y");

            Assert.AreEqual(((RectangleGeometry)((GeometryDrawing)g.Children [8]).Geometry).Rect, new Rect(10, 10, 90, 90), "11");
            Assert.AreEqual(((SolidColorBrush)((GeometryDrawing)g.Children [8]).Brush).Color, s.Color, "10 color");
        }
예제 #32
0
        /**
         * Does the hard work of building up the object graph from the excel bytes
         *
         * @exception BiffException
         * @exception PasswordException if the workbook is password protected
         */
        protected override void parse()
        {
            Record r = null;

            BOFRecord bof = new BOFRecord(excelFile.next());
            workbookBof = bof;
            bofs++;

            if (!bof.isBiff8() && !bof.isBiff7())
                {
                throw new BiffException(BiffException.unrecognizedBiffVersion);
                }

            if (!bof.isWorkbookGlobals())
                {
                throw new BiffException(BiffException.expectedGlobals);
                }
            ArrayList continueRecords = new ArrayList();
            ArrayList localNames = new ArrayList();
            nameTable = new ArrayList();
            addInFunctions = new ArrayList();

            // Skip to the first worksheet
            while (bofs == 1)
                {
                r = excelFile.next();

                if (r.getType() == Type.SST)
                    {
                    continueRecords.Clear();
                    Record nextrec = excelFile.peek();
                    while (nextrec.getType() == Type.CONTINUE)
                        {
                        continueRecords.Add(excelFile.next());
                        nextrec = excelFile.peek();
                        }

                    // cast the array
                    Record[] records = new Record[continueRecords.Count];
                    int pos = 0;
                    foreach (Record record in continueRecords)
                        records[pos++] = record;

                    sharedStrings = new SSTRecord(r,records,settings);
                    }
                else if (r.getType() == Type.FILEPASS)
                    {
                    throw new PasswordException();
                    }
                else if (r.getType() == Type.NAME)
                    {
                    NameRecord nr = null;

                    if (bof.isBiff8())
                        {
                        nr = new NameRecord(r,settings,nameTable.Count);

                        }
                    else
                        {
                        nr = new NameRecord(r,settings,nameTable.Count,
                                            NameRecord.biff7);
                        }

                    // Add all local and global names to the name table in order to
                    // preserve the indexing
                    nameTable.Add(nr);

                    if (nr.isGlobal())
                        namedRecords.Add(nr.getName(),nr);
                    else
                        localNames.Add(nr);
                    }
                else if (r.getType() == Type.FONT)
                    {
                    FontRecord fr = null;

                    if (bof.isBiff8())
                        fr = new FontRecord(r,settings);
                    else
                        fr = new FontRecord(r,settings,FontRecord.biff7);
                    fonts.addFont(fr);
                    }
                else if (r.getType() == Type.PALETTE)
                    {
                    CSharpJExcel.Jxl.Biff.PaletteRecord palette = new CSharpJExcel.Jxl.Biff.PaletteRecord(r);
                    formattingRecords.setPalette(palette);
                    }
                else if (r.getType() == Type.NINETEENFOUR)
                    {
                    NineteenFourRecord nr = new NineteenFourRecord(r);
                    nineteenFour = nr.is1904();
                    }
                else if (r.getType() == Type.FORMAT)
                    {
                    FormatRecord fr = null;
                    if (bof.isBiff8())
                        fr = new FormatRecord(r,settings,FormatRecord.biff8);
                    else
                        fr = new FormatRecord(r,settings,FormatRecord.biff7);
                    try
                        {
                        formattingRecords.addFormat(fr);
                        }
                    catch (NumFormatRecordsException e)
                        {
                        // This should not happen.  Bomb out
                        Assert.verify(false,e.Message);
                        }
                    }
                else if (r.getType() == Type.XF)
                    {
                    XFRecord xfr = null;
                    if (bof.isBiff8())
                        xfr = new XFRecord(r,settings,XFRecord.biff8);
                    else
                        xfr = new XFRecord(r,settings,XFRecord.biff7);

                    try
                        {
                        formattingRecords.addStyle(xfr);
                        }
                    catch (NumFormatRecordsException e)
                        {
                        // This should not happen.  Bomb out
                        Assert.verify(false,e.Message);
                        }
                    }
                else if (r.getType() == Type.BOUNDSHEET)
                    {
                    BoundsheetRecord br = null;

                    if (bof.isBiff8())
                        br = new BoundsheetRecord(r,settings);
                    else
                        br = new BoundsheetRecord(r,BoundsheetRecord.biff7);

                    if (br.isSheet())
                        boundsheets.Add(br);
                    else if (br.isChart() && !settings.getDrawingsDisabled())
                        boundsheets.Add(br);
                    }
                else if (r.getType() == Type.EXTERNSHEET)
                    {
                    if (bof.isBiff8())
                        externSheet = new ExternalSheetRecord(r,settings);
                    else
                        externSheet = new ExternalSheetRecord(r,settings,ExternalSheetRecord.biff7);
                    }
                else if (r.getType() == Type.XCT)
                    {
                    XCTRecord xctr = new XCTRecord(r);
                    xctRecords.Add(xctr);
                    }
                else if (r.getType() == Type.CODEPAGE)
                    {
                    CodepageRecord cr = new CodepageRecord(r);
                    settings.setCharacterSet(cr.getCharacterSet());
                    }
                else if (r.getType() == Type.SUPBOOK)
                    {
                    Record nextrec = excelFile.peek();
                    while (nextrec.getType() == Type.CONTINUE)
                        {
                        r.addContinueRecord(excelFile.next());
                        nextrec = excelFile.peek();
                        }

                    SupbookRecord sr = new SupbookRecord(r,settings);
                    supbooks.Add(sr);
                    }
                else if (r.getType() == Type.EXTERNNAME)
                    {
                    ExternalNameRecord enr = new ExternalNameRecord(r,settings);

                    if (enr.isAddInFunction())
                        {
                        addInFunctions.Add(enr.getName());
                        }
                    }
                else if (r.getType() == Type.PROTECT)
                    {
                    ProtectRecord pr = new ProtectRecord(r);
                    wbProtected = pr.isProtected();
                    }
                else if (r.getType() == Type.OBJPROJ)
                    {
                    doesContainMacros = true;
                    }
                else if (r.getType() == Type.COUNTRY)
                    {
                    countryRecord = new CountryRecord(r);
                    }
                else if (r.getType() == Type.MSODRAWINGGROUP)
                    {
                    if (!settings.getDrawingsDisabled())
                        {
                        msoDrawingGroup = new MsoDrawingGroupRecord(r);

                        if (drawingGroup == null)
                            {
                            drawingGroup = new DrawingGroup(Origin.READ);
                            }

                        drawingGroup.add(msoDrawingGroup);

                        Record nextrec = excelFile.peek();
                        while (nextrec.getType() == Type.CONTINUE)
                            {
                            drawingGroup.add(excelFile.next());
                            nextrec = excelFile.peek();
                            }
                        }
                    }
                else if (r.getType() == Type.BUTTONPROPERTYSET)
                    buttonPropertySet = new ButtonPropertySetRecord(r);
                else if (r.getType() == Type.EOF)
                    bofs--;
                else if (r.getType() == Type.REFRESHALL)
                    {
                    RefreshAllRecord rfm = new RefreshAllRecord(r);
                    settings.setRefreshAll(rfm.getRefreshAll());
                    }
                else if (r.getType() == Type.TEMPLATE)
                    {
                    TemplateRecord rfm = new TemplateRecord(r);
                    settings.setTemplate(rfm.getTemplate());
                    }
                else if (r.getType() == Type.EXCEL9FILE)
                    {
                    Excel9FileRecord e9f = new Excel9FileRecord(r);
                    settings.setExcel9File(e9f.getExcel9File());
                    }
                else if (r.getType() == Type.WINDOWPROTECT)
                    {
                    WindowProtectedRecord winp = new WindowProtectedRecord(r);
                    settings.setWindowProtected(winp.getWindowProtected());
                    }
                else if (r.getType() == Type.HIDEOBJ)
                    {
                    HideobjRecord hobj = new HideobjRecord(r);
                    settings.setHideobj(hobj.getHideMode());
                    }
                else if (r.getType() == Type.WRITEACCESS)
                    {
                    WriteAccessRecord war = new WriteAccessRecord(r,bof.isBiff8(),settings);
                    settings.setWriteAccess(war.getWriteAccess());
                    }
                else
                    {
                    // logger.info("Unsupported record type: " +
                    //            Integer.toHexString(r.getCode())+"h");
                    }
                }

            bof = null;
            if (excelFile.hasNext())
                {
                r = excelFile.next();

                if (r.getType() == Type.BOF)
                    bof = new BOFRecord(r);
                }

            // Only get sheets for which there is a corresponding Boundsheet record
            while (bof != null && getNumberOfSheets() < boundsheets.Count)
                {
                if (!bof.isBiff8() && !bof.isBiff7())
                    throw new BiffException(BiffException.unrecognizedBiffVersion);

                if (bof.isWorksheet())
                    {
                    // Read the sheet in
                    SheetImpl s = new SheetImpl(excelFile,
                                                sharedStrings,
                                                formattingRecords,
                                                bof,
                                                workbookBof,
                                                nineteenFour,
                                                this);

                    BoundsheetRecord br = (BoundsheetRecord)boundsheets[getNumberOfSheets()];
                    s.setName(br.getName());
                    s.setHidden(br.isHidden());
                    addSheet(s);
                    }
                else if (bof.isChart())
                    {
                    // Read the sheet in
                    SheetImpl s = new SheetImpl(excelFile,
                                                sharedStrings,
                                                formattingRecords,
                                                bof,
                                                workbookBof,
                                                nineteenFour,
                                                this);

                    BoundsheetRecord br = (BoundsheetRecord)boundsheets[getNumberOfSheets()];
                    s.setName(br.getName());
                    s.setHidden(br.isHidden());
                    addSheet(s);
                    }
                else
                    {
                    //logger.warn("BOF is unrecognized");

                    while (excelFile.hasNext() && r.getType() != Type.EOF)
                        r = excelFile.next();
                    }

                // The next record will normally be a BOF or empty padding until
                // the end of the block is reached.  In exceptionally unlucky cases,
                // the last EOF  will coincide with a block division, so we have to
                // check there is more data to retrieve.
                // Thanks to liamg for spotting this
                bof = null;
                if (excelFile.hasNext())
                    {
                    r = excelFile.next();

                    if (r.getType() == Type.BOF)
                        bof = new BOFRecord(r);
                    }
                }

            // Add all the local names to the specific sheets
            foreach (NameRecord nr in localNames)
                {
                if (nr.getBuiltInName() == null)
                    {
                    //logger.warn("Usage of a local non-builtin name");
                    }
                else if (nr.getBuiltInName() == BuiltInName.PRINT_AREA ||
                         nr.getBuiltInName() == BuiltInName.PRINT_TITLES)
                    {
                    // appears to use the internal tab number rather than the
                    // external sheet index
                    SheetImpl s = (SheetImpl)sheets[nr.getSheetRef() - 1];
                    s.addLocalName(nr);
                    }
                }
        }
예제 #33
0
        /// <summary>
        /// Функция "отрисовки" объекта
        /// </summary>
        /// <param name="drawingContext">Контекст "отрисовки"</param>
        protected override void OnRender(DrawingContext drawingContext)
        {
            if (_points.Count < 2)
            {
                return;
            }

            var width  = _points[1].Point.X - _points[0].Point.X;
            var height = _points[1].Point.Y - _points[0].Point.Y;
            var pointX = _points[0].Point.X;
            var pointY = _points[0].Point.Y;

            if (_tmpPoint != null)
            {
                if (_tmpPoint.Point.X > _points[0].Point.X)
                {
                    width = _tmpPoint.Point.X - _points[0].Point.X;
                }
                else
                {
                    width  = _points[0].Point.X - _tmpPoint.Point.X;
                    pointX = _tmpPoint.Point.X;
                }

                if (_tmpPoint.Point.Y > _points[0].Point.Y)
                {
                    height = _tmpPoint.Point.Y - _points[0].Point.Y;
                }
                else
                {
                    height = _points[0].Point.Y - _tmpPoint.Point.Y;
                    pointY = _tmpPoint.Point.Y;
                }
            }

            var _drawingGroup = new DrawingGroup();
            var rectGeom1     =
                new GeometryDrawing(
                    _fillColor,
                    new Pen(_strokeColor, _strokeThickness),
                    new RectangleGeometry(new Rect(
                                              pointX,
                                              pointY,
                                              width,
                                              height)
                                          )
                    );

            _drawingGroup.Children.Add(rectGeom1);

            if (_isSelected)
            {
                var selectedColor = new SolidColorBrush()
                {
                    Color   = Colors.LightGray,
                    Opacity = 0.5
                };

                var rectGeom2 =
                    new GeometryDrawing(
                        selectedColor,
                        new Pen(selectedColor, _strokeThickness),
                        new RectangleGeometry(new Rect(
                                                  pointX - 3,
                                                  pointY - 3,
                                                  width + 6,
                                                  height + 6)
                                              )
                        );

                _drawingGroup.Children.Add(rectGeom2);

                if (_tmpPoint != null)
                {
                    var rectGeom3 =
                        new GeometryDrawing(
                            new SolidColorBrush(Color.FromArgb(0, 0, 0, 0)),
                            new Pen(Brushes.Black, 2),
                            new RectangleGeometry(new Rect(
                                                      _points[0].Point.X,
                                                      _points[0].Point.Y,
                                                      _points[1].Point.X - _points[0].Point.X,
                                                      _points[1].Point.Y - _points[0].Point.Y)
                                                  )
                            );

                    _drawingGroup.Children.Add(rectGeom3);
                }
            }

            drawingContext.DrawDrawing(_drawingGroup);
        }
        /**
         * A pseudo copy constructor.  Takes the handles to the font and formatting
         * records
         *
         * @exception IOException
         * @param w the workbook to copy
         * @param os the output stream to write the data to
         * @param cs TRUE if the workbook should close the output stream, FALSE
         * @param ws the configuration for this workbook
         */
        public WritableWorkbookImpl(Stream os,
            Workbook w,
            bool cs,
            WorkbookSettings ws)
            : base()
        {
            CSharpJExcel.Jxl.Read.Biff.WorkbookParser wp = (CSharpJExcel.Jxl.Read.Biff.WorkbookParser)w;

            // Reset the statically declared styles.  These are no longer needed
            // because the Styles class will intercept all calls within
            // CellValue.setCellDetails and if it detects a standard format, then it
            // will return a clone.  In short, the static cell values will
            // never get initialized anyway.  Still, just to be extra sure...
            //lock (SYNCHRONIZER)
            //    {
            //    WritableWorkbook.ARIAL_10_PT.uninitialize();
            //    WritableWorkbook.HYPERLINK_FONT.uninitialize();
            //    WritableWorkbook.NORMAL_STYLE.uninitialize();
            //    WritableWorkbook.HYPERLINK_STYLE.uninitialize();
            //    WritableWorkbook.HIDDEN_STYLE.uninitialize();
            //    DateRecord.defaultDateFormat.uninitialize();
            //    }

            closeStream = cs;
            sheets = new ArrayList();
            sharedStrings = new SharedStrings();
            nameRecords = new Dictionary<string, NameRecord>();
            fonts = wp.getFonts();
            formatRecords = wp.getFormattingRecords();
            wbProtected = false;
            settings = ws;
            rcirCells = new ArrayList();
            styles = new Styles();
            outputFile = new File(os, ws, wp.getCompoundFile());

            containsMacros = false;
            if (!ws.getPropertySetsDisabled())
                containsMacros = wp.containsMacros();

            // Copy the country settings
            if (wp.getCountryRecord() != null)
                countryRecord = new CountryRecord(wp.getCountryRecord());

            // Copy any add in functions
            addInFunctionNames = wp.getAddInFunctionNames();

            // Copy XCT records
            xctRecords = wp.getXCTRecords();

            // Copy any external sheets
            if (wp.getExternalSheetRecord() != null)
                {
                externSheet = new ExternalSheetRecord(wp.getExternalSheetRecord());

                // Get the associated supbooks
                CSharpJExcel.Jxl.Read.Biff.SupbookRecord[] readsr = wp.getSupbookRecords();
                supbooks = new ArrayList(readsr.Length);

                for (int i = 0; i < readsr.Length; i++)
                    {
                    CSharpJExcel.Jxl.Read.Biff.SupbookRecord readSupbook = readsr[i];
                    if (readSupbook.getType() == SupbookRecord.INTERNAL || readSupbook.getType() == SupbookRecord.EXTERNAL)
                        supbooks.Add(new SupbookRecord(readSupbook, settings));
                    else
                        {
                        if (readSupbook.getType() != SupbookRecord.ADDIN)
                            {
                            //logger.warn("unsupported supbook type - ignoring");
                            }
                        }
                    }
                }

            // Copy any drawings.  These must be present before we try and copy
            // the images from the read workbook
            if (wp.getDrawingGroup() != null)
                drawingGroup = new DrawingGroup(wp.getDrawingGroup());

            // Copy the property set references
            if (containsMacros && wp.getButtonPropertySet() != null)
                buttonPropertySet = new ButtonPropertySetRecord(wp.getButtonPropertySet());

            // Copy any names
            if (!settings.getNamesDisabled())
                {
                CSharpJExcel.Jxl.Read.Biff.NameRecord[] na = wp.getNameRecords();
                names = new ArrayList(na.Length);

                for (int i = 0; i < na.Length; i++)
                    {
                    if (na[i].isBiff8())
                        {
                        NameRecord n = new NameRecord(na[i], i);
                        names.Add(n);
                        string key = n.getName() == null ? NULLKEY : n.getName();
                        nameRecords.Add(key, n);
                        }
                    else
                        {
                        //logger.warn("Cannot copy Biff7 name records - ignoring");
                        }
                    }
                }

            copyWorkbook(w);

            // The copy process may have caused some critical fields in the
            // read drawing group to change.  Make sure these updates are reflected
            // in the writable drawing group
            if (drawingGroup != null)
                drawingGroup.updateData(wp.getDrawingGroup());
        }
        private void InitializeBodyFrameDisplayVariables()
        {
            // get the coordinate mapper
            coordinateMapper = sensor.CoordinateMapper;

            // get the depth (display) extents
            FrameDescription frameDescription = sensor.DepthFrameSource.FrameDescription;

            // get size of joint space
            displayWidth  = frameDescription.Width;
            displayHeight = frameDescription.Height;

            // open the reader for the body frames
            bodyFrameReader = sensor.BodyFrameSource.OpenReader();

            // a bone defined as a line between two joints
            bones = new List <Tuple <JointType, JointType> >(
                new Tuple <JointType, JointType>[] {
                // torso
                new Tuple <JointType, JointType>(JointType.Head, JointType.Neck),
                new Tuple <JointType, JointType>(JointType.Neck, JointType.SpineShoulder),
                new Tuple <JointType, JointType>(JointType.SpineShoulder, JointType.SpineMid),
                new Tuple <JointType, JointType>(JointType.SpineMid, JointType.SpineBase),
                new Tuple <JointType, JointType>(JointType.SpineShoulder, JointType.ShoulderRight),
                new Tuple <JointType, JointType>(JointType.SpineShoulder, JointType.ShoulderLeft),
                new Tuple <JointType, JointType>(JointType.SpineBase, JointType.HipRight),
                new Tuple <JointType, JointType>(JointType.SpineBase, JointType.HipLeft),

                // right arm
                new Tuple <JointType, JointType>(JointType.ShoulderRight, JointType.ElbowRight),
                new Tuple <JointType, JointType>(JointType.ElbowRight, JointType.WristRight),
                new Tuple <JointType, JointType>(JointType.WristRight, JointType.HandRight),
                new Tuple <JointType, JointType>(JointType.HandRight, JointType.HandTipRight),
                new Tuple <JointType, JointType>(JointType.WristRight, JointType.ThumbRight),

                // Left Arm
                new Tuple <JointType, JointType>(JointType.ShoulderLeft, JointType.ElbowLeft),
                new Tuple <JointType, JointType>(JointType.ElbowLeft, JointType.WristLeft),
                new Tuple <JointType, JointType>(JointType.WristLeft, JointType.HandLeft),
                new Tuple <JointType, JointType>(JointType.HandLeft, JointType.HandTipLeft),
                new Tuple <JointType, JointType>(JointType.WristLeft, JointType.ThumbLeft),

                // Right Leg
                new Tuple <JointType, JointType>(JointType.HipRight, JointType.KneeRight),
                new Tuple <JointType, JointType>(JointType.KneeRight, JointType.AnkleRight),
                new Tuple <JointType, JointType>(JointType.AnkleRight, JointType.FootRight),

                // Left Leg
                new Tuple <JointType, JointType>(JointType.HipLeft, JointType.KneeLeft),
                new Tuple <JointType, JointType>(JointType.KneeLeft, JointType.AnkleLeft),
                new Tuple <JointType, JointType>(JointType.AnkleLeft, JointType.FootLeft)
            }
                );

            // populate body colors, one for each BodyIndex
            bodyColors = new List <Pen>();

            bodyColors.Add(new Pen(Brushes.Red, 6));
            bodyColors.Add(new Pen(Brushes.Orange, 6));
            bodyColors.Add(new Pen(Brushes.Green, 6));
            bodyColors.Add(new Pen(Brushes.Blue, 6));
            bodyColors.Add(new Pen(Brushes.Indigo, 6));
            bodyColors.Add(new Pen(Brushes.Violet, 6));

            // Create the drawing group we'll use for drawing
            drawingGroup = new DrawingGroup();

            // Create an image source that we can use in our image control
            imageSource = new DrawingImage(drawingGroup);

            // use the window object as the view model in this simple example
            DataContext = this;
        }
        /**
         * Create a drawing group for this workbook - used when importing sheets
         * which contain drawings, but this workbook doesn't.
         * We can't subsume this into the getDrawingGroup() method because the
         * null-ness of the return value is used elsewhere to determine the
         * origin of the workbook
         */
        public DrawingGroup createDrawingGroup()
        {
            if (drawingGroup == null)
                drawingGroup = new DrawingGroup(Origin.WRITE);

            return drawingGroup;
        }
예제 #37
0
        public override void BeforeRender(WpfDrawingRenderer renderer)
        {
            base.BeforeRender(renderer);

            WpfDrawingContext context = renderer.Context;

            _drawGroup = new DrawingGroup();

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

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

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

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

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

            SvgSvgElement svgElm = (SvgSvgElement)_svgElement;

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

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

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

            XmlNode parentNode = _svgElement.ParentNode;

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

            Transform transform = null;

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

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

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

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

                //DrawingGroup animationGroup = context.Links;
                //if (animationGroup != null)
                //{
                //    animationGroup.ClipGeometry = clipGeom;
                //}
            }
        }
예제 #38
0
 /**
  * Copy constructor used to copy drawings from read to write
  *
  * @param dgo the drawing group object
  * @param dg the drawing group
  */
 protected Drawing2(DrawingGroupObject dgo,DrawingGroup dg)
 {
     Drawing2 d = (Drawing2)dgo;
     Assert.verify(d.origin == Origin.READ);
     msoDrawingRecord = d.msoDrawingRecord;
     initialized = false;
     origin = Origin.READ;
     drawingData = d.drawingData;
     drawingGroup = dg;
     drawingNumber = d.drawingNumber;
     drawingGroup.addDrawing(this);
 }
        /// <summary>
        /// Converts a ViewModel into a DrawingImage
        /// </summary>
        /// <param name="value">A ViewModel</param>
        /// <param name="targetType">The parameter is not used.</param>
        /// <param name="parameter">The parameter is not used.</param>
        /// <param name="culture">The parameter is not used.</param>
        /// <returns>Returns a DrawingImage that has The visualized ViewModel on it</returns>
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            ViewModel model = (ViewModel)value;

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

            BuildingToGeometryConverter  bConv       = new BuildingToGeometryConverter();
            ExplosionToGeometryConverter eConv       = new ExplosionToGeometryConverter();
            IMovableToGeometryConverter  movableConv = new IMovableToGeometryConverter();

            GeometryGroup          buildingGeo     = (GeometryGroup)bConv.Convert(model.Buildings, null, null, null);
            GeometryGroup          explosionGeo    = (GeometryGroup)eConv.Convert(model.Explosions, null, null, null);
            List <GeometryDrawing> movableDrawings = (List <GeometryDrawing>)movableConv.Convert(model.Movables, null, model, null);

            DrawingGroup dg = new DrawingGroup();

            // We need to make sure that our play area is as big as we want it by applying a background
            dg.Children.Add(new GeometryDrawing(new SolidColorBrush(Color.FromRgb(0, 0, 0)), null, new RectangleGeometry(new Rect(0, 0, MainWindow.Grid.ActualWidth, MainWindow.Grid.ActualHeight))));

            // We want a single texture on each building, so we need to apply the brush on each building geometry
            foreach (Geometry singleBuilding in buildingGeo.Children)
            {
                if (singleBuilding is RectangleGeometry)
                {
                    // The building itself
                    Pen bPen = new Pen(Brushes.White, 0.5);
                    bPen.DashStyle = DashStyles.Dash;
                    dg.Children.Add(new GeometryDrawing(model.GetBuildingBrush(singleBuilding.Bounds.X, singleBuilding.Bounds.Y), bPen, singleBuilding));
                }
                else if (singleBuilding is GeometryGroup)
                {
                    GeometryGroup gg = (GeometryGroup)singleBuilding;
                    if (gg.Children.Count == 2)
                    {
                        // A shield with its HP
                        dg.Children.Add(new GeometryDrawing(model.GetShieldBrush(singleBuilding.Bounds.X, singleBuilding.Bounds.Y), null, gg.Children[0]));
                        dg.Children.Add(new GeometryDrawing(Brushes.Black, null, gg.Children[1]));
                    }
                    else
                    {
                        // The building's curHP/maxHP
                        dg.Children.Add(new GeometryDrawing(Brushes.Black, null, gg));
                    }
                }
            }

            foreach (EllipseGeometry singleExplosion in explosionGeo.Children)
            {
                SolidColorBrush brush;
                if (singleExplosion.Bounds.Height > MainWindow.Grid.ActualHeight)
                {
                    brush = Brushes.Orange;
                }
                else
                {
                    brush = Brushes.Transparent;
                }

                dg.Children.Add(new GeometryDrawing(brush, new Pen(Brushes.White, 2), singleExplosion));
            }

            foreach (GeometryDrawing movableDrawing in movableDrawings)
            {
                dg.Children.Add(movableDrawing);
            }

            DrawingImage img = new DrawingImage();

            img.Drawing = dg;
            return(img);
        }
예제 #40
0
        /**
         * Constructor used when reading images
         *
         * @param mso the drawing record
         * @param obj the object record
         * @param dd the drawing data for all drawings on this sheet
         * @param dg the drawing group
         * @param ws the workbook settings
         */
        public ComboBox(MsoDrawingRecord mso,ObjRecord obj,DrawingData dd,
            DrawingGroup dg,WorkbookSettings ws)
        {
            drawingGroup = dg;
            msoDrawingRecord = mso;
            drawingData = dd;
            objRecord = obj;
            initialized = false;
            workbookSettings = ws;
            origin = Origin.READ;
            drawingData.addData(msoDrawingRecord.getData());
            drawingNumber = drawingData.getNumDrawings() - 1;
            drawingGroup.addDrawing(this);

            Assert.verify(mso != null && obj != null);

            initialize();
        }
예제 #41
0
        public void Render(DrawingContext drawingContext, PointSet[] setsToDraw, Matrix m)
        {
            renderWatch.Restart();
            DrawingGroup group = new DrawingGroup();

            group.Transform = new MatrixTransform(m);

            foreach (PointSet set in setsToDraw)
            {
                Object          drawingObj = set.linkedObjects[CacheDrawingsType];
                GeometryDrawing drawing;

                Object val     = set.linkedObjects[CacheLastHashDrawingType];
                uint   oldHash = 0;
                if (val != null)
                {
                    oldHash = (uint)val;
                }
                uint nowHash = set.hash;

                if (drawingObj != null && oldHash == nowHash)
                {
                    drawing = drawingObj as GeometryDrawing;
                }
                else
                {
                    ColoredGeometry cg = (ColoredGeometry)set.linkedObjects[CacheColoredGeometryType];
                    drawing = new GeometryDrawing(
                        (cg.brushColor == null) ? null : new SolidColorBrush((Color)cg.brushColor),
                        (cg.penColor == null) ? null : new Pen(new SolidColorBrush((Color)cg.penColor), 1),
                        cg.g);
                    set.linkedObjects[CacheDrawingsType] = drawing;
                }
                set.linkedObjects[CacheLastHashDrawingType] = nowHash;

                drawing.Freeze();
                group.Children.Add(drawing);
            }
            //group.Freeze();


            foreach (Cluster c in world.pointsManager.clusters)
            {
                if (c != null && c.idZ == -1)// && c.idX >= world.pointsManager.li && c.idX <= world.pointsManager.ri && c.idY >= world.pointsManager.ti && c.idY <= world.pointsManager.bi)
                {
                    Geometry g = new RectangleGeometry(
                        new Rect(
                            new Point(c.x, c.y),
                            new Point(c.x + c.size, c.y + c.size))
                        );
                    g.Freeze();
                    Color color = Colors.DarkGreen;
                    group.Children.Add(
                        new GeometryDrawing(null, new Pen(new SolidColorBrush(color), c.idZ * 10 + 1), g)
                        );
                }
            }

            group.Children.Add(
                new GeometryDrawing(
                    Brushes.Black, null, new EllipseGeometry(new Point(0, 0), 20, 20)
                    )
                );

            drawingContext.DrawDrawing(group);

            lock (renderTimes)
            {
                renderTimes.Add(renderWatch.ElapsedMilliseconds);
                if (renderTimes.Count > checkTimes)
                {
                    renderTimes.RemoveAt(0);
                }
            }
        }
예제 #42
0
 /**
  * Sets the drawing group for this drawing.  Called by the drawing group
  * when this drawing is added to it
  *
  * @param dg the drawing group
  */
 public virtual void setDrawingGroup(DrawingGroup dg)
 {
     drawingGroup = dg;
 }
예제 #43
0
        /**
         * Constructor used when reading images
         *
         * @param mso the drawing record
         * @param obj the object record
         * @param dd the drawing data for all drawings on this sheet
         * @param dg the drawing group
         */
        public Drawing(MsoDrawingRecord mso,
            ObjRecord obj,
            DrawingData dd,
            DrawingGroup dg,
            Sheet s)
        {
            drawingGroup = dg;
            msoDrawingRecord = mso;
            drawingData = dd;
            objRecord = obj;
            sheet = s;
            initialized = false;
            origin = Origin.READ;
            drawingData.addData(msoDrawingRecord.getData());
            drawingNumber = drawingData.getNumDrawings() - 1;
            drawingGroup.addDrawing(this);

            Assert.verify(mso != null && obj != null);

            initialize();
        }