void DrawScene(DrawingContext dc) {
   dc.DrawEllipse(new SolidColorBrush(Color.FromArgb(255, 200, 200, 200)), null, new Point(50, 18), 12, 12);
   dc.DrawEllipse(new SolidColorBrush(Color.FromArgb(255, 200, 200, 200)), new Pen(new SolidColorBrush(Color.FromArgb(255, 100, 100, 100)), 3), new Point(50, 51), 12, 12);
   dc.DrawEllipse(null, new Pen(new SolidColorBrush(Color.FromArgb(255, 100, 100, 100)), 3), new Point(50, 87), 12, 12);
   
   dc.DrawRectangle(new SolidColorBrush(Color.FromArgb(255, 200, 200, 200)), null, new Rect(25, 111, 24, 24));
   dc.DrawRectangle(new SolidColorBrush(Color.FromArgb(255, 200, 200, 200)), new Pen(new SolidColorBrush(Color.FromArgb(255, 100, 100, 100)), 3), new Rect(25, 147, 24, 24));
   dc.DrawRectangle(null, new Pen(new SolidColorBrush(Color.FromArgb(255, 100, 100, 100)), 3), new Rect(25, 184, 24, 24));
   
   dc.DrawRoundedRectangle(new SolidColorBrush(Color.FromArgb(255, 200, 200, 200)), null, new Rect(25, 237, 24, 24), 5, 5);
   dc.DrawRoundedRectangle(new SolidColorBrush(Color.FromArgb(255, 200, 200, 200)), new Pen(new SolidColorBrush(Color.FromArgb(255, 100, 100, 100)), 3), new Rect(25, 270, 24, 24), 5, 5);
   dc.DrawRoundedRectangle(null, new Pen(new SolidColorBrush(Color.FromArgb(255, 100, 100, 100)), 3), new Rect(25, 307, 24, 24), 5, 5);
   
   dc.DrawLine(new Pen(new SolidColorBrush(Color.FromArgb(255, 100, 100, 100)), 3), new Point(50, 340), new Point (70, 360));
 }
Example #2
0
        public void OnDraw(object sender, DrawingContext context)
        {
            double height = 0;
            double width  = 0;
            List <KeyValuePair <int, FormattedText> > _text = new List <KeyValuePair <int, FormattedText> >();

            for (int i = 0; i < displayPrimes.Count; i++)
            {
                DisplayPrime p = displayPrimes[i];

                StringBuilder text = new StringBuilder(p.Prime.Name);
                text.Append(p.Prime.Name.Length < 20 ? "\t\t" : "\t");
                text.Append(p.DucatValue + " Ducats");

                if (p.PlatinumPrice != "?")
                {
                    text.Append("\t" + p.PlatinumPrice + " Plat");
                }

                if (!string.IsNullOrWhiteSpace(p.Data.Notes))
                {
                    text.Append("\t" + p.Data.Notes);
                }

                SolidColorBrush color = p.Data.NumberOwned >= 1 ? Brushes.CadetBlue : Brushes.OrangeRed;
                // Draw a formatted text string into the DrawingContext.
                FormattedText Ftext = new FormattedText(text.ToString(), CultureInfo.GetCultureInfo("en-us"), FlowDirection.LeftToRight,
                                                        Typeface, 13, color, MainWindow.pixelsPerDip);

                height = Ftext.Height;

                if (width < Ftext.Width)
                {
                    width = Ftext.Width;
                }

                _text.Add(new KeyValuePair <int, FormattedText>(i, Ftext));
            }

            //Draw a rectangle bellow the text for easier reading
            context?.DrawRectangle(brush, pen, new Rect(drawStartX - 10, drawStartY - 10, width + 20, ((height + 5) * displayPrimes.Count) + displayPrimes.Count * 7));

            foreach (KeyValuePair <int, FormattedText> keyValuePair in _text)
            {
                context.DrawText(keyValuePair.Value, new Point(drawStartX, (drawStartY + 25 * keyValuePair.Key)));
            }
        }
Example #3
0
            protected override void OnRender(DrawingContext dc)
            {
                string testString = "Formatted MML Document is displayed here!\nPlease implement the user oriented layout logic.";

                FormattedText formattedText = new FormattedText(testString, CultureInfo.CurrentCulture, FlowDirection.LeftToRight, new Typeface("Verdana"), 30, Brushes.Black);

                formattedText.MaxTextWidth = 280;
                formattedText.MaxTextHeight = 280;

                formattedText.SetForegroundBrush(new LinearGradientBrush(Colors.Blue, Colors.Teal, 90.0), 10, 12);

                formattedText.SetFontStyle(FontStyles.Italic, 36, 5);
                formattedText.SetForegroundBrush(new LinearGradientBrush(Colors.Pink, Colors.Crimson, 90.0), 36, 5);
                formattedText.SetFontSize(36, 36, 5);

                formattedText.SetFontWeight(FontWeights.Bold, 42, 48);

                dc.DrawRectangle(Brushes.White, null, new Rect(0, 0, 300, 300));

                dc.DrawText(formattedText, new Point(10, 10));
            }
Example #4
0
        protected override void OnRender(DrawingContext drawingContext)
        {
            base.OnRender(drawingContext);

            var track = game.Track;

            dirtBrush.Viewport = new Rect(0, 0, 0.5f / track.Tiles.GetLength(0), 0.5f / track.Tiles.GetLength(1));
            drawingContext.DrawRectangle(dirtBrush, null, new Rect(0, 0, Track.CELLSIZE * track.Tiles.GetLength(0), Track.CELLSIZE * track.Tiles.GetLength(1)));

            for (var x = 0; x < track.Tiles.GetLength(0); x++)
            {
                for (var y = 0; y < track.Tiles.GetLength(1); y++)
                {
                    switch (track.Tiles[x, y])
                    {
                    case TrackTile.Gras: DrawTile(drawingContext, TrackTile.Gras, x, y, grasTiles); break;

                    case TrackTile.Sand: DrawTile(drawingContext, TrackTile.Sand, x, y, sandTiles); break;

                    case TrackTile.Road: DrawTile(drawingContext, TrackTile.Road, x, y, roadTiles); break;

                    case TrackTile.GoalDown:
                        drawingContext.DrawRectangle(goalVerticalLeft, null, new Rect(
                                                         (x * Track.CELLSIZE),
                                                         (y * Track.CELLSIZE) + (Track.CELLSIZE / 2),
                                                         Track.CELLSIZE / 2, Track.CELLSIZE / 2));
                        drawingContext.DrawRectangle(goalVerticalRight, null, new Rect(
                                                         (x * Track.CELLSIZE) + (Track.CELLSIZE / 2),
                                                         (y * Track.CELLSIZE) + (Track.CELLSIZE / 2),
                                                         Track.CELLSIZE / 2, Track.CELLSIZE / 2));
                        drawingContext.DrawRectangle(roadTiles[TileType.Left], null, new Rect(
                                                         (x * Track.CELLSIZE),
                                                         (y * Track.CELLSIZE),
                                                         Track.CELLSIZE / 2, Track.CELLSIZE / 2));
                        drawingContext.DrawRectangle(roadTiles[TileType.Right], null, new Rect(
                                                         (x * Track.CELLSIZE) + (Track.CELLSIZE / 2),
                                                         (y * Track.CELLSIZE),
                                                         Track.CELLSIZE / 2, Track.CELLSIZE / 2));
                        drawingContext.DrawRectangle(startPositionDown, null, new Rect(
                                                         (x * Track.CELLSIZE),
                                                         (y * Track.CELLSIZE),
                                                         Track.CELLSIZE / 2, Track.CELLSIZE / 2));
                        drawingContext.DrawRectangle(startPositionDown, null, new Rect(
                                                         (x * Track.CELLSIZE) + (Track.CELLSIZE / 2),
                                                         (y * Track.CELLSIZE),
                                                         Track.CELLSIZE / 2, Track.CELLSIZE / 2));
                        break;

                    case TrackTile.GoalLeft:
                        drawingContext.DrawRectangle(goalHorizontalTop, null, new Rect(
                                                         (x * Track.CELLSIZE),
                                                         (y * Track.CELLSIZE),
                                                         Track.CELLSIZE / 2, Track.CELLSIZE / 2));
                        drawingContext.DrawRectangle(goalHorizontalBottom, null, new Rect(
                                                         (x * Track.CELLSIZE),
                                                         (y * Track.CELLSIZE) + (Track.CELLSIZE / 2),
                                                         Track.CELLSIZE / 2, Track.CELLSIZE / 2));
                        drawingContext.DrawRectangle(roadTiles[TileType.Upper], null, new Rect(
                                                         (x * Track.CELLSIZE) + (Track.CELLSIZE / 2),
                                                         (y * Track.CELLSIZE),
                                                         Track.CELLSIZE / 2, Track.CELLSIZE / 2));
                        drawingContext.DrawRectangle(roadTiles[TileType.Lower], null, new Rect(
                                                         (x * Track.CELLSIZE) + (Track.CELLSIZE / 2),
                                                         (y * Track.CELLSIZE) + (Track.CELLSIZE / 2),
                                                         Track.CELLSIZE / 2, Track.CELLSIZE / 2));
                        drawingContext.DrawRectangle(startPositionLeft, null, new Rect(
                                                         (x * Track.CELLSIZE) + (Track.CELLSIZE / 2),
                                                         (y * Track.CELLSIZE),
                                                         Track.CELLSIZE / 2, Track.CELLSIZE / 2));
                        drawingContext.DrawRectangle(startPositionLeft, null, new Rect(
                                                         (x * Track.CELLSIZE) + (Track.CELLSIZE / 2),
                                                         (y * Track.CELLSIZE) + (Track.CELLSIZE / 2),
                                                         Track.CELLSIZE / 2, Track.CELLSIZE / 2));
                        break;

                    case TrackTile.GoalRight:
                        drawingContext.DrawRectangle(goalHorizontalTop, null, new Rect(
                                                         (x * Track.CELLSIZE) + (Track.CELLSIZE / 2),
                                                         (y * Track.CELLSIZE),
                                                         Track.CELLSIZE / 2, Track.CELLSIZE / 2));
                        drawingContext.DrawRectangle(goalHorizontalBottom, null, new Rect(
                                                         (x * Track.CELLSIZE) + (Track.CELLSIZE / 2),
                                                         (y * Track.CELLSIZE) + (Track.CELLSIZE / 2),
                                                         Track.CELLSIZE / 2, Track.CELLSIZE / 2));
                        drawingContext.DrawRectangle(roadTiles[TileType.Upper], null, new Rect(
                                                         (x * Track.CELLSIZE),
                                                         (y * Track.CELLSIZE),
                                                         Track.CELLSIZE / 2, Track.CELLSIZE / 2));
                        drawingContext.DrawRectangle(roadTiles[TileType.Lower], null, new Rect(
                                                         (x * Track.CELLSIZE),
                                                         (y * Track.CELLSIZE) + (Track.CELLSIZE / 2),
                                                         Track.CELLSIZE / 2, Track.CELLSIZE / 2));
                        drawingContext.DrawRectangle(startPositionRight, null, new Rect(
                                                         (x * Track.CELLSIZE),
                                                         (y * Track.CELLSIZE),
                                                         Track.CELLSIZE / 2, Track.CELLSIZE / 2));
                        drawingContext.DrawRectangle(startPositionRight, null, new Rect(
                                                         (x * Track.CELLSIZE),
                                                         (y * Track.CELLSIZE) + (Track.CELLSIZE / 2),
                                                         Track.CELLSIZE / 2, Track.CELLSIZE / 2));
                        break;

                    case TrackTile.GoalUp:
                        drawingContext.DrawRectangle(goalVerticalLeft, null, new Rect(
                                                         (x * Track.CELLSIZE),
                                                         (y * Track.CELLSIZE),
                                                         Track.CELLSIZE / 2, Track.CELLSIZE / 2));
                        drawingContext.DrawRectangle(goalVerticalRight, null, new Rect(
                                                         (x * Track.CELLSIZE) + (Track.CELLSIZE / 2),
                                                         (y * Track.CELLSIZE),
                                                         Track.CELLSIZE / 2, Track.CELLSIZE / 2));
                        drawingContext.DrawRectangle(roadTiles[TileType.Left], null, new Rect(
                                                         (x * Track.CELLSIZE),
                                                         (y * Track.CELLSIZE) + (Track.CELLSIZE / 2),
                                                         Track.CELLSIZE / 2, Track.CELLSIZE / 2));
                        drawingContext.DrawRectangle(roadTiles[TileType.Right], null, new Rect(
                                                         (x * Track.CELLSIZE) + (Track.CELLSIZE / 2),
                                                         (y * Track.CELLSIZE) + (Track.CELLSIZE / 2),
                                                         Track.CELLSIZE / 2, Track.CELLSIZE / 2));
                        drawingContext.DrawRectangle(startPositionUp, null, new Rect(
                                                         (x * Track.CELLSIZE),
                                                         (y * Track.CELLSIZE) + (Track.CELLSIZE / 2),
                                                         Track.CELLSIZE / 2, Track.CELLSIZE / 2));
                        drawingContext.DrawRectangle(startPositionUp, null, new Rect(
                                                         (x * Track.CELLSIZE) + (Track.CELLSIZE / 2),
                                                         (y * Track.CELLSIZE) + (Track.CELLSIZE / 2),
                                                         Track.CELLSIZE / 2, Track.CELLSIZE / 2));
                        break;
                    }
                }
            }
        }
Example #5
0
 protected override void OnRender(DrawingContext drawingContext)
 {
     base.OnRender(drawingContext);
     drawingContext.DrawRectangle(brush, pen, rect);
 }
Example #6
0
        private void Reader_FrameArrived(object sender, BodyFrameArrivedEventArgs e)
        {
            bool player       = true;
            bool dataReceived = false;

            using (BodyFrame bodyFrame = e.FrameReference.AcquireFrame())
            {
                if (bodyFrame != null)
                {
                    if (this.bodies == null)
                    {
                        this.bodies = new Body[bodyFrame.BodyCount];
                    }

                    // The first time GetAndRefreshBodyData is called, Kinect will allocate each Body in the array.
                    // As long as those body objects are not disposed and not set to null in the array,
                    // those body objects will be re-used.
                    bodyFrame.GetAndRefreshBodyData(this.bodies);
                    dataReceived = true;
                }
            }
            if (dataReceived)
            {
                using (DrawingContext dc = this.drawingGroup.Open())
                {
                    // Draw a transparent background to set the render size
                    dc.DrawRectangle(Brushes.Transparent, null, new Rect(0.0, 0.0, this.displayWidth, this.displayHeight));
                    Pen line = new Pen(Brushes.Red, 1);
                    // Pen line2 = new Pen(Brushes.Red, 4);
                    dc.DrawLine(line, new Point(0, 335), new Point(600, 335));
                    // dc.DrawLine(line2, new Point(ElbowRightX, ElbowRightY), new Point(ElbowRightX , ElbowRightY+2));
                    // dc.DrawEllipse(EllipseBrush, null, new Point(350, 232), 5, 5);
                    int penIndex = 0;
                    foreach (Body body in this.bodies)
                    {
                        Pen drawPen = this.bodyColors[penIndex++];

                        /* if (!Headplay) { Pen drawPen = this.bodyColors[penIndex--]; }
                         * else { Pen drawPen = this.bodyColors[penIndex++]; }*/
                        if (body.IsTracked && player && Headplay)
                        {
                            player = false;
                            //this.DrawClippedEdges(body, dc);

                            IReadOnlyDictionary <JointType, Joint> joints = body.Joints;

                            // convert the joint points to depth (display) space

                            Dictionary <JointType, Point> jointPoints = new Dictionary <JointType, Point>();

                            foreach (JointType jointType in joints.Keys)
                            {
                                // sometimes the depth(Z) of an inferred joint may show as negative
                                // clamp down to 0.1f to prevent coordinatemapper from returning (-Infinity, -Infinity)
                                CameraSpacePoint position = joints[jointType].Position;
                                if (position.Z < 0)
                                {
                                    position.Z = InferredZPositionClamp;
                                }
                                DepthSpacePoint depthSpacePoint = this.coordinateMapper.MapCameraPointToDepthSpace(position);
                                jointPoints[jointType] = new Point(depthSpacePoint.X, depthSpacePoint.Y);
                            }
                            ProcessGesture(jointPoints);
                            //depthGOGO(jointPoints);
                            this.DrawBody(joints, jointPoints, dc, drawPen);
                            this.DrawHand(body.HandLeftState, jointPoints[JointType.HandLeft], dc);
                            this.DrawHand(body.HandRightState, jointPoints[JointType.HandRight], dc);
                            if (jointPoints[JointType.HandLeft].X > (jointPoints[JointType.ShoulderRight].X) + 10 && righthand == false && start)
                            {
                                righthand = true;
                                lefthand  = false;
                                SendKeyDown(Key.PageUp);
                            }
                            if (jointPoints[JointType.HandLeft].X <jointPoints[JointType.ShoulderRight].X && jointPoints[JointType.HandRight].X> jointPoints[JointType.ShoulderLeft].X && start)
                            {
                                righthand = false;
                                lefthand  = false;
                            }
                            if (jointPoints[JointType.HandRight].X < (jointPoints[JointType.ShoulderLeft].X) - 10 && lefthand == false && start)
                            {
                                lefthand  = true;
                                righthand = false;
                                SendKeyDown(Key.PageDown);
                            }
                        }
                    }

                    // prevent drawing outside of our render area
                    this.drawingGroup.ClipGeometry = new RectangleGeometry(new Rect(0.0, 0.0, this.displayWidth, this.displayHeight));
                }
            }
        }
Example #7
0
        protected override void OnRender(DrawingContext dc)
        {
            m_BoxEnd.X = this.ScreenGrid.Width;
            m_BoxEnd.Y = this.ScreenGrid.Height;

            SolidColorBrush backgroundBrush = new SolidColorBrush();

            backgroundBrush = BackColor as SolidColorBrush;
            Pen outerRectPen = new Pen(m_BorderColor, m_BorderWidth);

            // Main outer rectangle ...
            Rect outerRect = new Rect(m_Start, m_BoxEnd);

            dc.DrawRectangle(backgroundBrush, outerRectPen, outerRect);

            FormattedText printText;

            List <TelemetryObject> dispTelemetry = new List <TelemetryObject>();

            dispTelemetry = telemetryCollection;

            foreach (TelemetryObject thisObj in dispTelemetry.ToList <TelemetryObject>())
            {
                // Increment Y value
                thisObj.yPos++;

                //------ Advance the active item -------
                thisObj.yPos = thisObj.yPos + (m_ScrollSpeed / m_SpeedMultiplier);
                printBrush   = activeBrush;

                // -- Display the active data ...
                char[] printArray = thisObj.telemetryData.ToCharArray();
                for (int printCount = 0; printCount < thisObj.telemetryData.Length; printCount++)
                {
                    // Print the Item Vertical
                    printText = new FormattedText(
                        printArray[printCount].ToString().ToUpper(),
                        CultureInfo.GetCultureInfo("en-us"),
                        FlowDirection.LeftToRight,
                        new Typeface("Georgia"),
                        10,
                        printBrush);
                    // Do not draw outside the box ...
                    //          if ( (thisObj.yPos + (printCount * charTall)) < m_BoxEnd.Y)
                    if (((thisObj.yPos - (int)(printCount * charTall)) + BorderWidth < m_BoxEnd.Y) && ((thisObj.yPos - (int)printCount * charTall) > m_Start.Y + m_YStart))
                    {
                        dc.DrawText(printText, new Point(thisObj.xPos, thisObj.yPos + (printCount * charTall)));
                    }
                }

                //-- Trail behind the active item ...
                //if (thisObj.yPos > (thisObj.telemetryData.Length * charTall))
                for (float trailCount = 0; trailCount < (thisObj.tailArray.Length - 1); trailCount++)
                {
                    if (trailCount <= m_TailFrontLength)
                    {
                        printBrush = trailBrush;
                    }
                    else
                    {
                        printBrush = ghostBrush;
                    }
                    printText = new FormattedText(
                        thisObj.tailArray[(int)trailCount].ToString(),
                        CultureInfo.GetCultureInfo("en-us"),
                        FlowDirection.LeftToRight,
                        new Typeface("Verdana"),
                        10,
                        printBrush);
                    // Do not draw outside the box ...  Bottom && Top
                    if (((thisObj.yPos - (int)(trailCount * charTall)) + BorderWidth < m_BoxEnd.Y) && ((thisObj.yPos - (int)trailCount * charTall) > m_Start.Y + m_YStart))
                    {
                        dc.DrawText(printText, new Point(thisObj.xPos, ((thisObj.yPos - charTall) - (int)trailCount * charTall)));
                    }
                }
            }

            // -- Clear out any items that have scrolled off screen...
            List <TelemetryObject> cleanedCollection = new List <TelemetryObject>();

            foreach (TelemetryObject thisObj in telemetryCollection)
            {
                if ((m_BoxEnd.Y + (thisObj.tailArray.Length * charTall) + (thisObj.telemetryData.Length * charTall)) > thisObj.yPos)
                {
                    cleanedCollection.Add(thisObj);
                }
                else
                {
                    xPos[(int)thisObj.xPos] = 0;
                    //printStatus("Remove: " + thisObj.telemetryData, dc);
                }
            }
            telemetryCollection = cleanedCollection;

            foreach (GhostObject ghostTrail in ghostCollection)
            {
                // Advance ghost scrollers
                ghostTrail.yPos = ghostTrail.yPos + (m_GhostScrollSpeed / m_SpeedMultiplier);
                printBrush      = ghostBrush;
                char[] printArray = ghostTrail.tailArray;
                for (int printCount = 0; printCount < ghostTrail.tailArray.Length; printCount++)
                {
                    // Print the Item Vertical
                    printText = new FormattedText(
                        printArray[printCount].ToString(),
                        CultureInfo.GetCultureInfo("en-us"),
                        FlowDirection.LeftToRight,
                        new Typeface(m_GhostFont),
                        10,
                        printBrush);
                    // Do not draw outside the box ...  Bottom && Top
                    if (((ghostTrail.yPos - (int)(printCount * charTall)) + BorderWidth < m_BoxEnd.Y) && ((ghostTrail.yPos - (int)printCount * charTall) > m_Start.Y + m_YStart))
                    {
                        dc.DrawText(printText, new Point(ghostTrail.xPos, ((ghostTrail.yPos - charTall) - (int)printCount * charTall)));
                    }
                }
            }
            // -- Clear out any items that have scrolled off screen...
            List <GhostObject> cleanedGhostCollection = new List <GhostObject>();

            foreach (GhostObject thisObj in ghostCollection)
            {
                if ((m_BoxEnd.Y + (thisObj.tailArray.Length * charTall)) > thisObj.yPos)
                {
                    cleanedGhostCollection.Add(thisObj);
                }
                else
                {
                    // Replace the one removed...
                    GhostObject newGO           = new GhostObject();
                    int         nextGhostTrailx = 0;
                    nextGhostTrailx = getNextGhostTrailx();
                    int randHeight = rand.Next((int)(m_BoxEnd.Y - (20 * charTall)), 100);
                    newGO.xPos = nextGhostTrailx;
                    newGO.yPos = randHeight;
                    cleanedGhostCollection.Add(newGO);
                }
            }
            ghostCollection = cleanedGhostCollection;
        }
Example #8
0
        /// <summary>
        /// Render callback.
        /// </summary>
        protected override void OnRender(DrawingContext drawingContext)
        {
            CornerRadius cornerRadius = CornerRadius;

            Rect shadowBounds = new Rect(new Point(ShadowDepth, ShadowDepth),
                                         new Size(RenderSize.Width, RenderSize.Height));
            Color color = Color;

            if (shadowBounds.Width > 0 && shadowBounds.Height > 0 && color.A > 0)
            {
                // The shadow is drawn with a dark center the size of the shadow bounds
                // deflated by shadow depth on each side.
                double centerWidth  = shadowBounds.Right - shadowBounds.Left - 2 * ShadowDepth;
                double centerHeight = shadowBounds.Bottom - shadowBounds.Top - 2 * ShadowDepth;

                // Clamp corner radii to be less than 1/2 the side of the inner shadow bounds
                double maxRadius = Math.Min(centerWidth * 0.5, centerHeight * 0.5);
                cornerRadius.TopLeft     = Math.Min(cornerRadius.TopLeft, maxRadius);
                cornerRadius.TopRight    = Math.Min(cornerRadius.TopRight, maxRadius);
                cornerRadius.BottomLeft  = Math.Min(cornerRadius.BottomLeft, maxRadius);
                cornerRadius.BottomRight = Math.Min(cornerRadius.BottomRight, maxRadius);

                // Get the brushes for the 9 regions
                Brush[] brushes = GetBrushes(color, cornerRadius);

                // Snap grid to device pixels
                double centerTop    = shadowBounds.Top + ShadowDepth;
                double centerLeft   = shadowBounds.Left + ShadowDepth;
                double centerRight  = shadowBounds.Right - ShadowDepth;
                double centerBottom = shadowBounds.Bottom - ShadowDepth;

                // Because of different corner radii there are 6 potential x (or y) lines to snap to
                double[] guidelineSetX = new double[] { centerLeft,
                                                        centerLeft + cornerRadius.TopLeft,
                                                        centerRight - cornerRadius.TopRight,
                                                        centerLeft + cornerRadius.BottomLeft,
                                                        centerRight - cornerRadius.BottomRight,
                                                        centerRight };

                double[] guidelineSetY = new double[] { centerTop,
                                                        centerTop + cornerRadius.TopLeft,
                                                        centerTop + cornerRadius.TopRight,
                                                        centerBottom - cornerRadius.BottomLeft,
                                                        centerBottom - cornerRadius.BottomRight,
                                                        centerBottom };

                drawingContext.PushGuidelineSet(new GuidelineSet(guidelineSetX, guidelineSetY));

                // The corner rectangles are drawn drawn ShadowDepth pixels bigger to
                // account for the blur
                cornerRadius.TopLeft     = cornerRadius.TopLeft + ShadowDepth;
                cornerRadius.TopRight    = cornerRadius.TopRight + ShadowDepth;
                cornerRadius.BottomLeft  = cornerRadius.BottomLeft + ShadowDepth;
                cornerRadius.BottomRight = cornerRadius.BottomRight + ShadowDepth;


                // Draw Top row
                Rect topLeft = new Rect(shadowBounds.Left, shadowBounds.Top, cornerRadius.TopLeft, cornerRadius.TopLeft);
                drawingContext.DrawRectangle(brushes[TopLeft], null, topLeft);

                double topWidth = guidelineSetX[2] - guidelineSetX[1];
                if (topWidth > 0)
                {
                    Rect top = new Rect(guidelineSetX[1], shadowBounds.Top, topWidth, ShadowDepth);
                    drawingContext.DrawRectangle(brushes[Top], null, top);
                }

                Rect topRight = new Rect(guidelineSetX[2], shadowBounds.Top, cornerRadius.TopRight, cornerRadius.TopRight);
                drawingContext.DrawRectangle(brushes[TopRight], null, topRight);

                // Middle row
                double leftHeight = guidelineSetY[3] - guidelineSetY[1];
                if (leftHeight > 0)
                {
                    Rect left = new Rect(shadowBounds.Left, guidelineSetY[1], ShadowDepth, leftHeight);
                    drawingContext.DrawRectangle(brushes[Left], null, left);
                }

                double rightHeight = guidelineSetY[4] - guidelineSetY[2];
                if (rightHeight > 0)
                {
                    Rect right = new Rect(guidelineSetX[5], guidelineSetY[2], ShadowDepth, rightHeight);
                    drawingContext.DrawRectangle(brushes[Right], null, right);
                }

                // Bottom row
                Rect bottomLeft = new Rect(shadowBounds.Left, guidelineSetY[3], cornerRadius.BottomLeft, cornerRadius.BottomLeft);
                drawingContext.DrawRectangle(brushes[BottomLeft], null, bottomLeft);

                double bottomWidth = guidelineSetX[4] - guidelineSetX[3];
                if (bottomWidth > 0)
                {
                    Rect bottom = new Rect(guidelineSetX[3], guidelineSetY[5], bottomWidth, ShadowDepth);
                    drawingContext.DrawRectangle(brushes[Bottom], null, bottom);
                }

                Rect bottomRight = new Rect(guidelineSetX[4], guidelineSetY[4], cornerRadius.BottomRight, cornerRadius.BottomRight);
                drawingContext.DrawRectangle(brushes[BottomRight], null, bottomRight);


                // Fill Center

                // Because the heights of the top/bottom rects and widths of the left/right rects are fixed
                // and the corner rects are drawn with the size of the corner, the center
                // may not be a square.  In this case, create a path to fill the area

                // When the target object's corner radius is 0, only need to draw one rect
                if (cornerRadius.TopLeft == ShadowDepth &&
                    cornerRadius.TopLeft == cornerRadius.TopRight &&
                    cornerRadius.TopLeft == cornerRadius.BottomLeft &&
                    cornerRadius.TopLeft == cornerRadius.BottomRight)
                {
                    // All corners of target are 0, render one large rectangle
                    Rect center = new Rect(guidelineSetX[0], guidelineSetY[0], centerWidth, centerHeight);
                    drawingContext.DrawRectangle(brushes[Center], null, center);
                }
                else
                {
                    // If the corner radius is TL=2, TR=1, BL=0, BR=2 the following shows the shape that needs to be created.
                    //             _________________
                    //            |                 |_
                    //         _ _|                   |
                    //        |                       |
                    //        |                    _ _|
                    //        |                   |
                    //        |___________________|
                    // The missing corners of the shape are filled with the radial gradients drawn above

                    // Define shape counter clockwise
                    PathFigure figure = new PathFigure();

                    if (cornerRadius.TopLeft > ShadowDepth)
                    {
                        figure.StartPoint = new Point(guidelineSetX[1], guidelineSetY[0]);
                        figure.Segments.Add(new LineSegment(new Point(guidelineSetX[1], guidelineSetY[1]), true));
                        figure.Segments.Add(new LineSegment(new Point(guidelineSetX[0], guidelineSetY[1]), true));
                    }
                    else
                    {
                        figure.StartPoint = new Point(guidelineSetX[0], guidelineSetY[0]);
                    }

                    if (cornerRadius.BottomLeft > ShadowDepth)
                    {
                        figure.Segments.Add(new LineSegment(new Point(guidelineSetX[0], guidelineSetY[3]), true));
                        figure.Segments.Add(new LineSegment(new Point(guidelineSetX[3], guidelineSetY[3]), true));
                        figure.Segments.Add(new LineSegment(new Point(guidelineSetX[3], guidelineSetY[5]), true));
                    }
                    else
                    {
                        figure.Segments.Add(new LineSegment(new Point(guidelineSetX[0], guidelineSetY[5]), true));
                    }

                    if (cornerRadius.BottomRight > ShadowDepth)
                    {
                        figure.Segments.Add(new LineSegment(new Point(guidelineSetX[4], guidelineSetY[5]), true));
                        figure.Segments.Add(new LineSegment(new Point(guidelineSetX[4], guidelineSetY[4]), true));
                        figure.Segments.Add(new LineSegment(new Point(guidelineSetX[5], guidelineSetY[4]), true));
                    }
                    else
                    {
                        figure.Segments.Add(new LineSegment(new Point(guidelineSetX[5], guidelineSetY[5]), true));
                    }


                    if (cornerRadius.TopRight > ShadowDepth)
                    {
                        figure.Segments.Add(new LineSegment(new Point(guidelineSetX[5], guidelineSetY[2]), true));
                        figure.Segments.Add(new LineSegment(new Point(guidelineSetX[2], guidelineSetY[2]), true));
                        figure.Segments.Add(new LineSegment(new Point(guidelineSetX[2], guidelineSetY[0]), true));
                    }
                    else
                    {
                        figure.Segments.Add(new LineSegment(new Point(guidelineSetX[5], guidelineSetY[0]), true));
                    }

                    figure.IsClosed = true;
                    figure.Freeze();

                    PathGeometry geometry = new PathGeometry();
                    geometry.Figures.Add(figure);
                    geometry.Freeze();

                    drawingContext.DrawGeometry(brushes[Center], null, geometry);
                }

                drawingContext.Pop();
            }
        }
Example #9
0
        private void Render(Point location)
        {
            int  textStorePosition = 0;
            bool flipped;

            if (ParentAtom == null)
            {
                flipped = false;
            }
            else
            {
                flipped = Flipped;
            }

            var textStore = new FunctionalGroupTextSource(ParentGroup, flipped);

            //main textformatter - this does the writing of the visual
            using (TextFormatter textFormatter = TextFormatter.Create())
            {
                //set up the default paragraph properties
                var paraprops = new FunctionalGroupTextSource.GenericTextParagraphProperties(
                    FlowDirection.LeftToRight,
                    TextAlignment.Left,
                    true,
                    false,
                    new LabelTextRunProperties(),
                    TextWrapping.NoWrap,
                    GlyphText.SymbolSize,
                    0d);

                var    anchorRuns   = textStore.Runs.Where(f => f.IsAnchor);
                string anchorString = string.Empty;
                foreach (var run in anchorRuns)
                {
                    anchorString += run.Text;
                }

                using (TextLine myTextLine =
                           textFormatter.FormatLine(textStore, textStorePosition, 999, paraprops, null))
                {
                    IList <TextBounds> textBounds;
                    Rect firstRect = Rect.Empty;
                    if (!Flipped) //isolate them at the beginning
                    {
                        textBounds = myTextLine.GetTextBounds(0, anchorString.Length);
                    }
                    else
                    {
                        //isolate them at the end
                        var start = myTextLine.Length - 1 - anchorString.Length;
                        textBounds = myTextLine.GetTextBounds(start, anchorString.Length);
                    }

                    //add all the bounds together
                    foreach (TextBounds anchorBound in textBounds)
                    {
                        firstRect.Union(anchorBound.Rectangle);
                    }

                    //center will be position close to the origin 0,0
                    Point center = new Point((firstRect.Left + firstRect.Right) / 2,
                                             (firstRect.Top + firstRect.Bottom) / 2);

                    //the displacement vector will be added to each relative coordinate for the glyph run
                    var displacementVector = location - center;

                    //locus is where the text line is drawn
                    var locus = new Point(0, 0) + displacementVector;

                    textBounds = myTextLine.GetTextBounds(0, 999);
                    var obb = textBounds[0].Rectangle;

                    //draw the line of text
                    using (DrawingContext dc = RenderOpen())
                    {
                        myTextLine.Draw(dc, locus, InvertAxes.None);
#if DEBUG
#if SHOWBOUNDS
                        obb.Offset(new Vector(locus.X, locus.Y));
                        dc.DrawRectangle(null, new Pen(new SolidColorBrush(Colors.BlueViolet), 1.0), obb);
#endif
#endif
                        var          glyphRuns     = myTextLine.GetIndexedGlyphRuns();
                        List <Point> outline       = new List <Point>();
                        double       advanceWidths = 0d;

                        //build up the convex hull from each glyph
                        //you need to add in the advance widths for each
                        //glyph run as they are traversed,
                        //to the outline
                        foreach (IndexedGlyphRun igr in glyphRuns)
                        {
                            var originalRun = textStore.GetTextRun(igr.TextSourceCharacterIndex);
                            var currentRun  = igr.GlyphRun;
                            //need to work out how much the current run has been offset from the baseline
                            var runBounds =
                                myTextLine.GetTextBounds(igr.TextSourceCharacterIndex, igr.TextSourceLength);
                            //get the bounding rect
                            var rect = runBounds[0].TextRunBounds[0].Rectangle;

                            //it's relative to the baseline
                            //adjust it
                            rect.Offset(new Vector(locus.X, locus.Y));
                            var rectCopy = rect;
#if DEBUG
#if SHOWBOUNDS
                            dc.DrawRectangle(null, new Pen(new SolidColorBrush(Colors.DarkOrange), 1.0), rect);
#endif
#endif
                            var runOutline = GlyphUtils.GetOutline(currentRun);
                            //need to see if the run has been super or sub-scripted
                            var variants = originalRun.Properties.TypographyProperties.Variants;
                            if (variants == FontVariants.Subscript || variants == FontVariants.Superscript)
                            {
                                //simply union in the rect -it's easier!
                                outline.AddRange(new[]
                                {
                                    rectCopy.BottomLeft, rectCopy.BottomRight, rectCopy.TopLeft,
                                    rectCopy.TopRight
                                });
                            }
                            else
                            {
                                //add in the points from the convex hull
                                for (int i = 0; i < runOutline.Count; i++)
                                {
                                    var point = runOutline[i] + displacementVector +
                                                new Vector(0.0, myTextLine.Baseline);
                                    point.X      += advanceWidths;
                                    runOutline[i] = point;
                                }

                                outline.AddRange(runOutline);
                            }

                            advanceWidths += currentRun.AdvanceWidths.Sum();
                        }

                        _sortedOutline = (from Point p in outline
                                          orderby p.X ascending, p.Y descending
                                          select p).ToList();

                        Hull = Geometry <Point> .GetHull(_sortedOutline, p => p);

                        // Diag: Show Hulls or Atom centres
#if DEBUG
#if SHOWHULLS
                        dc.DrawGeometry(null, new Pen(Brushes.GreenYellow, thickness: 1), HullGeometry);
#endif
#if SHOWATOMCENTRES
                        dc.DrawEllipse(Brushes.Red, null, ParentAtom.Position, 5, 5);
#endif
#endif
                        // End Diag
                        dc.Close();
                    }
                }
            }
        }
Example #10
0
 /// <summary>
 /// When overriden in a class, this method allows the execution of code whenever the element has been rendered
 /// </summary>
 ///<param name="drawingContext">The <see cref="DrawingContext"/> in which the element has been rendered</param>
 protected override void OnRender(DrawingContext drawingContext)
 {
     if (this.Background != null)
     {
         drawingContext.DrawRectangle(this.RenderTarget, Thickness.Empty, this.Background, null);
     }
     foreach (UIElement element in this.Children)
     {
         element.Render(drawingContext);
     }
 }
        /// <summary>
        /// GetPointsAtMiddleSegment
        /// </summary>
        internal void GetPointsAtMiddleSegment(StrokeNode previous,
                                               double angleBetweenNodes,
                                               List <Point> abPoints,
                                               List <Point> dcPoints,
                                               out bool missingIntersection
#if DEBUG_RENDERING_FEEDBACK
                                               , DrawingContext debugDC, double feedbackSize, bool showFeedback
#endif
                                               )
        {
            missingIntersection = false;
            if (IsValid && previous.IsValid)
            {
                Quad quad1 = previous.ConnectingQuad;
                if (!quad1.IsEmpty)
                {
                    Quad quad2 = ConnectingQuad;
                    if (!quad2.IsEmpty)
                    {
                        if (IsEllipse)
                        {
                            Rect node1Bounds = _operations.GetNodeBounds(previous._lastNode);
                            Rect node2Bounds = _operations.GetNodeBounds(_lastNode);
                            Rect node3Bounds = _operations.GetNodeBounds(_thisNode);
#if DEBUG_RENDERING_FEEDBACK
                            if (showFeedback)
                            {
                                debugDC.DrawEllipse(null, new Pen(Brushes.Pink, feedbackSize / 2), _lastNode.Position, node2Bounds.Width / 2, node2Bounds.Height / 2);
                            }
#endif
                            if (angleBetweenNodes == 0.0d || ((quad1.B == quad2.A) && (quad1.C == quad2.D)))
                            {
                                //quads connections are the same, just add them
                                abPoints.Add(quad1.B);
                                dcPoints.Add(quad1.C);
#if DEBUG_RENDERING_FEEDBACK
                                if (showFeedback)
                                {
                                    debugDC.DrawEllipse(Brushes.Green, null, quad1.B, feedbackSize, feedbackSize);
                                    debugDC.DrawEllipse(Brushes.Yellow, null, quad1.C, feedbackSize, feedbackSize);
                                }
#endif
                            }
                            else if (angleBetweenNodes > 0.0)
                            {
                                //the stroke angled towards the AB side
                                //this part is easy
                                if (quad1.B == quad2.A)
                                {
                                    abPoints.Add(quad1.B);
#if DEBUG_RENDERING_FEEDBACK
                                    if (showFeedback)
                                    {
                                        debugDC.DrawEllipse(Brushes.Green, null, quad1.B, feedbackSize, feedbackSize);
                                    }
#endif
                                }
                                else
                                {
                                    Point intersection = GetIntersection(quad1.A, quad1.B, quad2.A, quad2.B);
                                    Rect  union        = Rect.Union(node1Bounds, node2Bounds);
                                    union.Inflate(1.0, 1.0);
                                    //make sure we're not off in space

#if DEBUG_RENDERING_FEEDBACK
                                    if (showFeedback)
                                    {
                                        debugDC.DrawEllipse(Brushes.Green, null, quad1.B, feedbackSize * 1.5, feedbackSize * 1.5);
                                        debugDC.DrawEllipse(Brushes.Red, null, quad2.A, feedbackSize, feedbackSize);
                                    }
#endif

                                    if (union.Contains(intersection))
                                    {
                                        abPoints.Add(intersection);
#if DEBUG_RENDERING_FEEDBACK
                                        if (showFeedback)
                                        {
                                            debugDC.DrawEllipse(Brushes.Orange, null, intersection, feedbackSize, feedbackSize);
                                        }
#endif
                                    }
                                    else
                                    {
                                        //if we missed the intersection we'll need to close the stroke segment
                                        //this work is done in StrokeRenderer
                                        missingIntersection = true;
                                        return; //we're done.
                                    }
                                }

                                if (quad1.C == quad2.D)
                                {
                                    dcPoints.Add(quad1.C);
#if DEBUG_RENDERING_FEEDBACK
                                    if (showFeedback)
                                    {
                                        debugDC.DrawEllipse(Brushes.Yellow, null, quad1.C, feedbackSize, feedbackSize);
                                    }
#endif
                                }
                                else
                                {
                                    //add instructions to arc from quad1.C to quad2.D in reverse order (since we walk this array backwards to render)
                                    dcPoints.Add(quad1.C);
                                    dcPoints.Add(new Point(node2Bounds.Width, node2Bounds.Height));
                                    dcPoints.Add(StrokeRenderer.ArcToMarker);
                                    dcPoints.Add(quad2.D);
#if DEBUG_RENDERING_FEEDBACK
                                    if (showFeedback)
                                    {
                                        debugDC.DrawEllipse(Brushes.Yellow, null, quad1.C, feedbackSize, feedbackSize);
                                        debugDC.DrawEllipse(Brushes.Blue, null, quad2.D, feedbackSize, feedbackSize);
                                    }
#endif
                                }
                            }
                            else
                            {
                                //the stroke angled towards the CD side
                                //this part is easy
                                if (quad1.C == quad2.D)
                                {
                                    dcPoints.Add(quad1.C);
#if DEBUG_RENDERING_FEEDBACK
                                    if (showFeedback)
                                    {
                                        debugDC.DrawEllipse(Brushes.Yellow, null, quad1.C, feedbackSize, feedbackSize);
                                    }
#endif
                                }
                                else
                                {
                                    Point intersection = GetIntersection(quad1.D, quad1.C, quad2.D, quad2.C);
                                    Rect  union        = Rect.Union(node1Bounds, node2Bounds);
                                    union.Inflate(1.0, 1.0);
                                    //make sure we're not off in space

#if DEBUG_RENDERING_FEEDBACK
                                    if (showFeedback)
                                    {
                                        debugDC.DrawEllipse(Brushes.Yellow, null, quad1.C, feedbackSize * 1.5, feedbackSize * 1.5);
                                        debugDC.DrawEllipse(Brushes.Blue, null, quad2.D, feedbackSize, feedbackSize);
                                    }
#endif

                                    if (union.Contains(intersection))
                                    {
                                        dcPoints.Add(intersection);
#if DEBUG_RENDERING_FEEDBACK
                                        if (showFeedback)
                                        {
                                            debugDC.DrawEllipse(Brushes.Orange, null, intersection, feedbackSize, feedbackSize);
                                        }
#endif
                                    }
                                    else
                                    {
                                        //if we missed the intersection we'll need to close the stroke segment
                                        //this work is done in StrokeRenderer
                                        missingIntersection = true;
                                        return; //we're done.
                                    }
                                }

                                if (quad1.B == quad2.A)
                                {
                                    abPoints.Add(quad1.B);
#if DEBUG_RENDERING_FEEDBACK
                                    if (showFeedback)
                                    {
                                        debugDC.DrawEllipse(Brushes.Green, null, quad1.B, feedbackSize, feedbackSize);
                                    }
#endif
                                }
                                else
                                {
                                    //we need to arc between quad1.B and quad2.A along node2
                                    abPoints.Add(quad1.B);
                                    abPoints.Add(StrokeRenderer.ArcToMarker);
                                    abPoints.Add(new Point(node2Bounds.Width, node2Bounds.Height));
                                    abPoints.Add(quad2.A);
#if DEBUG_RENDERING_FEEDBACK
                                    if (showFeedback)
                                    {
                                        debugDC.DrawEllipse(Brushes.Green, null, quad1.B, feedbackSize, feedbackSize);
                                        debugDC.DrawEllipse(Brushes.Red, null, quad2.A, feedbackSize, feedbackSize);
                                    }
#endif
                                }
                            }
                        }
                        else
                        {
                            //rectangle
                            int indexA = -1;
                            int indexB = -1;
                            int indexC = -1;
                            int indexD = -1;

                            Vector[] vertices       = _operations.GetVertices();
                            double   pressureFactor = _lastNode.PressureFactor;
                            for (int i = 0; i < vertices.Length; i++)
                            {
                                Point point = _lastNode.Position + (vertices[i % vertices.Length] * pressureFactor);
                                if (point == quad2.A)
                                {
                                    indexA = i;
                                }
                                if (point == quad1.B)
                                {
                                    indexB = i;
                                }
                                if (point == quad1.C)
                                {
                                    indexC = i;
                                }
                                if (point == quad2.D)
                                {
                                    indexD = i;
                                }
                            }

                            if (indexA == -1 || indexB == -1 || indexC == -1 || indexD == -1)
                            {
                                Debug.Assert(false, "Couldn't find all 4 indexes in StrokeNodeOperations.GetPointsAtMiddleSegment");
                                return;
                            }

#if DEBUG_RENDERING_FEEDBACK
                            if (showFeedback)
                            {
                                debugDC.DrawRectangle(null, new Pen(Brushes.Pink, feedbackSize / 2), _operations.GetNodeBounds(_lastNode));
                                debugDC.DrawEllipse(Brushes.Red, null, quad2.A, feedbackSize, feedbackSize);
                                debugDC.DrawEllipse(Brushes.Green, null, quad1.B, feedbackSize, feedbackSize);
                                debugDC.DrawEllipse(Brushes.Yellow, null, quad1.C, feedbackSize, feedbackSize);
                                debugDC.DrawEllipse(Brushes.Blue, null, quad2.D, feedbackSize, feedbackSize);
                            }
#endif

                            Rect node3Rect = _operations.GetNodeBounds(_thisNode);
                            //take care of a-b first
                            if (indexA == indexB)
                            {
                                //quad connection is the same, just add it
                                if (!node3Rect.Contains(quad1.B))
                                {
                                    abPoints.Add(quad1.B);
                                }
                            }
                            else if ((indexA == 0 && indexB == 3) || ((indexA != 3 || indexB != 0) && (indexA > indexB)))
                            {
                                if (!node3Rect.Contains(quad1.B))
                                {
                                    abPoints.Add(quad1.B);
                                }
                                if (!node3Rect.Contains(quad2.A))
                                {
                                    abPoints.Add(quad2.A);
                                }
                            }
                            else
                            {
                                Point intersection = GetIntersection(quad1.A, quad1.B, quad2.A, quad2.B);
                                Rect  node12       = Rect.Union(_operations.GetNodeBounds(previous._lastNode), _operations.GetNodeBounds(_lastNode));
                                node12.Inflate(1.0, 1.0);
                                //make sure we're not off in space
                                if (node12.Contains(intersection))
                                {
                                    abPoints.Add(intersection);
#if DEBUG_RENDERING_FEEDBACK
                                    if (showFeedback)
                                    {
                                        debugDC.DrawEllipse(Brushes.Orange, null, intersection, feedbackSize, feedbackSize * 1.5);
                                    }
#endif
                                }
                                else
                                {
                                    //if we missed the intersection we'll need to close the stroke segment
                                    //this work is done in StrokeRenderer.
                                    missingIntersection = true;
                                    return; //we're done.
                                }
                            }

                            // now take care of c-d.
                            if (indexC == indexD)
                            {
                                //quad connection is the same, just add it
                                if (!node3Rect.Contains(quad1.C))
                                {
                                    dcPoints.Add(quad1.C);
                                }
                            }
                            else if ((indexC == 0 && indexD == 3) || ((indexC != 3 || indexD != 0) && (indexC > indexD)))
                            {
                                if (!node3Rect.Contains(quad1.C))
                                {
                                    dcPoints.Add(quad1.C);
                                }
                                if (!node3Rect.Contains(quad2.D))
                                {
                                    dcPoints.Add(quad2.D);
                                }
                            }
                            else
                            {
                                Point intersection = GetIntersection(quad1.D, quad1.C, quad2.D, quad2.C);
                                Rect  node12       = Rect.Union(_operations.GetNodeBounds(previous._lastNode), _operations.GetNodeBounds(_lastNode));
                                node12.Inflate(1.0, 1.0);
                                //make sure we're not off in space
                                if (node12.Contains(intersection))
                                {
                                    dcPoints.Add(intersection);
#if DEBUG_RENDERING_FEEDBACK
                                    if (showFeedback)
                                    {
                                        debugDC.DrawEllipse(Brushes.Orange, null, intersection, feedbackSize, feedbackSize * 1.5);
                                    }
#endif
                                }
                                else
                                {
                                    //if we missed the intersection we'll need to close the stroke segment
                                    //this work is done in StrokeRenderer.
                                    missingIntersection = true;
                                    return; //we're done.
                                }
                            }
                        }
                    }
                }
            }
        }
        /// <summary>
        /// GetPointsAtEndOfSegment
        /// </summary>
        internal void GetPointsAtEndOfSegment(List <Point> abPoints,
                                              List <Point> dcPoints
#if DEBUG_RENDERING_FEEDBACK
                                              , DrawingContext debugDC, double feedbackSize, bool showFeedback
#endif
                                              )
        {
            if (IsValid)
            {
                Quad quad = ConnectingQuad;
                if (IsEllipse)
                {
                    Rect bounds = GetBounds();
                    //add instructions to arc from D to A
                    abPoints.Add(quad.B);
                    abPoints.Add(StrokeRenderer.ArcToMarker);
                    abPoints.Add(new Point(bounds.Width, bounds.Height));
                    abPoints.Add(quad.C);

                    //don't add to the dc points
#if DEBUG_RENDERING_FEEDBACK
                    if (showFeedback)
                    {
                        debugDC.DrawEllipse(null, new Pen(Brushes.Pink, feedbackSize / 2), _thisNode.Position, bounds.Width / 2, bounds.Height / 2);
                        debugDC.DrawEllipse(Brushes.Green, null, quad.B, feedbackSize, feedbackSize);
                        debugDC.DrawEllipse(Brushes.Yellow, null, quad.C, feedbackSize, feedbackSize);
                    }
#endif
                }
                else
                {
#if DEBUG_RENDERING_FEEDBACK
                    if (showFeedback)
                    {
                        debugDC.DrawRectangle(null, new Pen(Brushes.Pink, feedbackSize / 2), GetBounds());
                    }
#endif
                    //we're interested in the B, C points as well as the
                    //nodecountour points between them
                    double   pressureFactor = _thisNode.PressureFactor;
                    Vector[] vertices       = _operations.GetVertices();
                    int      maxCount       = vertices.Length * 2;
                    int      i = 0;
                    for (; i < maxCount; i++)
                    {
                        //look for the d point first
                        Point point = _thisNode.Position + (vertices[i % vertices.Length] * pressureFactor);
                        if (point == quad.B)
                        {
                            abPoints.Add(quad.B);
#if DEBUG_RENDERING_FEEDBACK
                            if (showFeedback)
                            {
                                debugDC.DrawEllipse(Brushes.Green, null, point, feedbackSize, feedbackSize);
                            }
#endif
                            break;
                        }
                    }

                    if (i == maxCount)
                    {
                        Debug.Assert(false, "StrokeNodeOperations.GetPointsAtEndOfSegment failed to find the B position");
                        //we didn't find the d point, return
                        return;
                    }

                    //now look for the C position
                    //advance i
                    i++;
                    for (int j = 0; i < maxCount && j < vertices.Length; i++, j++)
                    {
                        //look for the c point last
                        Point point = _thisNode.Position + (vertices[i % vertices.Length] * pressureFactor);
                        if (point == quad.C)
                        {
                            break;
                        }
                        //only add to ab if we didn't find C
                        abPoints.Add(point);

#if DEBUG_RENDERING_FEEDBACK
                        if (showFeedback)
                        {
                            debugDC.DrawEllipse(Brushes.Wheat, null, quad.C, feedbackSize, feedbackSize);
                        }
#endif
                    }
                    //finally, add the D point
                    dcPoints.Add(quad.C);

#if DEBUG_RENDERING_FEEDBACK
                    if (showFeedback)
                    {
                        debugDC.DrawEllipse(Brushes.Yellow, null, quad.C, feedbackSize, feedbackSize);
                    }
#endif
                }
            }
        }
        ///// <summary>
        ///// IsPointWithinRectOrEllipse
        ///// </summary>
        //internal bool IsPointWithinRectOrEllipse(Point point, double xRadiusOrHalfWidth, double yRadiusOrHalfHeight, Point center, bool isEllipse)
        //{
        //    if (isEllipse)
        //    {
        //        //determine what delta is required to move the rect to be
        //        //centered at 0,0
        //        double xDelta = center.X + xRadiusOrHalfWidth;
        //        double yDelta = center.Y + yRadiusOrHalfHeight;

        //        //offset the point by that delta
        //        point.X -= xDelta;
        //        point.Y -= yDelta;

        //        //formula for ellipse is x^2/a^2 + y^2/b^2 = 1
        //        double a = xRadiusOrHalfWidth;
        //        double b = yRadiusOrHalfHeight;
        //        double res = (((point.X * point.X) / (a * a)) +
        //                     ((point.Y * point.Y) / (b * b)));

        //        if (res <= 1)
        //        {
        //            return true;
        //        }
        //        return false;
        //    }
        //    else
        //    {
        //        if (point.X >= (center.X - xRadiusOrHalfWidth) &&
        //            point.X <= (center.X + xRadiusOrHalfWidth) &&
        //            point.Y >= (center.Y - yRadiusOrHalfHeight) &&
        //            point.Y <= (center.Y + yRadiusOrHalfHeight))
        //        {
        //            return true;
        //        }
        //        return false;
        //    }
        //}

        /// <summary>
        /// GetPointsAtStartOfSegment
        /// </summary>
        internal void GetPointsAtStartOfSegment(List <Point> abPoints,
                                                List <Point> dcPoints
#if DEBUG_RENDERING_FEEDBACK
                                                , DrawingContext debugDC, double feedbackSize, bool showFeedback
#endif
                                                )
        {
            if (IsValid)
            {
                Quad quad = ConnectingQuad;
                if (IsEllipse)
                {
                    Rect startNodeBounds = _operations.GetNodeBounds(_lastNode);

                    //add instructions to arc from D to A
                    abPoints.Add(quad.D);
                    abPoints.Add(StrokeRenderer.ArcToMarker);
                    abPoints.Add(new Point(startNodeBounds.Width, startNodeBounds.Height));
                    abPoints.Add(quad.A);

                    //simply start at D
                    dcPoints.Add(quad.D);

#if DEBUG_RENDERING_FEEDBACK
                    if (showFeedback)
                    {
                        debugDC.DrawEllipse(null, new Pen(Brushes.Pink, feedbackSize / 2), _lastNode.Position, startNodeBounds.Width / 2, startNodeBounds.Height / 2);
                        debugDC.DrawEllipse(Brushes.Red, null, quad.A, feedbackSize, feedbackSize);
                        debugDC.DrawEllipse(Brushes.Blue, null, quad.D, feedbackSize, feedbackSize);
                    }
#endif
                }
                else
                {
                    //we're interested in the A, D points as well as the
                    //nodecountour points between them
                    Rect endNodeRect = _operations.GetNodeBounds(_thisNode);

#if DEBUG_RENDERING_FEEDBACK
                    if (showFeedback)
                    {
                        debugDC.DrawRectangle(null, new Pen(Brushes.Pink, feedbackSize / 2), _operations.GetNodeBounds(_lastNode));
                    }
#endif
                    Vector[] vertices       = _operations.GetVertices();
                    double   pressureFactor = _lastNode.PressureFactor;
                    int      maxCount       = vertices.Length * 2;
                    int      i            = 0;
                    bool     dIsInEndNode = true;
                    for (; i < maxCount; i++)
                    {
                        //look for the d point first
                        Point point = _lastNode.Position + (vertices[i % vertices.Length] * pressureFactor);
                        if (point == quad.D)
                        {
                            //ab always starts with the D position (only add if it's not in endNode's bounds)
                            if (!endNodeRect.Contains(quad.D))
                            {
                                dIsInEndNode = false;
                                abPoints.Add(quad.D);
                                dcPoints.Add(quad.D);
                            }
#if DEBUG_RENDERING_FEEDBACK
                            if (showFeedback)
                            {
                                debugDC.DrawEllipse(Brushes.Blue, null, quad.D, feedbackSize, feedbackSize);
                            }
#endif
                            break;
                        }
                    }

                    if (i == maxCount)
                    {
                        Debug.Assert(false, "StrokeNodeOperations.GetPointsAtStartOfSegment failed to find the D position");
                        //we didn't find the d point, return
                        return;
                    }


                    //now look for the A position
                    //advance i
                    i++;
                    for (int j = 0; i < maxCount && j < vertices.Length; i++, j++)
                    {
                        //look for the A point now
                        Point point = _lastNode.Position + (vertices[i % vertices.Length] * pressureFactor);
                        //add everything in between to ab as long as it's not already in endNode's bounds
                        if (!endNodeRect.Contains(point))
                        {
                            abPoints.Add(point);
#if DEBUG_RENDERING_FEEDBACK
                            if (showFeedback)
                            {
                                debugDC.DrawEllipse(Brushes.Wheat, null, point, feedbackSize, feedbackSize);
                            }
#endif
                        }
                        if (dIsInEndNode)
                        {
                            Debug.Assert(!endNodeRect.Contains(point));

                            //add the first point after d, clockwise
                            dIsInEndNode = false;
                            dcPoints.Add(point);
                        }
                        if (point == quad.A)
                        {
#if DEBUG_RENDERING_FEEDBACK
                            if (showFeedback)
                            {
                                debugDC.DrawEllipse(Brushes.Red, null, point, feedbackSize, feedbackSize);
                            }
#endif
                            break;
                        }
                    }
                }
            }
        }
Example #14
0
        protected override void OnRender(DrawingContext dc)
        {
            dc.DrawRectangle(Background, null, new Rect(RenderSize));
            this.VisualTextRenderingMode = TextRenderingMode.ClearType;
            this.VisualTextHintingMode   = TextHintingMode.Fixed;

            if (Items == null)
            {
                return;
            }

            Typeface      typefaceNormal      = null;
            Typeface      typefaceTitle       = null;
            GlyphTypeface glyphTypefaceNormal = null;
            GlyphTypeface glyphTypefaceTitle  = null;

            try
            {
                if (Settings.Instance.FontName.Length > 0)
                {
                    typefaceNormal = new Typeface(new FontFamily(Settings.Instance.FontName),
                                                  FontStyles.Normal,
                                                  FontWeights.Normal,
                                                  FontStretches.Normal);
                }
                if (Settings.Instance.FontNameTitle.Length > 0)
                {
                    if (Settings.Instance.FontBoldTitle == true)
                    {
                        typefaceTitle = new Typeface(new FontFamily(Settings.Instance.FontNameTitle),
                                                     FontStyles.Normal,
                                                     FontWeights.Bold,
                                                     FontStretches.Normal);
                    }
                    else
                    {
                        typefaceTitle = new Typeface(new FontFamily(Settings.Instance.FontNameTitle),
                                                     FontStyles.Normal,
                                                     FontWeights.Normal,
                                                     FontStretches.Normal);
                    }
                }
                if (!typefaceNormal.TryGetGlyphTypeface(out glyphTypefaceNormal))
                {
                    typefaceNormal = null;
                }
                if (!typefaceTitle.TryGetGlyphTypeface(out glyphTypefaceTitle))
                {
                    typefaceTitle = null;
                }

                if (typefaceNormal == null)
                {
                    typefaceNormal = new Typeface(new FontFamily("MS UI Gothic"),
                                                  FontStyles.Normal,
                                                  FontWeights.Normal,
                                                  FontStretches.Normal);
                    if (!typefaceNormal.TryGetGlyphTypeface(out glyphTypefaceNormal))
                    {
                        MessageBox.Show("フォント指定が不正です");
                        return;
                    }
                }
                if (typefaceTitle == null)
                {
                    typefaceTitle = new Typeface(new FontFamily("MS UI Gothic"),
                                                 FontStyles.Normal,
                                                 FontWeights.Bold,
                                                 FontStretches.Normal);
                    if (!typefaceTitle.TryGetGlyphTypeface(out glyphTypefaceTitle))
                    {
                        MessageBox.Show("フォント指定が不正です");
                        return;
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + "\r\n" + ex.StackTrace);
            }

            try
            {
                double sizeNormal = Settings.Instance.FontSize;
                double sizeTitle  = Settings.Instance.FontSizeTitle;
                foreach (ReserveViewItem info in Items)
                {
                    dc.DrawRectangle(Brushes.LightGray, null, new Rect(info.LeftPos, info.TopPos, info.Width, info.Height));
                    if (info.Height > 2)
                    {
                        SolidColorBrush color = Brushes.White;
                        if (info.ReserveInfo.OverlapMode == 1)
                        {
                            color = Brushes.Yellow;
                            //color = CommonManager.Instance.CustContentColorList[0x14];
                        }
                        dc.DrawRectangle(color, null, new Rect(info.LeftPos + 1, info.TopPos + 1, info.Width - 2, info.Height - 2));
                        if (info.Height < 4 + sizeTitle + 2)
                        {
                            //高さ足りない
                            info.TitleDrawErr = true;
                            continue;
                        }

                        double totalHeight = 0;

                        //分
                        string min;
                        min = info.ReserveInfo.StartTime.Minute.ToString("d02") + "  ";

                        double useHeight = 0;
                        if (RenderText(min, dc, glyphTypefaceNormal, sizeNormal, info.Width - 4, info.Height - 4, info.LeftPos, info.TopPos, ref useHeight) == false)
                        {
                            info.TitleDrawErr = true;
                            continue;
                        }

                        double widthOffset = sizeNormal * 2;

                        //サービス名
                        if (info.ReserveInfo.StationName.Length > 0)
                        {
                            String serviceName = info.ReserveInfo.StationName;
                            if (0x7880 <= info.ReserveInfo.OriginalNetworkID && info.ReserveInfo.OriginalNetworkID <= 0x7FE8)
                            {
                                serviceName += " (地デジ)";
                            }
                            else if (info.ReserveInfo.OriginalNetworkID == 0x0004)
                            {
                                serviceName += " (BS)";
                            }
                            else if (info.ReserveInfo.OriginalNetworkID == 0x0006)
                            {
                                serviceName += " (CS1)";
                            }
                            else if (info.ReserveInfo.OriginalNetworkID == 0x0007)
                            {
                                serviceName += " (CS2)";
                            }
                            else
                            {
                                serviceName += " (その他)";
                            }
                            if (RenderText(serviceName, dc, glyphTypefaceTitle, sizeTitle, info.Width - 6 - widthOffset, info.Height - 6 - totalHeight, info.LeftPos + widthOffset, info.TopPos + totalHeight, ref useHeight) == false)
                            {
                                info.TitleDrawErr = true;
                                continue;
                            }
                            totalHeight += useHeight + (sizeNormal / 2);
                        }
                        widthOffset = 2;
                        //番組名
                        if (info.ReserveInfo.Title.Length > 0)
                        {
                            if (RenderText(info.ReserveInfo.Title, dc, glyphTypefaceNormal, sizeNormal, info.Width - 6 - widthOffset, info.Height - 6 - totalHeight, info.LeftPos + widthOffset, info.TopPos + totalHeight, ref useHeight) == false)
                            {
                                info.TitleDrawErr = true;
                                continue;
                            }
                            totalHeight += useHeight + sizeNormal;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + "\r\n" + ex.StackTrace);
            }
        }
Example #15
0
        public override void Drawing(DrawingContext drawingContext)
        {
            Point loca = Coordinate.CoordinateTransport(new Point(this.X, this.Y), this.Parent.GlobalCoordinate, Coordinate.BaseCoornidate);

            drawingContext.DrawRectangle(System.Windows.Media.Brushes.Black, new Pen(Brushes.White, 1), new Rect(loca.X - this.Size / 2, loca.Y - this.Size / 2, this.Size, this.Size));
        }
Example #16
0
 protected override void OnRender(DrawingContext drawingContext)
 {
     drawingContext.DrawRectangle(null, _pen, this._bounds);
 }
Example #17
0
 /// <summary>
 /// 十字线末端显示数据
 /// </summary>
 /// <param name="drawingContext"></param>
 /// <param name="labelcontent"></param>
 /// <param name="location"></param>
 private void DrawingText(DrawingContext drawingContext, string labelcontent, Point location, Size rectsize)
 {
     drawingContext.DrawRectangle(Brushes.Blue, BlackPen, new Rect(location, rectsize));
     drawingContext.DrawText(new FormattedText(labelcontent, CultureInfo.CurrentCulture,
                                               FlowDirection.LeftToRight, new Typeface("Tahoma"), 14, Brushes.White), location);
 }
 protected override void OnRender(DrawingContext drawingContext)
 {
     drawingContext.DrawRectangle(
         this.Brush,
         this.Pen,
         new Rect(10, 10, 180, 180.5));
 }
Example #19
0
        protected override void OnRender(DrawingContext drawingContext)
        {
            Rect fullRect = new Rect(new Point(), new Size(ActualWidth, ActualHeight));

            drawingContext.PushClip(new RectangleGeometry(fullRect));

            drawingContext.DrawRectangle(Background, null, fullRect);

            Pen linePen = new Pen(Brushes.White, 3);

            //drawingContext.DrawLine(linePen, new Point(0, ActualHeight / 2), new Point(ActualWidth, ActualHeight / 2));

            drawingContext.DrawLine(new Pen(Brushes.Red, 11), new Point(Midpoint * ActualWidth, 0), new Point(Midpoint * ActualWidth, ActualHeight));

            if (Timeline != null)
            {
                double timeFrom = _progress - Midpoint * TotalDisplayedDuration;
                double timeTo   = _progress + (1 - Midpoint) * TotalDisplayedDuration;

                double position = Math.Floor(timeFrom);

                List <double> beatPositions = new List <double>();

                while (position < timeTo)
                {
                    BeatGroup group = Timeline.FindActiveGroup(position);
                    if (group == null)
                    {
                        group = Timeline.FindNextGroup(position);
                        if (group != null)
                        {
                            position = group.Start;
                        }
                    }

                    if (group == null)
                    {
                        break;
                    }

                    position = group.FindStartingPoint(position);

                    while (position < group.End && position < timeTo)
                    {
                        foreach (double beat in group.Pattern.BeatPositions)
                        {
                            double relativePosition = (((beat * group.ActualPatternDuration) + position - timeFrom) / (timeTo - timeFrom));
                            beatPositions.Add(relativePosition);
                        }

                        position += group.ActualPatternDuration;
                    }
                }

                const double safeSpace = 30;
                double       y         = ActualHeight / 2.0;

                if (_simpleRendering)
                {
                    DrawLine(drawingContext, Colors.Red, new Point(-safeSpace, y),
                             new Point(ActualWidth + safeSpace, y));

                    foreach (double pos in beatPositions)
                    {
                        DrawLine(drawingContext, Colors.Lime, new Point(pos * ActualWidth, -5), new Point(pos * ActualWidth, ActualHeight + 5));
                    }
                }
                else
                {
                    PathGeometry geometry = new PathGeometry();



                    if (beatPositions.Count > 0)
                    {
                        double start = Math.Min(0, beatPositions.First());
                        double end   = Math.Max(1, beatPositions.Last());


                        PathFigure figure = new PathFigure {
                            StartPoint = new Point(start * ActualWidth - safeSpace, y)
                        };
                        geometry.Figures.Add(figure);

                        foreach (double beatPosition in beatPositions)
                        {
                            AppendSwiggely(figure, new Point(beatPosition * ActualWidth, y));
                        }

                        figure.Segments.Add(new LineSegment(new Point(end * ActualWidth + safeSpace, y), true));
                    }
                    else
                    {
                        geometry.Figures.Add(new PathFigure(new Point(-safeSpace, y), new[] { new LineSegment(new Point(ActualWidth + safeSpace, y), true) }, false));
                    }

                    drawingContext.DrawGeometry(null, new Pen(new SolidColorBrush(Colors.Red)
                    {
                        Opacity = 0.5
                    }, 4)
                    {
                        LineJoin = PenLineJoin.Round
                    }, geometry);
                    drawingContext.DrawGeometry(null, new Pen(new SolidColorBrush(Colors.White)
                    {
                        Opacity = 1.0
                    }, 2)
                    {
                        LineJoin = PenLineJoin.Round
                    }, geometry);
                }
            }

            drawingContext.Pop();
        }
Example #20
0
        private void bodyFrameReader_FrameArrived(object sender, BodyFrameArrivedEventArgs e)
        {
            bool dataReceived = false;

            using (BodyFrame bodyFrame = e.FrameReference.AcquireFrame())
            {
                if (bodyFrame != null)
                {
                    if (this.bodies == null)
                    {
                        this.bodies = new Body[bodyFrame.BodyCount];
                    }

                    bodyFrame.GetAndRefreshBodyData(this.bodies);
                    dataReceived = true;
                }
            }

            if (dataReceived)
            {
                using (DrawingContext dc = this.bodyDrawingGroup.Open())
                {
                    // Draw a transparent background to set the render size
                    dc.DrawRectangle(Brushes.Black, null, new Rect(0.0, 0.0, this.colorFrameDescription.Width, this.colorFrameDescription.Height));
                    // prevent drawing outside of our render area
                    bodyDrawingGroup.ClipGeometry = new RectangleGeometry(new Rect(0.0, 0.0, this.colorFrameDescription.Width, this.colorFrameDescription.Height));
                    dc.DrawImage(colorBitmap, new Rect(0.0, 0.0, this.colorFrameDescription.Width, this.colorFrameDescription.Height));

                    //Draw recordState
                    bool record = btn_record.Content.Equals("Stop");
                    if (record)
                    {
                        dc.DrawRectangle(Brushes.Firebrick, null, new Rect(new Point(80, 80), new Size(80, 80)));
                        dc.DrawText(new FormattedText("Rec", CultureInfo.CurrentUICulture, FlowDirection.LeftToRight, new Typeface("Arial"), 35, Brushes.Black), new Point(90, 95));
                    }

                    foreach (Body body in this.bodies)
                    {
                        if (body.IsTracked)
                        {
                            leftHandPostition  = body.Joints[JointType.HandLeft].Position;
                            rightHandPostition = body.Joints[JointType.HandRight].Position;

                            bool angleMode = radio_angle.IsChecked ?? false;
                            drawUI(body.Joints, dc, angleMode);

                            frameSelector++;
                            if (frameSelector == 2)
                            {
                                // 1) Calculate All Data (angles or distances)
                                var allData = calculateData(body.Joints, angleMode, body.JointOrientations);
                                // 2) Write and draw to UI
                                writeData2Gui(allData, angleMode);
                                // 3) Export Data if activated
                                if (record && sequenceID <= maxTrainData + maxTestData)
                                {
                                    //show recorded frames
                                    lbl_fpsBody.Content = Convert.ToUInt64(lbl_fpsBody.Content) + 1;
                                    writeTrainingData(allData);
                                }

                                frameSelector = 0;
                            }
                        }
                    }
                }
            }
        }
        // A common way to implement an adorner's rendering behavior is to override the OnRender
        // method, which is called by the layout system as part of a rendering pass.
        /// <summary>
        /// Paints the highlight.
        /// </summary>
        protected override void OnRender(DrawingContext drawingContext)
        {
            //// Some arbitrary drawing implements.


            /* this is a nice shortcut but it means we can't set yPos, which is used by scroll highlighter
             * int firstline = tb.GetFirstVisibleLineIndex();
             * if (firstline == -1) { OnRenderImpossible(); return; }
             * int lastline = tb.GetLastVisibleLineIndex();
             * if (lastline == -1) { OnRenderImpossible(); return; }
             * try
             * {
             *  int charline = tb.GetLineIndexFromCharacterIndex(start);
             *  if (charline == -1) { OnRenderImpossible(); return; }
             *  if (charline < firstline - 1 || charline > lastline + 1) return;
             * }
             * catch (ArgumentOutOfRangeException) { OnRenderImpossible(); return; }
             */
            //drawingContext.PushClip(new RectangleGeometry(new Rect(0, 0, this.AdornedElement.RenderSize.Width, this.AdornedElement.RenderSize.Height)));

            var leftRectangle  = tb.GetRectFromCharacterIndex(start);
            var rightRectangle = tb.GetRectFromCharacterIndex(start + length);

            if (Double.IsInfinity(leftRectangle.X))
            {
                OnRenderImpossible();
            }

            yPos = leftRectangle.Top;

            AdjustRectanglesToView(ref leftRectangle, ref rightRectangle, this.AdornedElement.RenderSize.Height - horizontalScrollBarHeight);
            //       AdjustRectanglesToView(ref leftRectangle, ref rightRectangle, AdornedElement.RenderSize.Height - SystemParameters.ScrollHeight);

            if (leftRectangle.Top > 1 && rightRectangle.Y > 1 && leftRectangle.Top < (AdornedElement.RenderSize.Height - horizontalScrollBarHeight) &&
                leftRectangle.Left > 1 && rightRectangle.Right > 1 && leftRectangle.Left < (AdornedElement.RenderSize.Width - horizontalScrollBarHeight) //assume vertical scrollbar is as wide as horiz scroll is high


                )
            {
                if (rightRectangle.Left > AdornedElement.RenderSize.Width - horizontalScrollBarHeight - 1)//if it ends to the right
                {
                    rightRectangle.X = AdornedElement.RenderSize.Width - horizontalScrollBarHeight - 1;
                }

                isInViewport = true;
                if (RoughlyTheSame(leftRectangle.Top, rightRectangle.Top))
                {
                    //notsplit over more than 1 line
                    var rect = new Rect(leftRectangle.TopLeft, rightRectangle.BottomRight);

                    rect.Inflate(1, 1);
                    drawingContext.DrawRectangle(renderBrush, null, rect);
                }
                else
                {
                    if (leftRectangle != Rect.Empty && rightRectangle != Rect.Empty)
                    {
                        //paint as 3 rects
                        //r1 is top line from word to end of line
                        //r2 is start of line to end of line, between first line and last line
                        //r3 is last line from start of line to end of word

                        //we need to figure out the X coords of the start of the line and end of the line
                        Rect[] points = FindStartEndOfVisualLineRects(start, leftRectangle);
                        HighlightAdorner.DrawMultiLine(drawingContext, renderBrush, renderPen, ref leftRectangle, ref rightRectangle, points);
                    }
                }
            }
            else
            {
                isInViewport = false;
            }
            //drawingContext.Pop();
        }
Example #22
0
        private async void PhotoOnload()
        {
            string filePath = @"C:\Users\Public\Pictures\tmp_face.png";
            // сохранить фото по пути filePath
            PngBitmapEncoder encoder = new PngBitmapEncoder();

            encoder.Frames.Add(BitmapFrame.Create((BitmapSource)ImageWebcamFrame.Source));
            using (FileStream fileStream = new FileStream(filePath, FileMode.Create))
            {
                encoder.Save(fileStream);
            }

            Uri         fileUri      = new Uri(filePath);
            BitmapImage bitmapSource = new BitmapImage();

            bitmapSource.BeginInit();
            bitmapSource.CacheOption = BitmapCacheOption.None;
            bitmapSource.UriSource   = fileUri;
            bitmapSource.EndInit();

            ImageWebcamFrame.Source = bitmapSource;

            // передать путь в функцию
            faceList = await UploadAndDetectFaces(filePath);

            if (faceList.Count > 0)
            {
                // Prepare to draw rectangles around the faces.
                DrawingVisual  visual         = new DrawingVisual();
                DrawingContext drawingContext = visual.RenderOpen();
                drawingContext.DrawImage(bitmapSource,
                                         new Rect(0, 0, bitmapSource.Width, bitmapSource.Height));
                double dpi = bitmapSource.DpiX;
                // Some images don't contain dpi info.
                resizeFactor     = (dpi == 0) ? 1 : 96 / dpi;
                faceDescriptions = new String[faceList.Count];

                for (int i = 0; i < faceList.Count; ++i)
                {
                    DetectedFace face = faceList[i];

                    // Draw a rectangle on the face.
                    drawingContext.DrawRectangle(
                        Brushes.Transparent,
                        new Pen(Brushes.Red, 2),
                        new Rect(
                            face.FaceRectangle.Left * resizeFactor,
                            face.FaceRectangle.Top * resizeFactor,
                            face.FaceRectangle.Width * resizeFactor,
                            face.FaceRectangle.Height * resizeFactor
                            )
                        );
                }

                drawingContext.Close();

                // Display the image with the rectangle around the face.
                RenderTargetBitmap faceWithRectBitmap = new RenderTargetBitmap(
                    (int)(bitmapSource.PixelWidth * resizeFactor),
                    (int)(bitmapSource.PixelHeight * resizeFactor),
                    96,
                    96,
                    PixelFormats.Pbgra32);

                faceWithRectBitmap.Render(visual);
                ImageWebcamFrame.Source = faceWithRectBitmap;
            }
        }
    public override void Render(DrawingContext context)
    {
        if (Rows == null)
        {
            return;
        }

        var font = new Typeface(TextBlock.GetFontFamily(this));

        var actualWidth = Bounds.Width;

        var scrollViewer = this.FindAncestorOfType <ScrollViewer>();

        // determine the first and last visible row
        var startIndex = Math.Max(0, (int)(scrollViewer.Offset.Y / RowHeight) - 1);
        var endIndex   = Math.Min(startIndex + scrollViewer.Viewport.Height / RowHeight + 2, Rows.Count);

        double y   = startIndex * RowHeight + DrawingStartOffsetY;
        bool   odd = startIndex % 2 == 0;

        Span <double> columnWidths = stackalloc double[Columns?.Count ?? 0];

        if (Columns != null)
        {
            for (int i = 0; i < Columns.Count; i++)
            {
                columnWidths[i] = Columns[i].Width;
            }
        }

        var cellDrawer = CustomCellDrawer;

        // we draw only the visible rows
        var selectionIterator = MultiSelection.ContainsIterator;

        for (var index = startIndex; index < endIndex; index++)
        {
            var    row     = Rows[index];
            double x       = 0;
            var    rowRect = new Rect(0, y, actualWidth, RowHeight);

            // background
            bool isSelected = selectionIterator.Contains(index);
            context.FillRectangle(isSelected ? (SelectedRowBackground) : (odd ? OddRowBackground : EvenRowBackground), rowRect);

            cellDrawer?.DrawRow(context, row, rowRect);

            var textColor = isSelected ? FocusTextBrush : TextBrush;

            int cellIndex = 0;
            foreach (var cell in row.CellsList)
            {
                if (cellIndex >= columnWidths.Length)
                {
                    return;
                }

                if (!IsColumnVisible(cellIndex))
                {
                    cellIndex++;
                    continue;
                }

                var columnWidth = columnWidths[cellIndex];

                // we draw only the visible columns
                // todo: could be optimized so we don't iterate through all columns when we know we don't need to
                if (x + columnWidth > scrollViewer.Offset.X && x < scrollViewer.Offset.X + scrollViewer.Viewport.Width)
                {
                    var rect      = new Rect(x, y, Math.Max(0, columnWidth - ColumnSpacing), RowHeight);
                    var rectWidth = rect.Width;
                    var state     = context.PushClip(rect);
                    if (cellDrawer == null || !cellDrawer.Draw(context, ref rect, cell))
                    {
                        var text = cell.ToString();
                        if (!string.IsNullOrEmpty(text))
                        {
                            var ft = new FormattedText
                            {
                                Text       = text,
                                Constraint = new Size(rect.Width, RowHeight),
                                Typeface   = font,
                                FontSize   = 12
                            };
                            if (Math.Abs(rectWidth - rect.Width) > 0.01)
                            {
                                state.Dispose();
                                state = context.PushClip(rect);
                            }
                            context.DrawText(textColor, new Point(rect.X + ColumnSpacing, y + RowHeight / 2 - ft.Bounds.Height / 2), ft);
                        }
                    }

                    state.Dispose();
                }

                x += columnWidth;
                cellIndex++;
            }

            y  += RowHeight;
            odd = !odd;
        }

        if (IsKeyboardFocusWithin && IsSelectedCellValid && !editor.IsOpened)
        {
            context.DrawRectangle(FocusOuterPen, SelectedCellRect, 4);
            context.DrawRectangle(FocusPen, SelectedCellRect, 4);
        }

        RenderHeaders(context);
    }
Example #24
0
        public void RenderRectangle(Rect rectangle, Brush foreground)
        {
            var scaledRectangle = GeometryHelper.ScaleRectangle(_scale, rectangle);

            _drawingContext.DrawRectangle(foreground, null, scaledRectangle);
        }
Example #25
0
        //------------------------------------------------------
        //
        //  Protected Methods
        //
        //------------------------------------------------------

        #region Protected Methods

        /// <summary>
        /// Render override to render the composition adorner here.
        /// </summary>
        protected override void OnRender(DrawingContext drawingContext)
        {
            // Get the matrix from AdornedElement to the visual parent to get the transformed
            // start/end point
            Visual parent2d = VisualTreeHelper.GetParent(this.AdornedElement) as Visual;

            if (parent2d == null)
            {
                return;
            }

            GeneralTransform transform = AdornedElement.TransformToAncestor(parent2d);

            if (transform == null)
            {
                return;
            }

            // Please note that we do the highlight adornment for the CONVERTED text only
            // for Simplified Chinese IMEs. Doing this uniformly across all IMEs wasnt possible
            // because it was noted that some of them (viz. Japanese) werent being consistent
            // about this attribute.

            bool isChinesePinyin = chinesePinyin.Equals(InputLanguageManager.Current.CurrentInputLanguage.IetfLanguageTag);

            // Render the each of the composition string attribute from the attribute ranges.
            for (int i = 0; i < _attributeRanges.Count; i++)
            {
                DoubleCollection dashArray;

                // Get the composition attribute range from the attribute range lists
                AttributeRange attributeRange = (AttributeRange)_attributeRanges[i];

                // Skip the rendering composition lines if the composition line doesn't exist.
                if (attributeRange.CompositionLines.Count == 0)
                {
                    continue;
                }

                // Set the line bold and squiggle
                bool lineBold            = attributeRange.TextServicesDisplayAttribute.IsBoldLine ? true : false;
                bool squiggle            = false;
                bool hasVirtualSelection = (attributeRange.TextServicesDisplayAttribute.AttrInfo & UnsafeNativeMethods.TF_DA_ATTR_INFO.TF_ATTR_TARGET_CONVERTED) != 0;

                Brush  selectionBrush   = null;
                double selectionOpacity = -1;
                Pen    selectionPen     = null;

                if (isChinesePinyin && hasVirtualSelection)
                {
                    DependencyObject owner = _textView.TextContainer.Parent;
                    selectionBrush   = (Brush)owner.GetValue(TextBoxBase.SelectionBrushProperty);
                    selectionOpacity = (double)owner.GetValue(TextBoxBase.SelectionOpacityProperty);
                }

                // Set the line height and cluse gap value that base on the ratio of text height
                double height     = attributeRange.Height;
                double lineHeight = height * (lineBold ? BoldLineHeightRatio : NormalLineHeightRatio);
                double clauseGap  = height * ClauseGapRatio;

                // Create Pen for drawing the composition lines with the specified line color
                Pen pen = new Pen(new SolidColorBrush(Colors.Black), lineHeight);

                // Set the pen style that based on IME's composition line style
                switch (attributeRange.TextServicesDisplayAttribute.LineStyle)
                {
                case UnsafeNativeMethods.TF_DA_LINESTYLE.TF_LS_DOT:
                    // Add the dot length and specify the start/end line cap as the round
                    dashArray = new DoubleCollection();
                    dashArray.Add(DotLength);
                    dashArray.Add(DotLength);

                    pen.DashStyle    = new DashStyle(dashArray, 0);
                    pen.DashCap      = System.Windows.Media.PenLineCap.Round;
                    pen.StartLineCap = System.Windows.Media.PenLineCap.Round;
                    pen.EndLineCap   = System.Windows.Media.PenLineCap.Round;

                    // Update the line height for the dot line. Dot line will be more thickness than
                    // other line to show it clearly.
                    lineHeight = height * (lineBold ? BoldDotLineHeightRatio : NormalDotLineHeightRatio);

                    break;

                case UnsafeNativeMethods.TF_DA_LINESTYLE.TF_LS_DASH:
                    double dashLength    = height * (lineBold ? BoldDashRatio : NormalDashRatio);
                    double dashGapLength = height * (lineBold ? BoldDashGapRatio : NormalDashGapRatio);

                    // Add the dash and dash gap legth
                    dashArray = new DoubleCollection();
                    dashArray.Add(dashLength);
                    dashArray.Add(dashGapLength);

                    pen.DashStyle    = new DashStyle(dashArray, 0);
                    pen.DashCap      = System.Windows.Media.PenLineCap.Round;
                    pen.StartLineCap = System.Windows.Media.PenLineCap.Round;
                    pen.EndLineCap   = System.Windows.Media.PenLineCap.Round;

                    break;

                case UnsafeNativeMethods.TF_DA_LINESTYLE.TF_LS_SOLID:
                    pen.StartLineCap = System.Windows.Media.PenLineCap.Round;
                    pen.EndLineCap   = System.Windows.Media.PenLineCap.Round;

                    break;

                case UnsafeNativeMethods.TF_DA_LINESTYLE.TF_LS_SQUIGGLE:
                    squiggle = true;
                    break;
                }

                double halfLineHeight = lineHeight / 2;

                // Draw the each of the composition line
                for (int j = 0; j < attributeRange.CompositionLines.Count; j++)
                {
                    CompositionLine compositionLine = (CompositionLine)attributeRange.CompositionLines[j];

                    // Get the start/end point for composition adorner.
                    // Currently Text doesn't aware of the spaceroom for the drawing of the composition
                    // adorner(like as normal/bold dot/line/squggle), so we should draw the composition adorners
                    // to the closest area of the bottom text.
                    Point startPoint = new Point(compositionLine.StartPoint.X + clauseGap, compositionLine.StartPoint.Y - halfLineHeight);
                    Point endPoint   = new Point(compositionLine.EndPoint.X - clauseGap, compositionLine.EndPoint.Y - halfLineHeight);

                    // Apply composition line color which is actually the foreground of text as well
                    pen.Brush = new SolidColorBrush(compositionLine.LineColor);

                    // Apply matrix to start/end point
                    // REVIEW: if the points can't be transformed, should we not draw anything?
                    transform.TryTransform(startPoint, out startPoint);
                    transform.TryTransform(endPoint, out endPoint);

                    if (isChinesePinyin && hasVirtualSelection)
                    {
                        Rect rect = Rect.Union(compositionLine.StartRect, compositionLine.EndRect);
                        rect = transform.TransformBounds(rect);

                        drawingContext.PushOpacity(selectionOpacity);

                        drawingContext.DrawRectangle(selectionBrush, selectionPen, rect);

                        drawingContext.Pop();
                    }

                    if (squiggle)
                    {
                        // Draw the squiggle line with using of the PathFigure and DrawGemetry.
                        // We may revisit this logic to render the smooth squiggle line.
                        Point pathPoint = new Point(startPoint.X, startPoint.Y - halfLineHeight);

                        double squiggleGap = halfLineHeight;

                        PathFigure pathFigure = new PathFigure();
                        pathFigure.StartPoint = pathPoint;

                        int indexPoint = 0;

                        while (indexPoint < ((endPoint.X - startPoint.X) / (squiggleGap)))
                        {
                            if (indexPoint % 4 == 0 || indexPoint % 4 == 3)
                            {
                                pathPoint = new Point(pathPoint.X + squiggleGap, pathPoint.Y + halfLineHeight);
                                pathFigure.Segments.Add(new LineSegment(pathPoint, true));
                            }
                            else if (indexPoint % 4 == 1 || indexPoint % 4 == 2)
                            {
                                pathPoint = new Point(pathPoint.X + squiggleGap, pathPoint.Y - halfLineHeight);
                                pathFigure.Segments.Add(new LineSegment(pathPoint, true));
                            }

                            indexPoint++;
                        }

                        PathGeometry pathGeometry = new PathGeometry();
                        pathGeometry.Figures.Add(pathFigure);

                        // Draw the composition line with the squiggle
                        drawingContext.DrawGeometry(null, pen, pathGeometry);
                    }
                    else
                    {
                        drawingContext.DrawLine(pen, startPoint, endPoint);
                    }
                }
            }
        }
Example #26
0
        /// <summary>
        /// Handles the body frame data arriving from the sensor
        /// </summary>
        /// <param name="sender">object sending the event</param>
        /// <param name="e">event arguments</param>
        private void Reader_FrameArrived(object sender, BodyFrameArrivedEventArgs e)
        {
            bool dataReceived = false;

            using (BodyFrame bodyFrame = e.FrameReference.AcquireFrame())
            {
                if (bodyFrame != null)
                {
                    if (this.bodies == null)
                    {
                        this.bodies = new Body[bodyFrame.BodyCount];
                    }

                    // The first time GetAndRefreshBodyData is called, Kinect will allocate each Body in the array.
                    // As long as those body objects are not disposed and not set to null in the array,
                    // those body objects will be re-used.
                    bodyFrame.GetAndRefreshBodyData(this.bodies);
                    dataReceived = true;
                }
            }

            if (dataReceived)
            {
                using (DrawingContext dc = this.drawingGroup.Open())
                {
                    // Draw a transparent background to set the render size
                    dc.DrawRectangle(Brushes.Black, null, new Rect(0.0, 0.0, this.displayWidth, this.displayHeight));

                    int penIndex = 0;
                    foreach (Body body in this.bodies)
                    {
                        Pen drawPen = this.bodyColors[penIndex++];

                        if (body.IsTracked)
                        {
                            this.DrawClippedEdges(body, dc);

                            IReadOnlyDictionary <JointType, Joint> joints = body.Joints;

                            // convert the joint points to depth (display) space
                            Dictionary <JointType, Point> jointPoints = new Dictionary <JointType, Point>();

                            foreach (JointType jointType in joints.Keys)
                            {
                                // sometimes the depth(Z) of an inferred joint may show as negative
                                // clamp down to 0.1f to prevent coordinatemapper from returning (-Infinity, -Infinity)
                                CameraSpacePoint position = joints[jointType].Position;
                                if (position.Z < 0)
                                {
                                    position.Z = InferredZPositionClamp;
                                }

                                DepthSpacePoint depthSpacePoint = this.coordinateMapper.MapCameraPointToDepthSpace(position);
                                jointPoints[jointType] = new Point(depthSpacePoint.X, depthSpacePoint.Y);
                            }

                            this.DrawBody(joints, jointPoints, dc, drawPen);

                            this.DrawHand(body.HandLeftState, jointPoints[JointType.HandLeft], dc);
                            this.DrawHand(body.HandRightState, jointPoints[JointType.HandRight], dc);

                            // Write wrist position and hand orientation
                            if (!this.WriteJoint(body))
                            {
                                Environment.Exit(0);
                            }
                        }
                    }

                    // prevent drawing outside of our render area
                    this.drawingGroup.ClipGeometry = new RectangleGeometry(new Rect(0.0, 0.0, this.displayWidth, this.displayHeight));
                }
            }
        }
Example #27
0
        /// <summary>
        /// Event handler for Kinect sensor's SkeletonFrameReady event
        /// </summary>
        /// <param name="sender">object sending the event</param>
        /// <param name="e">event arguments</param>
        private void SensorSkeletonFrameReady(object sender, SkeletonFrameReadyEventArgs e)
        {
            Skeleton[] skeletons = new Skeleton[0];

            using (SkeletonFrame skeletonFrame = e.OpenSkeletonFrame())
            {
                if (skeletonFrame != null)
                {
                    skeletons = new Skeleton[skeletonFrame.SkeletonArrayLength];
                    skeletonFrame.CopySkeletonDataTo(skeletons);
                }
            }

            using (DrawingContext dc = this.drawingGroup.Open())
            {
                // Draw a transparent background to set the render size
                dc.DrawRectangle(Brushes.Black, null, new Rect(0.0, 0.0, RenderWidth, RenderHeight));

                if (skeletons.Count(t => t.TrackingState == SkeletonTrackingState.Tracked) >= 1)
                {
                    Skeleton player1 = skeletons.First(p => p.TrackingState == SkeletonTrackingState.Tracked);
                    Skeleton player2 = skeletons.Last(p => p.TrackingState == SkeletonTrackingState.Tracked);
                    //Console.WriteLine(player1.Position.Z.ToString());
                    paddleLeft.MoveTo((RenderHeight / 2 - paddleLeft.h / 2) + (player1.Position.Z - 2) * 500);
                    paddleRight.MoveTo((RenderHeight / 2 - paddleRight.h / 2) + (player2.Position.Z - 2) * 500); //TODO change to player2
                }

                paddleLeft.Draw(dc);
                paddleRight.Draw(dc);
                ball.Draw(dc);
                ball.Move();
                ball.DetectCollision(paddleLeft, paddleRight);
                if (ball.HitRight())
                {
                    scoreLeft++;
                    this.ScoreLeft.Text = scoreLeft.ToString();
                    ball.Spawn();
                }
                if (ball.HitLeft())
                {
                    scoreRight++;
                    this.ScoreRight.Text = scoreRight.ToString();
                    ball.Spawn();
                }


                if (showSkeletons)
                {
                    foreach (Skeleton skel in skeletons)
                    {
                        //RenderClippedEdges(skel, dc);

                        if (skel.TrackingState == SkeletonTrackingState.Tracked)
                        {
                            this.DrawBonesAndJoints(skel, dc);
                        }
                        else if (skel.TrackingState == SkeletonTrackingState.PositionOnly)
                        {
                            dc.DrawEllipse(
                                this.centerPointBrush,
                                null,
                                this.SkeletonPointToScreen(skel.Position),
                                BodyCenterThickness,
                                BodyCenterThickness);
                        }
                    }
                }

                // prevent drawing outside of our render area
                this.drawingGroup.ClipGeometry = new RectangleGeometry(new Rect(0.0, 0.0, RenderWidth, RenderHeight));
            }
        }
Example #28
0
        /// <summary>
        /// Exports the diagram to an image.
        /// </summary>
        /// <param name="method">image format</param>
        /// <param name="filename">file name</param>
        /// <param name="title">diagram title</param>
        /// <param name="useFrameAndCaption"></param>
        public void ExportToImage(EExportToImageMethod method, string filename, string title, bool useFrameAndCaption)
        {
            const int bounds     = 10;
            const int textoffset = 20;

            #if DEBUG
            Visibility labelVisible = MouseLabel.Visibility;
            MouseLabel.Visibility = Visibility.Collapsed;
            #endif

            if (method == EExportToImageMethod.PNG || method == EExportToImageMethod.PNGClipBoard)
            {
                FormattedText titleText = new FormattedText(title, new CultureInfo("en-us"), FlowDirection.LeftToRight, new Typeface("Verdana"), 20, Brushes.Gray);

                double canvasWidth;
                double canvasHeight;
                GetCanvasWidthAndHeight(out canvasWidth, out canvasHeight);

                RenderTargetBitmap rtb;

                if (useFrameAndCaption)
                {
                    rtb = new RenderTargetBitmap((int)(Math.Max(bounds + canvasWidth + bounds, textoffset + titleText.Width + textoffset)), (int)(textoffset + titleText.Height + textoffset + canvasHeight + bounds), 96, 96, PixelFormats.Pbgra32);
                }
                else
                {
                    rtb = new RenderTargetBitmap((int)(canvasWidth), (int)(canvasHeight), 96, 96, PixelFormats.Pbgra32);
                }

                this.InvalidateVisual();
                DrawingVisual  drawingVisual  = new DrawingVisual();
                DrawingContext drawingContext = drawingVisual.RenderOpen();
                drawingContext.DrawRectangle(this.Background, null, new Rect(0, 0, rtb.Width, rtb.Height));
                VisualBrush canvasBrush = new VisualBrush(this);
                canvasBrush.Stretch    = Stretch.None;
                canvasBrush.AlignmentX = 0;
                canvasBrush.AlignmentY = 0;
                if (useFrameAndCaption)
                {
                    Rect rect = new Rect(bounds, textoffset + titleText.Height + textoffset, rtb.Width - 2 * bounds, rtb.Height - bounds - textoffset - titleText.Height - textoffset);
                    drawingContext.DrawRectangle(canvasBrush, new Pen(Brushes.LightGray, 1), rect);
                    drawingContext.DrawText(titleText, new Point(rtb.Width / 2 - titleText.Width / 2, textoffset));
                }
                else
                {
                    drawingContext.DrawRectangle(canvasBrush, null, new Rect(0, 0, (canvasWidth), (canvasHeight)));
                }
                drawingContext.Close();

                rtb.Render(drawingVisual);
                PngBitmapEncoder png = new PngBitmapEncoder();
                png.Frames.Add(BitmapFrame.Create(rtb));
                if (method == EExportToImageMethod.PNG)
                {
                    using (Stream stm = File.Create(filename))
                    {
                        png.Save(stm);
                    }
                }
                if (method == EExportToImageMethod.PNGClipBoard)
                {
                    Clipboard.SetImage(rtb);
                }
            }
            else if (method == EExportToImageMethod.XPS)
            {
                {
                    double canvasWidth;
                    double canvasHeight;
                    GetCanvasWidthAndHeight(out canvasWidth, out canvasHeight);


                    // Save current canvas transorm
                    Transform transform = this.LayoutTransform;
                    // Temporarily reset the layout transform before saving
                    this.LayoutTransform = null;


                    // Get the size of the canvas
                    Size size = new Size(canvasWidth, canvasHeight);
                    // Measure and arrange elements
                    this.Measure(size);
                    this.Arrange(new Rect(size));

                    // Open new package
                    System.IO.Packaging.Package package = System.IO.Packaging.Package.Open(filename, FileMode.Create);
                    // Create new xps document based on the package opened
                    XpsDocument doc = new XpsDocument(package);
                    // Create an instance of XpsDocumentWriter for the document
                    XpsDocumentWriter writer = XpsDocument.CreateXpsDocumentWriter(doc);
                    // Write the canvas (as Visual) to the document
                    writer.Write(this);
                    // Close document
                    doc.Close();
                    // Close package
                    package.Close();

                    // Restore previously saved layout
                    this.LayoutTransform = transform;
                }
            }

            #if DEBUG
            MouseLabel.Visibility = labelVisible;
            #endif
        }
        /// <summary>
        /// Handles the body frame data arriving from the sensor
        /// </summary>
        /// <param name="sender">object sending the event</param>
        /// <param name="e">event arguments</param>
        private void Reader_FrameArrived(object sender, BodyFrameArrivedEventArgs e)
        {
            bool dataReceived = false;

            using (BodyFrame bodyFrame = e.FrameReference.AcquireFrame())
            {
                if (bodyFrame != null)
                {
                    if (this.bodies == null)
                    {
                        this.bodies = new Body[bodyFrame.BodyCount];
                    }

                    // The first time GetAndRefreshBodyData is called, Kinect will allocate each Body in the array.
                    // As long as those body objects are not disposed and not set to null in the array,
                    // those body objects will be re-used.
                    bodyFrame.GetAndRefreshBodyData(this.bodies);
                    dataReceived = true;
                }
            }

            if (dataReceived)
            {
                using (DrawingContext dc = this.drawingGroup.Open())
                {
                    // Draw a transparent background to set the render size
                    dc.DrawRectangle(Brushes.Black, null, new Rect(0.0, 0.0, this.displayWidth, this.displayHeight));

                    int penIndex = 0;
                    foreach (Body body in this.bodies)
                    {
                        Pen drawPen = this.bodyColors[2];

                        if (body.IsTracked)
                        {
                            Joint l_shoulder = body.Joints[JointType.ShoulderLeft];
                            Joint r_shoulder = body.Joints[JointType.ShoulderRight];
                            Joint elbow      = body.Joints[JointType.ElbowRight];
                            Joint hand       = body.Joints[JointType.WristRight];

                            hand_x = hand.Position.X;
                            hand_y = hand.Position.Y;
                            hand_z = hand.Position.Z;

                            elbow_x = elbow.Position.X;
                            elbow_y = elbow.Position.Y;
                            elbow_z = elbow.Position.Z;

                            r_shoulder_x = r_shoulder.Position.X;
                            r_shoulder_y = r_shoulder.Position.Y;
                            r_shoulder_z = r_shoulder.Position.Z;

                            l_shoulder_x = l_shoulder.Position.X;
                            l_shoulder_y = l_shoulder.Position.Y;
                            l_shoulder_z = l_shoulder.Position.Z;

                            //Vectores
                            v1[0] = (r_shoulder_x - l_shoulder_x);
                            v1[1] = (r_shoulder_y - l_shoulder_y);
                            v1[2] = (r_shoulder_z - l_shoulder_z);

                            v2[0] = (elbow_x - r_shoulder_x);
                            v2[1] = (elbow_y - r_shoulder_y);
                            v2[2] = (elbow_z - r_shoulder_z);

                            v3[0] = (hand_x - elbow_x);
                            v3[1] = (hand_y - elbow_y);
                            v3[2] = (hand_z - elbow_z);

                            Vector vector1 = new Vector(v1[0], v1[1]);
                            Vector vector2 = new Vector(v2[0], v2[1]);
                            Vector vector3 = new Vector(v3[0], v3[1]);
                            //Codo
                            angle_1 = Vector.AngleBetween(vector1, vector2);
                            //Mano
                            angle_2 = Vector.AngleBetween(vector2, vector3);

                            if (angle_1 > 0)
                            {
                                a1_sig = 1;
                            }
                            else
                            {
                                a1_sig = 0;
                            }

                            if (angle_2 > 0)
                            {
                                a2_sig = 1;
                            }
                            else
                            {
                                a2_sig = 0;
                            }


                            if (angle_1 <= -90)
                            {
                                angle_1 = -90;
                            }
                            else if (angle_1 >= -91 && angle_1 < -83)
                            {
                                angle_1 = -90;
                            }
                            else if (angle_1 >= -83 && angle_1 < -76)
                            {
                                angle_1 = -76;
                            }
                            else if (angle_1 >= -75 && angle_1 < -70)
                            {
                                angle_1 = -75;
                            }
                            else if (angle_1 >= -70 && angle_1 < -65)
                            {
                                angle_1 = -70;
                            }
                            else if (angle_1 >= -65 && angle_1 < -60)
                            {
                                angle_1 = -65;
                            }
                            else if (angle_1 >= -60 && angle_1 < -55)
                            {
                                angle_1 = -60;
                            }
                            else if (angle_1 >= -55 && angle_1 < -50)
                            {
                                angle_1 = -55;
                            }
                            else if (angle_1 >= -50 && angle_1 < -45)
                            {
                                angle_1 = -50;
                            }
                            else if (angle_1 >= -45 && angle_1 < -40)
                            {
                                angle_1 = -45;
                            }
                            else if (angle_1 >= -40 && angle_1 < -35)
                            {
                                angle_1 = -40;
                            }
                            else if (angle_1 >= -35 && angle_1 < -30)
                            {
                                angle_1 = -35;
                            }
                            else if (angle_1 >= -30 && angle_1 < -25)
                            {
                                angle_1 = -30;
                            }
                            else if (angle_1 >= -25 && angle_1 < -20)
                            {
                                angle_1 = -25;
                            }
                            else if (angle_1 >= -20 && angle_1 < -15)
                            {
                                angle_1 = -20;
                            }
                            else if (angle_1 >= -15 && angle_1 < -10)
                            {
                                angle_1 = -15;
                            }
                            else if (angle_1 >= -10 && angle_1 < -5)
                            {
                                angle_1 = -10;
                            }
                            else if (angle_1 >= -5 && angle_1 < 0)
                            {
                                angle_1 = -5;
                            }
                            else if (angle_1 >= 0 && angle_1 < 5)
                            {
                                angle_1 = 0;
                            }
                            else if (angle_1 >= 5 && angle_1 < 10)
                            {
                                angle_1 = 5;
                            }
                            else if (angle_1 >= 10 && angle_1 < 15)
                            {
                                angle_1 = 15;
                            }
                            else if (angle_1 >= 15 && angle_1 < 20)
                            {
                                angle_1 = 20;
                            }
                            else if (angle_1 >= 20 && angle_1 < 25)
                            {
                                angle_1 = 25;
                            }
                            else if (angle_1 >= 25 && angle_1 < 30)
                            {
                                angle_1 = 30;
                            }
                            else if (angle_1 >= 30 && angle_1 < 35)
                            {
                                angle_1 = 35;
                            }
                            else if (angle_1 >= 35 && angle_1 < 40)
                            {
                                angle_1 = 40;
                            }
                            else if (angle_1 >= 45 && angle_1 < 50)
                            {
                                angle_1 = 45;
                            }
                            else if (angle_1 >= 50 && angle_1 < 55)
                            {
                                angle_1 = 50;
                            }
                            else if (angle_1 >= 55 && angle_1 < 60)
                            {
                                angle_1 = 55;
                            }
                            else if (angle_1 >= 60 && angle_1 < 65)
                            {
                                angle_1 = 60;
                            }
                            else if (angle_1 >= 65 && angle_1 < 70)
                            {
                                angle_1 = 65;
                            }
                            else if (angle_1 >= 70 && angle_1 < 75)
                            {
                                angle_1 = 70;
                            }
                            else if (angle_1 >= 75 && angle_1 < 80)
                            {
                                angle_1 = 75;
                            }
                            else if (angle_1 >= 80 && angle_1 < 85)
                            {
                                angle_1 = 80;
                            }
                            else if (angle_1 >= 85 && angle_1 < 90)
                            {
                                angle_1 = 85;
                            }
                            else if (angle_1 >= 90)
                            {
                                angle_1 = 90;
                            }

                            //Fuzzy Angle Mano
                            if (angle_2 <= 0)
                            {
                                angle_2 = 0;
                            }
                            else if (angle_2 >= 9 && angle_2 < 18)
                            {
                                angle_2 = 9;
                            }
                            else if (angle_2 >= 18 && angle_2 < 27)
                            {
                                angle_2 = 18;
                            }
                            else if (angle_2 >= 27 && angle_2 < 36)
                            {
                                angle_2 = 27;
                            }
                            else if (angle_2 >= 36 && angle_2 < 45)
                            {
                                angle_2 = 36;
                            }
                            else if (angle_2 >= 45 && angle_2 < 54)
                            {
                                angle_2 = 45;
                            }
                            else if (angle_2 >= 54 && angle_2 < 63)
                            {
                                angle_2 = 54;
                            }
                            else if (angle_2 >= 63 && angle_2 < 72)
                            {
                                angle_2 = 63;
                            }
                            else if (angle_2 >= 72 && angle_2 < 81)
                            {
                                angle_2 = 72;
                            }
                            else if (angle_2 >= 81 && angle_2 < 90)
                            {
                                angle_2 = 81;
                            }
                            else if (angle_2 >= 90 && angle_2 < 99)
                            {
                                angle_2 = 90;
                            }
                            else if (angle_2 >= 99 && angle_2 < 108)
                            {
                                angle_2 = 99;
                            }
                            else if (angle_2 >= 108 && angle_2 < 117)
                            {
                                angle_2 = 108;
                            }
                            else if (angle_2 >= 117 && angle_2 < 126)
                            {
                                angle_2 = 117;
                            }
                            else if (angle_2 >= 126)
                            {
                                angle_2 = 126;
                            }


                            //Codo
                            temp_1 = (Convert.ToInt32(Math.Abs(angle_1))).ToString("D3");
                            //Mano
                            temp_2 = (Convert.ToInt32(Math.Abs(angle_2))).ToString("D3");



                            //12345  6 7 8  9  10 11 12 13 14 15 16 17
                            //#TEXT  0 1 4  A  0  3  6  B  0  C  1  D#


                            this.DrawClippedEdges(body, dc);

                            IReadOnlyDictionary <JointType, Joint> joints = body.Joints;

                            // convert the joint points to depth (display) space
                            Dictionary <JointType, Point> jointPoints = new Dictionary <JointType, Point>();

                            foreach (JointType jointType in joints.Keys)
                            {
                                // sometimes the depth(Z) of an inferred joint may show as negative
                                // clamp down to 0.1f to prevent coordinatemapper from returning (-Infinity, -Infinity)
                                CameraSpacePoint position = joints[jointType].Position;
                                if (position.Z < 0)
                                {
                                    position.Z = InferredZPositionClamp;
                                }

                                DepthSpacePoint depthSpacePoint = this.coordinateMapper.MapCameraPointToDepthSpace(position);
                                jointPoints[jointType] = new Point(depthSpacePoint.X, depthSpacePoint.Y);
                            }

                            this.DrawBody(joints, jointPoints, dc, drawPen);

                            this.DrawHand(body.HandLeftState, jointPoints[JointType.HandLeft], dc);
                            this.DrawHand(body.HandRightState, jointPoints[JointType.HandRight], dc);
                        }
                    }

                    // prevent drawing outside of our render area
                    this.drawingGroup.ClipGeometry = new RectangleGeometry(new Rect(0.0, 0.0, this.displayWidth, this.displayHeight));
                }
            }
        }
Example #30
0
        private void DrawScroll(object picture)
        {
            WriteableBitmap wbmp          = (WriteableBitmap)picture;
            DrawingVisual   drawingVisual = new DrawingVisual();

            using (DrawingContext drawingContext = drawingVisual.RenderOpen())
            {
                //Заливка цветом
                drawingContext.DrawRectangle(Brushes.White, blackPen, new Rect(this._size));
                double oy = (this._y / this._k);
                double ox = this._size.Width / (this._channel.Length - 1) * this._zoom.ZoomX;
                //Видимая ширина в пикселях

                int    xBaseValue = CommonHelper.CalcBaseXValue(COUNTDOWN_MAX_WIDTH, this._size.Width * this._zoom.ZoomX, this._channel.Length);
                double yBaseValue = (BASE_HEIGTH / 2.0 + ADDED_HEIGTH) * this._zoom.ZoomY;

                int startX =
                    (int)Math.Round(((this._channel.Length - 1) / (double)this._zoom.ZoomX * (this._scrollOffset / (double)WorkplaceControl.BASE_CHANGE)));
                int endX =
                    (int)
                    Math.Round((this._channel.Length - 1) / (double)this._zoom.ZoomX * (1 + this._scrollOffset / (double)WorkplaceControl.BASE_CHANGE));

                //Ось Х(Горизонтальные линии)
                for (int j = -2; j <= 2; j++)
                {
                    Point p1 = new Point(startX * ox - this._xOffset, oy * j + yBaseValue);
                    Point p2 = new Point(endX * ox - this._xOffset, oy * j + yBaseValue);
                    drawingContext.DrawLine(j == 0 ? blackPen : grayPen, p1, p2);
                }

                //Ось Y(Вертикальные линии)
                for (int i = (startX / xBaseValue) * xBaseValue; i < endX; i += xBaseValue)
                {
                    Point p1 = new Point(i * ox - this._xOffset, 0);
                    Point p2 = new Point(i * ox - this._xOffset, FULL_HEIGTH * this._zoom.ZoomY);
                    drawingContext.DrawLine(grayPen, p1, p2);
                }
                //График(Кривая)
                double[] values = this._channel.Values(this.CurrentValueType);
                for (int i = startX; i < endX; i += 1)
                {
                    Point p1 = new Point(i * ox - this._xOffset, -(values[i] / this._k) + yBaseValue);
                    Point p2 = new Point((i + 1) * ox - this._xOffset, -(values[i + 1] / this._k) + yBaseValue);
                    drawingContext.DrawLine(this.diagramPen, p1, p2);
                }

                //Подписи оси оХ
                for (int i = 0; i < endX; i += xBaseValue)
                {
                    FormattedText formattedText = new FormattedText(
                        ((i)).ToString(CultureInfo.InvariantCulture),
                        CultureInfo.GetCultureInfo("en-us"),
                        FlowDirection.LeftToRight,
                        new Typeface("Verdana"),
                        12,
                        Brushes.Black);

                    double xPos = 0;
                    if ((i != 0) || (this._scrollOffset != 0))
                    {
                        xPos = i * ox - this._xOffset - formattedText.Width / 2;
                    }

                    drawingContext.DrawText(formattedText,
                                            new Point(xPos, yBaseValue));
                }
            }

            RenderTargetBitmap bmp = new RenderTargetBitmap((int)(this._size.Width), (int)this._size.Height, 0, 0, PixelFormats.Pbgra32);

            bmp.Render(drawingVisual);
            bmp.Freeze();
            uint[] arrBits = new uint[bmp.PixelWidth * bmp.PixelHeight];
            bmp.CopyPixels(arrBits, 4 * bmp.PixelWidth, 0);

            Dispatcher.Invoke(new Action <uint[], WriteableBitmap>(this.DrawComplite), arrBits, wbmp);
        }
Example #31
0
 /// <summary>
 /// When overriden in a class, renders the visual
 /// </summary>
 /// <param name="drawingContext">The <see cref="DrawingContext"/> in whihc to render the visual</param>
 protected override void OnRender(DrawingContext drawingContext)
 {
     if (this.Background != null)
     {
         drawingContext.DrawRectangle(this.RenderTarget, Thickness.Empty, this.Background, null);
     }
     if(this.Child != null)
     {
         this.Child.Render(drawingContext);
     }
 }
Example #32
0
        private void DrawTile(DrawingContext context, TrackTile type, int x, int y, Dictionary <TileType, ImageBrush> mapping)
        {
            bool left;
            bool upper;
            bool lower;
            bool right;
            bool upperLeft;
            bool upperRight;
            bool lowerLeft;
            bool lowerRight;

            if (type == TrackTile.Road)
            {
                left       = game.Track.GetTileByIndex(x - 1, y).HasFlag(TrackTile.Road);
                upper      = game.Track.GetTileByIndex(x, y - 1).HasFlag(TrackTile.Road);
                lower      = game.Track.GetTileByIndex(x, y + 1).HasFlag(TrackTile.Road);
                right      = game.Track.GetTileByIndex(x + 1, y).HasFlag(TrackTile.Road);
                upperLeft  = game.Track.GetTileByIndex(x - 1, y - 1).HasFlag(TrackTile.Road);
                upperRight = game.Track.GetTileByIndex(x + 1, y - 1).HasFlag(TrackTile.Road);
                lowerLeft  = game.Track.GetTileByIndex(x - 1, y + 1).HasFlag(TrackTile.Road);
                lowerRight = game.Track.GetTileByIndex(x + 1, y + 1).HasFlag(TrackTile.Road);
            }
            else
            {
                left       = game.Track.GetTileByIndex(x - 1, y) == type;
                upper      = game.Track.GetTileByIndex(x, y - 1) == type;
                lower      = game.Track.GetTileByIndex(x, y + 1) == type;
                right      = game.Track.GetTileByIndex(x + 1, y) == type;
                upperLeft  = game.Track.GetTileByIndex(x - 1, y - 1) == type;
                upperRight = game.Track.GetTileByIndex(x + 1, y - 1) == type;
                lowerLeft  = game.Track.GetTileByIndex(x - 1, y + 1) == type;
                lowerRight = game.Track.GetTileByIndex(x + 1, y + 1) == type;
            }

            #region Upper Left

            ImageBrush cell00 = mapping[TileType.Center];
            if (!left)
            {
                if (!upper)
                {
                    // konvexe linke ecke
                    cell00 = mapping[TileType.UpperLeftConvex];
                }
                else
                {
                    // linke kante
                    cell00 = mapping[TileType.Left];
                }
            }
            else
            {
                if (!upper)
                {
                    // obere Kante
                    cell00 = mapping[TileType.Upper];
                }
                else if (!upperLeft)
                {
                    // linke konkave Ecke
                    cell00 = mapping[TileType.UpperLeftConcave];
                }
            }

            context.DrawRectangle(cell00, null, new Rect(x * Track.CELLSIZE, y * Track.CELLSIZE, Track.CELLSIZE / 2, Track.CELLSIZE / 2));

            #endregion

            #region Upper Right

            ImageBrush cell10 = mapping[TileType.Center];
            if (!right)
            {
                if (!upper)
                {
                    // konvexe linke ecke
                    cell10 = mapping[TileType.UpperRightConvex];
                }
                else
                {
                    // linke kante
                    cell10 = mapping[TileType.Right];
                }
            }
            else
            {
                if (!upper)
                {
                    // obere Kante
                    cell10 = mapping[TileType.Upper];
                }
                else if (!upperRight)
                {
                    // linke konkave Ecke
                    cell10 = mapping[TileType.UpperRightConcave];
                }
            }

            context.DrawRectangle(cell10, null, new Rect((x * Track.CELLSIZE) + (Track.CELLSIZE / 2), y * Track.CELLSIZE, Track.CELLSIZE / 2, Track.CELLSIZE / 2));

            #endregion

            #region Lower Right

            ImageBrush cell11 = mapping[TileType.Center];
            if (!right)
            {
                if (!lower)
                {
                    // konvexe linke ecke
                    cell11 = mapping[TileType.LowerRightConvex];
                }
                else
                {
                    // linke kante
                    cell11 = mapping[TileType.Right];
                }
            }
            else
            {
                if (!lower)
                {
                    // obere Kante
                    cell11 = mapping[TileType.Lower];
                }
                else if (!lowerRight)
                {
                    // linke konkave Ecke
                    cell11 = mapping[TileType.LowerRightConcave];
                }
            }

            context.DrawRectangle(cell11, null, new Rect((x * Track.CELLSIZE) + (Track.CELLSIZE / 2), (y * Track.CELLSIZE) + (Track.CELLSIZE / 2), Track.CELLSIZE / 2, Track.CELLSIZE / 2));

            #endregion

            #region Lower Left

            ImageBrush cell01 = mapping[TileType.Center];
            if (!left)
            {
                if (!lower)
                {
                    // konvexe linke ecke
                    cell01 = mapping[TileType.LowerLeftConvex];
                }
                else
                {
                    // linke kante
                    cell01 = mapping[TileType.Left];
                }
            }
            else
            {
                if (!lower)
                {
                    // obere Kante
                    cell01 = mapping[TileType.Lower];
                }
                else if (!lowerLeft)
                {
                    // linke konkave Ecke
                    cell01 = mapping[TileType.LowerLeftConcave];
                }
            }

            context.DrawRectangle(cell01, null, new Rect(x * Track.CELLSIZE, (y * Track.CELLSIZE) + (Track.CELLSIZE / 2), Track.CELLSIZE / 2, Track.CELLSIZE / 2));

            #endregion
        }
Example #33
0
 /// <summary>
 /// When overriden in a class, renders the visual
 /// </summary>
 /// <param name="drawingContext">The <see cref="DrawingContext"/> in whihc to render the visual</param>
 protected override void OnRender(DrawingContext drawingContext)
 {
     if(this.Background != null || this.BorderBrush != null)
     {
         drawingContext.DrawRectangle(this.RenderTarget, this.BorderThickness, this.Background, this.BorderBrush);
     }
     if (this.Child != null)
     {
         this.Child.Render(drawingContext);
     }
 }
Example #34
0
        /// <summary>
        /// Event handler for Kinect sensor's SkeletonFrameReady event
        /// </summary>
        /// <param name="sender">object sending the event</param>
        /// <param name="e">event arguments</param>
        private void SensorSkeletonFrameReady(object sender, SkeletonFrameReadyEventArgs e)
        {
            Skeleton[] skeletons = new Skeleton[0];
            using (SkeletonFrame skeletonFrame = e.OpenSkeletonFrame())
            {
                if (skeletonFrame != null)
                {
                    skeletons = new Skeleton[skeletonFrame.SkeletonArrayLength];
                    skeletonFrame.CopySkeletonDataTo(skeletons);
                }
            }

            using (DrawingContext dc = this.drawingGroup.Open())
            {
                // Draw a transparent background to set the render size
                dc.DrawRectangle(Brushes.Transparent, null, new Rect(0.0, 0.0, RenderWidth, RenderHeight));
                if (skeletons.Length != 0)
                {
                    foreach (Skeleton skel in skeletons)
                    {
                        if (skel.TrackingState == SkeletonTrackingState.Tracked)
                        {
                            visible = true;
                            if (comenzado && !terminado)
                            {
                                updateAll(skel);
                                //this.DrawBonesAndJoints(skel, dc);
                                SkeletonPoint[] listOfPoints = { skel.Joints[JointType.WristRight].Position, skel.Joints[JointType.WristLeft].Position };
                                for (int i = 0; i < 3; i++)
                                {
                                    if (exercise.isInMovementN(listOfPoints, i))
                                    {
                                        drawTargets(dc, Brushes.Green, i);
                                        Step = (i + 1) % 3;
                                        score++;
                                    }
                                    else
                                    if (exercise.isInErrorMovement(listOfPoints, i))
                                    {
                                        drawTargets(dc, Brushes.Red, i);
                                        Step = (i + 1) % 3;
                                        score--;
                                    }
                                    else
                                    {
                                        drawTargets(dc, Brushes.Yellow, i);
                                    }
                                }
                            }
                        }
                        else if (skel.TrackingState == SkeletonTrackingState.PositionOnly)
                        {
                            visible = false;
                            dc.DrawEllipse(
                                this.centerPointBrush,
                                null,
                                this.SkeletonPointToScreen(skel.Position),
                                BodyCenterThickness,
                                BodyCenterThickness);
                        }
                    }
                }

                // prevent drawing outside of our render area
                this.drawingGroup.ClipGeometry = new RectangleGeometry(new Rect(-120.0, -200.0, RenderWidth, RenderHeight));
            }
        }
Example #35
0
		/// <summary>
		/// Renders the contents of the image
		/// </summary>
		/// <param name="dc">An instance of <see cref="T:Windows.UI.Xaml.Media.DrawingContext"/> used to render the control.</param>
		protected override void OnRender (DrawingContext dc)
		{
			if (background != null)
				dc.DrawRectangle (background, null, new Rect (0, 0, RenderSize.Width, RenderSize.Height));

			if (Source == null)
				return;

			ImageSource src = Source;
			var ourSize = RenderSize.Width * RenderSize.Height;
			foreach (var frame in _availableFrames)
			{
				src = frame;
				if (frame.PixelWidth * frame.PixelHeight >= ourSize)
					break;
			}
			dc.DrawImage (src, new Rect (new Point (0, 0), RenderSize));
		}
Example #36
0
File: Border.cs Project: ash2005/z
        /// <summary>
        /// In addition to the child, Border renders a background + border.  The background is drawn inside the border.
        /// </summary>
        protected override void OnRender(DrawingContext dc)
        {
            bool useLayoutRounding = this.UseLayoutRounding;

            if (_useComplexRenderCodePath)
            {
                Brush          brush;
                StreamGeometry borderGeometry = BorderGeometryCache;
                if (borderGeometry != null &&
                    (brush = BorderBrush) != null)
                {
                    dc.DrawGeometry(brush, null, borderGeometry);
                }

                StreamGeometry backgroundGeometry = BackgroundGeometryCache;
                if (backgroundGeometry != null &&
                    (brush = Background) != null)
                {
                    dc.DrawGeometry(brush, null, backgroundGeometry);
                }
            }
            else
            {
                Thickness border = BorderThickness;
                Brush     borderBrush;

                CornerRadius cornerRadius      = CornerRadius;
                double       outerCornerRadius = cornerRadius.TopLeft; // Already validated that all corners have the same radius
                bool         roundedCorners    = !DoubleUtil.IsZero(outerCornerRadius);

                // If we have a brush with which to draw the border, do so.
                // NB: We double draw corners right now.  Corner handling is tricky (bevelling, &c...) and
                //     we need a firm spec before doing "the right thing."  (greglett, ffortes)
                if (!border.IsZero &&
                    (borderBrush = BorderBrush) != null)
                {
                    // Initialize the first pen.  Note that each pen is created via new()
                    // and frozen if possible.  Doing this avoids the pen
                    // being copied when used in the DrawLine methods.
                    Pen pen = LeftPenCache;
                    if (pen == null)
                    {
                        pen       = new Pen();
                        pen.Brush = borderBrush;

                        if (useLayoutRounding)
                        {
                            pen.Thickness = UIElement.RoundLayoutValue(border.Left, FrameworkElement.DpiScaleX);
                        }
                        else
                        {
                            pen.Thickness = border.Left;
                        }
                        if (borderBrush.IsFrozen)
                        {
                            pen.Freeze();
                        }

                        LeftPenCache = pen;
                    }

                    double halfThickness;
                    if (border.IsUniform)
                    {
                        halfThickness = pen.Thickness * 0.5;


                        // Create rect w/ border thickness, and round if applying layout rounding.
                        Rect rect = new Rect(new Point(halfThickness, halfThickness),
                                             new Point(RenderSize.Width - halfThickness, RenderSize.Height - halfThickness));

                        if (roundedCorners)
                        {
                            dc.DrawRoundedRectangle(
                                null,
                                pen,
                                rect,
                                outerCornerRadius,
                                outerCornerRadius);
                        }
                        else
                        {
                            dc.DrawRectangle(
                                null,
                                pen,
                                rect);
                        }
                    }
                    else
                    {
                        // Nonuniform border; stroke each edge.
                        if (DoubleUtil.GreaterThan(border.Left, 0))
                        {
                            halfThickness = pen.Thickness * 0.5;
                            dc.DrawLine(
                                pen,
                                new Point(halfThickness, 0),
                                new Point(halfThickness, RenderSize.Height));
                        }

                        if (DoubleUtil.GreaterThan(border.Right, 0))
                        {
                            pen = RightPenCache;
                            if (pen == null)
                            {
                                pen       = new Pen();
                                pen.Brush = borderBrush;

                                if (useLayoutRounding)
                                {
                                    pen.Thickness = UIElement.RoundLayoutValue(border.Right, FrameworkElement.DpiScaleX);
                                }
                                else
                                {
                                    pen.Thickness = border.Right;
                                }

                                if (borderBrush.IsFrozen)
                                {
                                    pen.Freeze();
                                }

                                RightPenCache = pen;
                            }

                            halfThickness = pen.Thickness * 0.5;
                            dc.DrawLine(
                                pen,
                                new Point(RenderSize.Width - halfThickness, 0),
                                new Point(RenderSize.Width - halfThickness, RenderSize.Height));
                        }

                        if (DoubleUtil.GreaterThan(border.Top, 0))
                        {
                            pen = TopPenCache;
                            if (pen == null)
                            {
                                pen       = new Pen();
                                pen.Brush = borderBrush;
                                if (useLayoutRounding)
                                {
                                    pen.Thickness = UIElement.RoundLayoutValue(border.Top, FrameworkElement.DpiScaleY);
                                }
                                else
                                {
                                    pen.Thickness = border.Top;
                                }

                                if (borderBrush.IsFrozen)
                                {
                                    pen.Freeze();
                                }

                                TopPenCache = pen;
                            }

                            halfThickness = pen.Thickness * 0.5;
                            dc.DrawLine(
                                pen,
                                new Point(0, halfThickness),
                                new Point(RenderSize.Width, halfThickness));
                        }

                        if (DoubleUtil.GreaterThan(border.Bottom, 0))
                        {
                            pen = BottomPenCache;
                            if (pen == null)
                            {
                                pen       = new Pen();
                                pen.Brush = borderBrush;
                                if (useLayoutRounding)
                                {
                                    pen.Thickness = UIElement.RoundLayoutValue(border.Bottom, FrameworkElement.DpiScaleY);
                                }
                                else
                                {
                                    pen.Thickness = border.Bottom;
                                }
                                if (borderBrush.IsFrozen)
                                {
                                    pen.Freeze();
                                }

                                BottomPenCache = pen;
                            }

                            halfThickness = pen.Thickness * 0.5;
                            dc.DrawLine(
                                pen,
                                new Point(0, RenderSize.Height - halfThickness),
                                new Point(RenderSize.Width, RenderSize.Height - halfThickness));
                        }
                    }
                }

                // Draw background in rectangle inside border.
                Brush background = Background;
                if (background != null)
                {
                    // Intialize background
                    Point ptTL, ptBR;

                    if (useLayoutRounding)
                    {
                        ptTL = new Point(UIElement.RoundLayoutValue(border.Left, FrameworkElement.DpiScaleX),
                                         UIElement.RoundLayoutValue(border.Top, FrameworkElement.DpiScaleY));
                        ptBR = new Point(UIElement.RoundLayoutValue(RenderSize.Width - border.Right, FrameworkElement.DpiScaleX),
                                         UIElement.RoundLayoutValue(RenderSize.Height - border.Bottom, FrameworkElement.DpiScaleY));
                    }
                    else
                    {
                        ptTL = new Point(border.Left, border.Top);
                        ptBR = new Point(RenderSize.Width - border.Right, RenderSize.Height - border.Bottom);
                    }

                    // Do not draw background if the borders are so large that they overlap.
                    if (ptBR.X > ptTL.X && ptBR.Y > ptTL.Y)
                    {
                        if (roundedCorners)
                        {
                            Radii  innerRadii        = new Radii(cornerRadius, border, false); // Determine the inner edge radius
                            double innerCornerRadius = innerRadii.TopLeft;                     // Already validated that all corners have the same radius
                            dc.DrawRoundedRectangle(background, null, new Rect(ptTL, ptBR), innerCornerRadius, innerCornerRadius);
                        }
                        else
                        {
                            dc.DrawRectangle(background, null, new Rect(ptTL, ptBR));
                        }
                    }
                }
            }
        }
Example #37
0
        // Displays the image and calls Detect Faces.

        private async void BrowseButton_Click(object sender, RoutedEventArgs e)
        {
            // Get the image file to scan from the user.
            var openDlg = new Microsoft.Win32.OpenFileDialog();

            openDlg.Filter = "JPEG Image(*.jpg)|*.jpg";
            bool?result = openDlg.ShowDialog(this);

            // Return if canceled.
            if (!(bool)result)
            {
                return;
            }

            // Display the image file.
            string filePath = openDlg.FileName;

            Uri         fileUri      = new Uri(filePath);
            BitmapImage bitmapSource = new BitmapImage();

            bitmapSource.BeginInit();
            bitmapSource.CacheOption = BitmapCacheOption.None;
            bitmapSource.UriSource   = fileUri;
            bitmapSource.EndInit();

            FacePhoto.Source = bitmapSource;


            // Detect any faces in the image.
            Title = "Detecting...";
            faces = await UploadAndDetectFaces(filePath);

            Title = String.Format("Detection Finished. {0} face(s) detected", faces.Length);

            if (faces.Length > 0)
            {
                // Prepare to draw rectangles around the faces.
                DrawingVisual  visual         = new DrawingVisual();
                DrawingContext drawingContext = visual.RenderOpen();
                drawingContext.DrawImage(bitmapSource,
                                         new Rect(0, 0, bitmapSource.Width, bitmapSource.Height));
                double dpi = bitmapSource.DpiX;
                resizeFactor     = 96 / dpi;
                faceDescriptions = new String[faces.Length];

                for (int i = 0; i < faces.Length; ++i)
                {
                    Face face = faces[i];

                    // Draw a rectangle on the face.
                    drawingContext.DrawRectangle(
                        Brushes.Transparent,
                        new Pen(Brushes.Red, 2),
                        new Rect(
                            face.FaceRectangle.Left * resizeFactor,
                            face.FaceRectangle.Top * resizeFactor,
                            face.FaceRectangle.Width * resizeFactor,
                            face.FaceRectangle.Height * resizeFactor
                            )
                        );

                    // Store the face description.
                    faceDescriptions[i] = FaceDescription(face);
                }

                drawingContext.Close();

                // Display the image with the rectangle around the face.
                RenderTargetBitmap faceWithRectBitmap = new RenderTargetBitmap(
                    (int)(bitmapSource.PixelWidth * resizeFactor),
                    (int)(bitmapSource.PixelHeight * resizeFactor),
                    96,
                    96,
                    PixelFormats.Pbgra32);

                faceWithRectBitmap.Render(visual);
                FacePhoto.Source = faceWithRectBitmap;

                // Set the status bar text.
                faceDescriptionStatusBar.Text = "Place the mouse pointer over a face to see the face description.";
            }
        }
 void DrawScene(DrawingContext dc) {
   dc.DrawRectangle(Brushes.White, null, new Rect(0, 0, 500, 500));
   DrawBall(dc);
 }
Example #39
0
        protected override void OnRender(DrawingContext dc)
        {
            /*var text_lines = new List<string>();

            int maxlength = 0;
            string indent_string = new string(' ', _textView.FormattedLineSource.TabSize);
            var lines = _textView.TextBuffer.CurrentSnapshot.Lines;
            foreach (var line in lines)
            {
                string text = line.GetText();
                text = text.Replace("\t", indent_string);
                text_lines.Add(text);
                maxlength = Math.Max(maxlength, text.Length);
            }

            double symbol_size = this.Width/maxlength;
            int line_index = 0;
            foreach (var line in text_lines)
            {
                int symbol_index = 0;
                foreach (var c in line)
                {
                    if (c != ' ')
                    {
                        double left = symbol_index * symbol_size;
                        var brush = new SolidColorBrush(Color.FromArgb(127, 0, 0, 0));
                        dc.DrawRectangle(brush, null, new Rect(left, line_index * 1.6 + 1, symbol_size, 1))
                    }
                    symbol_index++;
                }
                line_index++;
            }*/

            var snapshot = _textView.TextSnapshot;
            var segments = _textParser.Parse(_textView);

            //	calculate max string length
            int maxlength = 0;
            foreach (var line in snapshot.Lines)
            {
                string text = line.GetText();
                maxlength = Math.Max(maxlength, text.Length);
            }

            double symbol_size = this.Width / maxlength;
            foreach (var segment in segments)
            {
                string text = snapshot.GetText(segment.span);
                ITextSnapshotLine line = snapshot.GetLineFromPosition(segment.span.Start);

                double x = (segment.span.Start - line.Start.Position) * symbol_size;
                double y = line.LineNumber * 2.0;
                double w = (segment.span.Length) * symbol_size;
                double h = 1;

                var brush = new SolidColorBrush(segment.color);
                dc.DrawRectangle(brush, null, new Rect(x, y, w, h));
            }
        }