Example #1
0
        private void Canvas_Draw(CanvasControl sender, CanvasDrawEventArgs args)
        {
            var a = new Vector2(10, 10);
            var b = new Vector2(100, 100);

            args.DrawingSession.DrawLine(a, b, Colors.Yellow);
        }
Example #2
0
        private void canvasCtrl_Draw(CanvasControl sender, CanvasDrawEventArgs args)
        {
            if (!this.initialized) {
                return;
            }
            this.host.CallFunction("drawScene");
            var target = (CanvasRenderTarget)this.host.Window.Render();

            args.DrawingSession.DrawImage(target);


            if (drawCount == 0) {
                this.start = DateTime.Now;
            }
            drawCount++;
            var seconds = (DateTime.Now - this.start).TotalSeconds;
            if (seconds > 0) {
                var fps = drawCount / seconds;

                args.DrawingSession.DrawText(fps.ToString("0.#") + "fps", 10, 10, Colors.Red);
            }

            // triggers next Draw event at max 60fps
            this.canvasCtrl.Invalidate();
        }
 private void Canvas_Draw(CanvasControl sender, CanvasDrawEventArgs args)
 {
     GaussianBlurEffect effect = new GaussianBlurEffect()
     {
         Source = _bitmap,
         BlurAmount = 5,
         BorderMode = EffectBorderMode.Hard
     };
     args.DrawingSession.DrawImage(effect);
 }
Example #4
0
 private void CanvasControl_Draw(CanvasControl sender, CanvasDrawEventArgs args)
 {
     CubeHelper helper = new CubeHelper(GetLength());
     foreach (Tuple<Vector2, Vector2> edge in helper.GetEdges(currentTransformation))
     {
         ColorValue colorValue = ColorComboBox.SelectedValue as ColorValue;
         Color color = (colorValue == null ? Colors.Black : colorValue.Color);
         args.DrawingSession.DrawLine(edge.Item1, edge.Item2, color);
     }
 }
Example #5
0
        void Canvas_Draw(CanvasControl sender, CanvasDrawEventArgs args)
        {
            var ds = args.DrawingSession;
            ds.Clear(Color.FromArgb(0,0,0,0));

            var shape = this.Shapes.SelectedItem as Shape;
            if (shape == null)
                return;

            var width = sender.ActualWidth;
            var height = sender.ActualHeight;

            if (shape.Drawer != null)
                shape.Drawer(sender, ds);
        }
Example #6
0
        void OnDraw(CanvasControl sender, CanvasDrawEventArgs args)
        {
            float strokeWidth = 1;

            sharedResources = GetSharedResources(sender);
            var arrow = sharedResources.GetArrow(TextDirection);
            var bounds = arrow.ComputeStrokeBounds(strokeWidth);

            var ds = args.DrawingSession;

            var foregroundBrush = (SolidColorBrush)this.Foreground;
            var color = foregroundBrush.Color;

            arrow = arrow.Transform(CalculateTransform(bounds, new Rect(new Point(0, 0), sender.Size)));

            ds.DrawGeometry(arrow, color, strokeWidth, ArrowStrokeStyle);
        }
        public void Draw(CanvasControl sender, CanvasDrawEventArgs args)
        {
            var size = sender.Size;
            using (var ds = args.DrawingSession)
            {
                ds.DrawImage(effect, (size.ToVector2() - currentEffectSize) / 2);
                var brush = new CanvasImageBrush(sender, this.effect)
                {
                    ExtendX = CanvasEdgeBehavior.Wrap,
                    ExtendY = CanvasEdgeBehavior.Wrap,
                    SourceRectangle = new Rect(0, bitmap.SizeInPixels.Height - 96, 96, 96)
                };

                ds.FillRectangle(0, 0, (float)this.ActualWidth, (float)this.ActualHeight, brush);
            }
            sender.Invalidate();
        }
 private void OnDraw(CanvasControl sender, CanvasDrawEventArgs args)
 {
     if (_graphics == null)
     {
         _graphics = new NativeGraphics();
         _graphics.destination = new AsyncGraphics(args.DrawingSession);
         _graphics.resetClip();
     }
     else
     {
         ((AsyncGraphics)_graphics.destination).getInternal().setGraphics(args.DrawingSession);
     }
     if (renderingOperations.Count > 0)
     {
         foreach (AsyncOp o in renderingOperations)
         {
             //Debug.WriteLine("OnDraw - execute " + o);
             o.executeWithClip(((AsyncGraphics)_graphics.destination).getInternal());
         }
     }
     args.DrawingSession.Dispose();
     renderingOperations.Clear();
 }
        void Canvas_Draw(CanvasControl sender, CanvasDrawEventArgs args)
        {
            if (CanvasImage.IsHistogramSupported(sender.Device))
            {
                SetEffectProperties();

                // Draw the image.
                if (!ThumbnailGenerator.IsDrawingThumbnail)
                {
                    args.DrawingSession.DrawImage(hueEffect, (sender.Size.ToVector2() - bitmap.Size.ToVector2()) * new Vector2(0.5f, 0.25f));
                }

                // Overlay a histogram for each color channel.
                args.DrawingSession.Blend = CanvasBlend.Add;

                DrawHistogram(args.DrawingSession, sender.Size, EffectChannelSelect.Red,   redBrush);
                DrawHistogram(args.DrawingSession, sender.Size, EffectChannelSelect.Green, greenBrush);
                DrawHistogram(args.DrawingSession, sender.Size, EffectChannelSelect.Blue,  blueBrush);
            }
            else
            {
                DrawNotSupported(args.DrawingSession, sender.Size);
            }
        }
        private void Draw(CanvasControl sender, CanvasDrawEventArgs args)
        {
            if (_contentPresenter == null) return;

            var border = VisualTreeHelper.GetChild(_contentPresenter, 0) as Border;
            if (border == null) return;

            var borderPoint = border.TransformToVisual(this).TransformPoint(new Point(0, 0));

            var cl = new CanvasCommandList(sender);
            using (var clds = cl.CreateDrawingSession())
            {
                clds.FillRoundedRectangle(new Rect(borderPoint.X, borderPoint.Y, border.ActualWidth, border.ActualHeight), (float)border.CornerRadius.TopLeft, (float)border.CornerRadius.TopLeft, Color.FromArgb(128, 0, 0, 0));
            }

            var shadowEffect = new Transform2DEffect
            {
                Source =
                    new Transform2DEffect
                    {
                        Source = new ShadowEffect
                        {
                            BlurAmount = 2,
                            ShadowColor = Color.FromArgb(160, 0, 0, 0),
                            Source = cl
                        },
                        //TODO not doing any scaling right now, confirm with larger shadows
                        TransformMatrix = Matrix3x2.CreateScale(1.0f, new Vector2((float)(border.ActualWidth / 2), ((float)border.ActualHeight / 2)))

                    },
                TransformMatrix = Matrix3x2.CreateTranslation(0, 1)
            };

            args.DrawingSession.DrawImage(shadowEffect);
            // args.DrawingSession.DrawImage(cl);
        }
Example #11
0
        void Canvas_Draw(CanvasControl sender, CanvasDrawEventArgs args)
        {
            // Transform and clip so the scene will fit whatever size display we are running on.
            Vector2 sceneSize = sceneSizes[whichScene];

            args.DrawingSession.Transform = Utils.GetDisplayTransform(sender.Size.ToVector2(), sceneSize);

            using (args.DrawingSession.CreateLayer(1f, new Rect(0, 0, sceneSize.X, sceneSize.Y)))
            {
                // Draw the vector art.
                currentDrawingSession = args.DrawingSession;

                switch (whichScene)
                {
                    case 0:
                        DrawScene0();
                        break;

                    case 1:
                        DrawScene1(randomSeed);
                        break;
                }
            }
        }
        private void canvasControl_Draw(CanvasControl sender, CanvasDrawEventArgs args)
        {
            if (DesignMode.DesignModeEnabled)
                return;

            if (modeInstance == null)
            {
                frameCounter = 0;
                modeInstance = CurrentMode.Create(this, sender);
            }

            modeInstance.Draw(args.DrawingSession, frameCounter, (float)sender.ActualWidth, (float)sender.ActualHeight);

            frameCounter++;
            sender.Invalidate();
        }
Example #13
0
 void canvasControl_Draw(CanvasControl sender, CanvasDrawEventArgs args)
 {
     args.DrawingSession.Clear(Colors.CornflowerBlue);
     args.DrawingSession.DrawEllipse(190, 125, 140, 40, Colors.Black, 6);
     args.DrawingSession.DrawText("Hello, world!", 100, 100, Colors.Yellow);
 }
Example #14
0
        void Canvas_Draw(CanvasControl sender, CanvasDrawEventArgs args)
        {
            var ds = args.DrawingSession;

            var centerPoint = (arcPoints[0] + arcPoints[1]) / 2;

            // Draw the end point markers.
            if (!ThumbnailGenerator.IsDrawingThumbnail)
            {
                for (int i = 0; i < 2; i++)
                {
                    ds.DrawCircle(arcPoints[i], hitTestRadius, (i == activeDrag) ? Colors.White : Colors.Gray);
                }
            }

            switch (CurrentOverload)
            {
                case AddArcOverload.AroundEllipse:
                    // Compute positions.
                    var ellipseRadius = (arcPoints[1] - arcPoints[0]) / 2;

                    ellipseRadius.X = Math.Abs(ellipseRadius.X);
                    ellipseRadius.Y = Math.Abs(ellipseRadius.Y);

                    float startAngle = Utils.DegreesToRadians(ArcStartAngle);
                    float sweepAngle = Utils.DegreesToRadians(ArcSweepAngle);

                    var startPoint = centerPoint + Vector2.Transform(Vector2.UnitX, Matrix3x2.CreateRotation(startAngle)) * ellipseRadius;

                    // Draw the bounding rectangle.
                    if (!ThumbnailGenerator.IsDrawingThumbnail)
                    {
                        ds.DrawRectangle(new Rect(arcPoints[0].ToPoint(), arcPoints[1].ToPoint()), Color.FromArgb(255, 64, 64, 64));
                    }

                    // Draw the arc.
                    using (var builder = new CanvasPathBuilder(sender))
                    {
                        builder.BeginFigure(startPoint);
                        builder.AddArc(centerPoint, ellipseRadius.X, ellipseRadius.Y, startAngle, sweepAngle);
                        builder.EndFigure(CanvasFigureLoop.Open);

                        using (var geometry = CanvasGeometry.CreatePath(builder))
                        {
                            ds.DrawGeometry(geometry, Colors.Yellow, strokeWidth, strokeStyle);
                        }
                    }
                    break;

                case AddArcOverload.PointToPoint:
                    // Display a warning if this is an invalid arc configuration.
                    bool isRadiusTooSmall = IsArcRadiusTooSmall();

                    if (isRadiusTooSmall)
                    {
                        ds.DrawText("Radius is less than the\ndistance between the\nstart and end points", centerPoint, Colors.Red, textFormat);
                    }

                    // Draw the arc.
                    using (var builder = new CanvasPathBuilder(sender))
                    {
                        builder.BeginFigure(arcPoints[0]);
                        builder.AddArc(arcPoints[1], ArcRadiusX, ArcRadiusY, Utils.DegreesToRadians(ArcRotation), ArcSweepDirection, ArcSize);
                        builder.EndFigure(CanvasFigureLoop.Open);

                        using (var geometry = CanvasGeometry.CreatePath(builder))
                        {
                            ds.DrawGeometry(geometry, isRadiusTooSmall ? Colors.Red : Colors.Yellow, strokeWidth, strokeStyle);
                        }
                    }
                    break;
            }
        }
Example #15
0
        void OnCanvasControlDraw(CanvasControl sender, CanvasDrawEventArgs args)
        {
            CanvasDrawingSession session = args.DrawingSession;

            // Recreate the geometry if necessary
            if (baseGeometry == null)
            {
                BuildGeometry(session);
            }

            // Don't continue if stretchedGeometry does not exist
            if (stretchedGeometry == null)
            {
                return;
            }

            // Recreate the brushes if necessary.
            if (xamStroke != null && strokeBrushWrapper.Brush == null)
            {
                ConvertBrush(session, xamStroke, strokeBrushWrapper);
            }

            if (xamFill != null && fillBrushWrapper.Brush == null)
            {
                ConvertBrush(session, xamFill, fillBrushWrapper);
            }

            // Don't continue if both brushes are null.
            if (strokeBrushWrapper.Brush == null && fillBrushWrapper.Brush == null)
            {
                return;
            }

            // If it's a Rectangle, RadiusX and RadiusY must be independent of Stretch
            if (this is RectangleCanvasControl)
            {
                float radiusX = (this as RectangleCanvasControl).RadiusX;
                float radiusY = (this as RectangleCanvasControl).RadiusY;
                stretchedGeometry = CanvasGeometry.CreateRoundedRectangle(session, stretchedGeometryBounds, radiusX, radiusY);
            }

            // Shift so negative coordinates are visible.
            session.Transform = renderMatrix;

            // Brush-fixing logic. TODO: This is similar for stroke and fill and can probably
            //  be consolidated in a Func.
            if (fillBrushWrapper.Brush != null)
            {
                bool okToRender = true;

                if (fillBrushWrapper.Brush is CanvasLinearGradientBrush)
                {
                    fillBrushWrapper.SetGradientPoints(stretchedGeometryBounds);
                }
                else if (fillBrushWrapper.Brush is CanvasImageBrush)
                {
                    okToRender = fillBrushWrapper.SetImageBrushBitmap();
                }

                if (okToRender)
                {
                    session.FillGeometry(stretchedGeometry, fillBrushWrapper.Brush);
                }
            }
            if (strokeBrushWrapper.Brush != null)
            {
                bool okToRender = true;

                if (strokeBrushWrapper.Brush is CanvasLinearGradientBrush)
                {
                    strokeBrushWrapper.SetGradientPoints(stretchedGeometryStrokeBounds);
                }
                else if (strokeBrushWrapper.Brush is CanvasImageBrush)
                {
                    okToRender = strokeBrushWrapper.SetImageBrushBitmap();
                }

                if (okToRender)
                {
                    session.DrawGeometry(stretchedGeometry, strokeBrushWrapper.Brush, strokeWidth, strokeStyle);
                }
            }
        }
 private void ChartWin2DCanvas_Draw(CanvasControl sender, CanvasDrawEventArgs args)
 {
     if (_offscreenBackGround != null)
     {
         //background with lines and value texts
         args.DrawingSession.DrawImage(_offscreenBackGround, new Rect(new Point(0, 0), ChartWin2DCanvas.Size), new Rect(new Point(0, 0), _offscreenBackGround.Size));
         if (_offscreenChartImage != null)
         {
             //the actual graph is drawn in here, according to move & zoom values
             args.DrawingSession.DrawImage(_offscreenChartImage, new Rect(new Point(0, 0), ChartWin2DCanvas.Size), new Rect(_graphDrawingPoint, _graphDrawingSource));
         }
     }
     else {
         // in the start we don't have data, so we'll just draw the background rect with background color
         args.DrawingSession.DrawRectangle(0, 0, (float)ChartWin2DCanvas.Size.Width, (float)ChartWin2DCanvas.Size.Height, BACKGROUND_COLOR);
     }
 }
Example #17
0
 private void OnDraw(CanvasControl sender, CanvasDrawEventArgs args)
 {
     this.UpdateGeometry(args.DrawingSession, sender.Size);
 }
Example #18
0
        private void TheCanvas_Draw(CanvasControl sender, CanvasDrawEventArgs e)
        {
            /*
             *
             *
             * FROM https://en.wikipedia.org/wiki/Mandelbrot_set#Computer_drawings
             * For each pixel (Px, Py) on the screen, do:
             * {
             * x0 = scaled x coordinate of pixel (scaled to lie in the Mandelbrot X scale (-2.5, 1))
             * y0 = scaled y coordinate of pixel (scaled to lie in the Mandelbrot Y scale (-1, 1))
             * x = 0.0
             * y = 0.0
             * iteration = 0
             * max_iteration = 1000
             * while (x*x + y*y < 2*2  AND  iteration < max_iteration) {
             * xtemp = x*x - y*y + x0
             * y = 2*x*y + y0
             * x = xtemp
             * iteration = iteration + 1
             * }
             * color = palette[iteration]
             * plot(Px, Py, color)
             * }
             *
             */


            double paletteMin = 30, palletteMax = 330;

            Rect  rect;
            Color color;

            List <Color> pallette = new List <Color>();

            Rect bounds;

            bounds = new Rect(new Point(-2, 0.5), new Point(-1, -0.5));

            bounds = GetBounds(-0.7463, 0.1102, 0.005);

            bounds = GetBounds(-0.7453, 0.1127, 0.00065);

            int iterations = 10000;

            double palletteStep = (palletteMax - paletteMin) / (double)iterations;
            double hue;

            for (int i = 0; i < iterations; ++i)
            {
                hue = paletteMin + (i * palletteStep);

                while (hue > 360)
                {
                    hue -= 360.0;
                }

                pallette.Add(Microsoft.Toolkit.Uwp.Helpers.ColorHelper.FromHsv(hue, 1, 1));
            }

            double deltaX = bounds.Width / this.ActualWidth;
            double deltaY = bounds.Height / this.ActualHeight;

            Point logicalPoint;

            double x, y;

            for (double pX = 0.0; pX < this.ActualWidth; ++pX)
            {
                x = (pX * deltaX) + bounds.Left;
                for (double pY = 0; pY < this.ActualHeight; ++pY)
                {
                    y            = (pY * deltaY) + bounds.Top;
                    logicalPoint = new Point(x, y);
                    color        = GetColorForPoint(pallette, logicalPoint);

                    rect = new Rect(new Point(pX, pY), new Size(1, 1));

                    e.DrawingSession.DrawRectangle(rect, color);
                }
            }
        }
Example #19
0
        protected void valueControl_Draw(CanvasControl sender, CanvasDrawEventArgs args)
        {
            this.EnsureResources(sender, args);
            CanvasDrawingSession ds = args.DrawingSession;

            float height = (float)(sender.ActualHeight * _gaugeGridHeight);
            float yTop   = (float)(sender.ActualHeight - height) / 2F;

            height -= 4F * c_boxThickness;
            yTop   += 2F * c_boxThickness;

            float increment = (float)(height / (this.MaxValue - this.MinValue));

            float atX = 10F;
            float atY = (float)(yTop + height - ((this.Value - this.MinValue) * increment));

            Vector2 atPointer = new Vector2(atX, atY);

            Rect pointerBoundingRectangle;
            Rect valueBoundingRectangle;

            using (var textFormat = new CanvasTextFormat()
            {
                HorizontalAlignment = CanvasHorizontalAlignment.Center,
                VerticalAlignment = CanvasVerticalAlignment.Center,
                FontSize = 32, // (float)this.ValueFontSize,
            })
            {
                ds.DrawText("â—„", atPointer, this.GaugePointerColor, textFormat);
                pointerBoundingRectangle = Utilities.CalculateStringBoundingRectangle(sender, args, "â—„", textFormat);
            }

            using (var textFormat = new CanvasTextFormat()
            {
                HorizontalAlignment = CanvasHorizontalAlignment.Left,
                VerticalAlignment = CanvasVerticalAlignment.Center,
                FontSize = (float)this.ValueFontSize * 0.8F,
            })
            {
                string  format = "{0:F" + string.Format("{0:F0}", this.Resolution) + "}";
                Vector2 at     = new Vector2(
                    (float)pointerBoundingRectangle.Width,
                    atPointer.Y);

                ds.DrawText(string.Format(format, this.Value), at, this.GaugePointerColor, textFormat);
                valueBoundingRectangle = Utilities.CalculateStringBoundingRectangle(sender, args, string.Format(format, this.Value), textFormat);
            }

            using (var textFormat = new CanvasTextFormat()
            {
                HorizontalAlignment = CanvasHorizontalAlignment.Left,
                VerticalAlignment = CanvasVerticalAlignment.Center,
                FontSize = (float)this.UnitsFontSize * 0.9F
            })
            {
                Vector2 at = new Vector2(
                    (float)pointerBoundingRectangle.Width,
                    atPointer.Y + (float)valueBoundingRectangle.Height * 0.9F);
                ds.DrawText(this.Units, at, this.GaugePointerColor, textFormat);
            }
        }
Example #20
0
 protected abstract void DrawGhost(CanvasControl sender, CanvasDrawEventArgs args);
Example #21
0
        private void canvas_Draw(CanvasControl sender, CanvasDrawEventArgs args)
        {
            startupGraphic();

            //Horizontal da canvas
            float vx = totalVL + lateralArea;

            while (vx < drawAreaHorizontal + lateralArea)
            {
                args.DrawingSession.DrawLine(vx, 0, vx, drawAreaVertical + 30, Colors.DarkGray, (float)1.5, strokeStyle);
                vx = vx + totalVL;
            }

            //Linha de isolamento superior
            args.DrawingSession.DrawLine(0 + lateralArea, 10, drawAreaHorizontal + lateralArea, 10, Colors.DarkGray, (float)1.5, strokeStyle);
            //Linha de isolamento lateral
            args.DrawingSession.DrawLine(0 + lateralArea, 0, 0 + lateralArea, drawAreaVertical + 30, Colors.DarkGray, (float)1.5, strokeStyle);
            //Linha de isolamento inferior
            args.DrawingSession.DrawLine(0 + lateralArea, drawAreaVertical, drawAreaHorizontal + lateralArea, drawAreaVertical, Colors.DarkGray, (float)1.5, strokeStyle);

            //Texto inferior
            float  tx    = 0;
            int    ix    = 0;
            string month = "JAN";

            while (tx <= drawAreaHorizontal)
            {
                #region IF MESES
                if (ix == 0)
                {
                    month = "JAN";
                }
                if (ix == 1)
                {
                    month = "FEV";
                }
                if (ix == 2)
                {
                    month = "MAR";
                }
                if (ix == 3)
                {
                    month = "ABR";
                }
                if (ix == 4)
                {
                    month = "MAI";
                }
                if (ix == 5)
                {
                    month = "JUN";
                }
                if (ix == 6)
                {
                    month = "JUL";
                }
                if (ix == 7)
                {
                    month = "AGO";
                }
                if (ix == 8)
                {
                    month = "SET";
                }
                if (ix == 9)
                {
                    month = "OUT";
                }
                if (ix == 10)
                {
                    month = "NOV";
                }
                if (ix == 11)
                {
                    month = "DEZ";
                }
                #endregion

                args.DrawingSession.DrawText(month, new Vector2(tx + ((totalVL / 2) - 15) + lateralArea, (float)canvas.ActualHeight - 25), Colors.DarkGray, MonthsFormat);
                tx = tx + totalVL;
                ix++;
            }

            //Texto lateral
            float ty = 0;
            float iy = vMax;
            while (ty <= drawAreaVertical - 10)
            {
                args.DrawingSession.DrawText(string.Format(cultureInfo, "{0:C}", iy), new Vector2(10, ty), Colors.DarkGray, ValuesFormat);
                iy = iy - (vMax / itemsV);

                ty = ty + totalHL;
            }

            //Vertical da canvas
            float hy = totalHL + 10;
            while (hy < (drawAreaVertical - 10))
            {
                args.DrawingSession.DrawLine(0 + lateralArea, hy, drawAreaHorizontal + lateralArea, hy, Colors.DarkGray, (float)1.5, strokeStyle);
                hy = hy + totalHL;
            }

            //Desenha o gráfico mensal manual
            foreach (line l in Lines)
            {
                args.DrawingSession.DrawLine(l.x1, l.y1, l.x2, l.y2, Colors.Red, 1);

                if (l.isMouseOver == true)
                {
                    args.DrawingSession.DrawRectangle(new Rect(new Point(l.x2 + 5, l.y2 + 5), new Point(l.x2 - 5, l.y2 - 5)), Colors.DeepSkyBlue);

                    args.DrawingSession.DrawText(string.Format(cultureInfo, "{0:C}", l.value), new Vector2(l.x2 + 10, l.y2 - 8), Colors.DarkGray, ValuesFormat);
                }
            }

            //Desenha itens aleatórios no gráfico
            if (draw == true)
            {
                int iT = 0;
                while (iT < itemsTotal)
                {
                    if (iT == 0)
                    {
                        x1 = totalVL + lateralArea;
                        y1 = rnd.Next(10, (int)drawAreaVertical + 1);
                        args.DrawingSession.DrawLine(lateralArea, rnd.Next(10, (int)drawAreaVertical), x1, y1, Colors.Red, 1);

                        a1 = totalVL + lateralArea;
                        b1 = rnd.Next(10, (int)drawAreaVertical + 1);
                        args.DrawingSession.DrawLine(lateralArea, rnd.Next(10, (int)drawAreaVertical), a1, b1, Colors.YellowGreen, 1);
                        iT++;
                    }
                    if (iT > 0)
                    {
                        x2 = x1 + totalVL;
                        y2 = rnd.Next(10, (int)drawAreaVertical + 1);
                        args.DrawingSession.DrawLine(x1, y1, x2, y2, Colors.Red, 1);
                        x1 = x2;
                        y1 = y2;

                        a2 = a1 + totalVL;
                        b2 = rnd.Next(10, (int)drawAreaVertical + 1);
                        args.DrawingSession.DrawLine(a1, b1, a2, b2, Colors.YellowGreen, 1);
                        a1 = a2;
                        b1 = b2;
                        iT++;
                    }
                }
                draw = false;
            }
        }
Example #22
0
        void Canvas_Draw(CanvasControl sender, CanvasDrawEventArgs args)
        {
            var currentShape = availableShapes[this.Shapes.SelectedIndex];

            currentShape.Drawer(sender, args.DrawingSession);
        }
        void OnDrawGpuGraph(CanvasControl sender, CanvasDrawEventArgs args)
        {
            var graphDrawer = new GraphDrawer((float)sender.ActualWidth, (float)sender.ActualHeight, Scenarios, e => e.GpuTimeInMs, "GPU");

            graphDrawer.Draw(args.DrawingSession);
        }
Example #24
0
        private void Canvas_Draw(CanvasControl sender, CanvasDrawEventArgs args)
        {
            strokeStyle.StartCap = StartCap;
            strokeStyle.EndCap = EndCap;
            strokeStyle.DashStyle = DashStyle;
            strokeStyle.DashCap = DashCap;
            strokeStyle.LineJoin = LineJoin;

            var ds = args.DrawingSession;

            var width = (float)sender.ActualWidth;
            var height = (float)sender.ActualHeight;

            var col1Left = width * 0.1f;
            var col1Right = width * 0.4f;
            var col2Left = width * 0.6f;
            var col2Right = width * 0.9f;

            var row1Top = height * 0.1f;
            var row1Bottom = height * 0.4f;
            var row2Top = height * 0.6f;
            var row2Bottom = height * 0.9f;

            //
            // Draw hairlines showing the start/end points of the line.  
            // This helps demonstrate the behavior of start/end cap.
            //
            ds.DrawLine(
                col1Left,
                row1Top,
                col1Left,
                row1Bottom,
                Colors.Aqua,
                1.0f,
                this.hairlineStrokeStyle);

            ds.DrawLine(
                col1Right,
                row1Top,
                col1Right,
                row1Bottom,
                Colors.Aqua,
                1.0f,
                this.hairlineStrokeStyle);

            //
            // Draw the demo shapes with the chosen stroke style
            //
            var strokeWidth = (float)Math.Max(5, Math.Min(30, width / 50));

            ds.DrawLine(
                col1Left, 
                (row1Top + row1Bottom) / 2,
                col1Right,
                (row1Top + row1Bottom) / 2,
                Colors.Green,
                strokeWidth,
                this.strokeStyle);

            ds.DrawRectangle(
                new Rect(new Point(col2Left, row1Top), new Point(col2Right, row1Bottom)),
                Colors.Green,
                strokeWidth,
                this.strokeStyle);

            ds.DrawRoundedRectangle(
                new Rect(new Point(col1Left, row2Top), new Point(col1Right, row2Bottom)),
                width * 0.1f,
                height * 0.1f,
                Colors.Green,
                strokeWidth,
                this.strokeStyle);

            ds.DrawEllipse(
                (col2Left + col2Right) / 2,
                (row2Top + row2Bottom) / 2,
                (col2Right - col2Left) / 2,
                (row2Bottom - row2Top) / 2,
                Colors.Green,
                strokeWidth,
                this.strokeStyle);

            //
            // Explain what is going on if this combination of properties leaves dots invisible
            //
            bool hasDots = DashStyle == CanvasDashStyle.Dot ||
                           DashStyle == CanvasDashStyle.DashDot ||
                           DashStyle == CanvasDashStyle.DashDotDot;

            if (hasDots && DashCap == CanvasCapStyle.Flat)
            {
                ds.DrawText("Dots have zero size when DashCap = CanvasCapStyle.Flat", col1Left, 0, Colors.White);
            }
        }
Example #25
0
 void DriveCanvas_DrawEvent(object sender, CanvasDrawEventArgs args)
 {
     args.DrawingSession.DrawImage(joystickBitmap, joystickDrawRect);
 }
Example #26
0
        private void canvas_Draw(CanvasControl sender, CanvasDrawEventArgs args)
        {
            //var mybitmap = new CanvasRenderTarget(sender, 200, 200);
            //using (var ds=mybitmap.CreateDrawingSession())
            //{
                
            //}

            //only draw if image is loaded
            if (bitmapImg != null)
            {
                bitmapRect = new Rect(0, 0, canvas.ActualWidth, canvas.ActualHeight);
                //args.DrawingSession.DrawImage(bitmapImg, bitmapRect,new Rect(0, 0, 100, 100) );
                //sender.Invalidate();
                args.DrawingSession.DrawImage(bitmapImg);
            }
        }
Example #27
0
        private void OnCanvasDraw(CanvasControl sender, CanvasDrawEventArgs args)
        {
            if (string.IsNullOrWhiteSpace(_data))
            {
                CommandsList.Text = string.Empty;
                return;
            }

            this._errorGeometry ??= CanvasPathGeometry.CreateGeometry(sender, ErrorString);

            _logger?.Clear();
            CommandsList.Text = string.Empty;

            try
            {
                _logger?.AppendLine("// The following commands represent the CanvasPathBuilder command(s) needed");
                _logger?.AppendLine("// to create the CanvasGeometry from the specified Win2d Path Mini Language.");
                var geometry = CanvasPathGeometry.CreateGeometry(sender, _data);
                _reader.StartLogging();
                geometry.SendPathTo(_reader);
                _logger?.AppendLine(_reader.EndLogging());
                CommandsList.Text = _logger?.ToString() ?? string.Empty;

                args.DrawingSession.FillGeometry(geometry, _fillColor);
                args.DrawingSession.DrawGeometry(geometry, _strokeColor, _strokeThickness);
                RootPivot.SelectedIndex = 0;
                CommandsList.Foreground = _commandBrush;
            }
            catch (ArgumentException argEx)
            {
                var message    = argEx.Message;
                var errorCode  = message.Substring(0, 11);
                var parseError = string.Empty;
                if (message.StartsWith(ParseError1))
                {
                    parseError = "Parse Error: No matching data!";
                }
                else if (message.StartsWith(ParseError2))
                {
                    parseError = "Parse Error: Multiple FillRule elements present in Path Data!";
                }
                else if (message.StartsWith(ParseError3))
                {
                    var tokens = message.Split('\n', StringSplitOptions.RemoveEmptyEntries);
                    if (tokens.Length == 3)
                    {
                        parseError = $"Parse Error at {tokens[1]}. Cannot parse '{tokens[2]}'.";
                    }
                }
                else
                {
                    parseError = "Parsing error! Invalid input data!";
                }

                args.DrawingSession.FillGeometry(_errorGeometry, Colors.Black);
                CommandsList.Text       = parseError;
                RootPivot.SelectedIndex = 1;
                CommandsList.Foreground = _commandErrorBrush;
            }
            catch (Exception)
            {
                args.DrawingSession.FillGeometry(_errorGeometry, Colors.Black);
                CommandsList.Text       = "Parsing error! Invalid input data!";
                RootPivot.SelectedIndex = 1;
                CommandsList.Foreground = _commandErrorBrush;
            }
        }
 void DriveCanvas_DrawEvent(object sender, CanvasDrawEventArgs args)
 {
     args.DrawingSession.DrawImage(joystickBitmap, joystickDrawRect);
 }
        void Canvas_Draw(CanvasControl sender, CanvasDrawEventArgs args)
        {
            var ds = args.DrawingSession;

            var centerPoint = (arcPoints[0] + arcPoints[1]) / 2;

            // Draw the end point markers.
            if (!ThumbnailGenerator.IsDrawingThumbnail)
            {
                for (int i = 0; i < 2; i++)
                {
                    ds.DrawCircle(arcPoints[i], hitTestRadius, (i == activeDrag) ? Colors.White : Colors.Gray);
                }
            }

            switch (CurrentOverload)
            {
            case AddArcOverload.AroundEllipse:
                // Compute positions.
                var ellipseRadius = (arcPoints[1] - arcPoints[0]) / 2;

                ellipseRadius.X = Math.Abs(ellipseRadius.X);
                ellipseRadius.Y = Math.Abs(ellipseRadius.Y);

                float startAngle = Utils.DegreesToRadians(ArcStartAngle);
                float sweepAngle = Utils.DegreesToRadians(ArcSweepAngle);

                var startPoint = centerPoint + Vector2.Transform(Vector2.UnitX, Matrix3x2.CreateRotation(startAngle)) * ellipseRadius;

                // Draw the bounding rectangle.
                if (!ThumbnailGenerator.IsDrawingThumbnail)
                {
                    ds.DrawRectangle(new Rect(arcPoints[0].ToPoint(), arcPoints[1].ToPoint()), Color.FromArgb(255, 64, 64, 64));
                }

                // Draw the arc.
                using (var builder = new CanvasPathBuilder(sender))
                {
                    builder.BeginFigure(startPoint);
                    builder.AddArc(centerPoint, ellipseRadius.X, ellipseRadius.Y, startAngle, sweepAngle);
                    builder.EndFigure(CanvasFigureLoop.Open);

                    using (var geometry = CanvasGeometry.CreatePath(builder))
                    {
                        ds.DrawGeometry(geometry, Colors.Yellow, strokeWidth, strokeStyle);
                    }
                }
                break;

            case AddArcOverload.PointToPoint:
                // Display a warning if this is an invalid arc configuration.
                bool isRadiusTooSmall = IsArcRadiusTooSmall();

                if (isRadiusTooSmall)
                {
                    ds.DrawText("Radius is less than the\ndistance between the\nstart and end points", centerPoint, Colors.Red, textFormat);
                }

                // Draw the arc.
                using (var builder = new CanvasPathBuilder(sender))
                {
                    builder.BeginFigure(arcPoints[0]);
                    builder.AddArc(arcPoints[1], ArcRadiusX, ArcRadiusY, Utils.DegreesToRadians(ArcRotation), ArcSweepDirection, ArcSize);
                    builder.EndFigure(CanvasFigureLoop.Open);

                    using (var geometry = CanvasGeometry.CreatePath(builder))
                    {
                        ds.DrawGeometry(geometry, isRadiusTooSmall ? Colors.Red : Colors.Yellow, strokeWidth, strokeStyle);
                    }
                }
                break;
            }
        }
Example #30
0
 // Draw to the CanvasControl.
 void Canvas_Draw(CanvasControl sender, CanvasDrawEventArgs args)
 {
     Draw(args.DrawingSession, "Canvas\nControl", sender.Size);
 }
        private void DrawText(InkRecognitionUnit recoUnit, CanvasControl sender, CanvasDrawEventArgs args)
        {
            var childIds = recoUnit.childIds;
            var initialTransformation = args.DrawingSession.Transform;

            // Points of bounding rectangle to align drawn text
            float floatX = (float)recoUnit.boundingRectangle.topX;
            float floatY = (float)recoUnit.boundingRectangle.topY;

            // Rotated bounding rectangle points to get correct angle of text being drawn
            float topLeftX = (float)recoUnit.rotatedBoundingRectangle[0].x;
            float topLeftY = (float)recoUnit.rotatedBoundingRectangle[0].y;

            float topRightX = (float)recoUnit.rotatedBoundingRectangle[1].x;
            float topRightY = (float)recoUnit.rotatedBoundingRectangle[1].y;

            float bottomRightX = (float)recoUnit.rotatedBoundingRectangle[2].x;
            float bottomRightY = (float)recoUnit.rotatedBoundingRectangle[2].y;

            float bottomLeftX = (float)recoUnit.rotatedBoundingRectangle[3].x;
            float bottomLeftY = (float)recoUnit.rotatedBoundingRectangle[3].y;

            // Height and width of bounding rectangle to get font size and width for text layout
            float height = GetDistanceBetweenPoints(topRightX, bottomRightX, topRightY, bottomRightY) * dipsPerMm;
            float width  = GetDistanceBetweenPoints(bottomLeftX, bottomRightX, bottomLeftY, bottomRightY) * dipsPerMm;

            if (height < 45)
            {
                height = 45;
            }

            // Transform to get correct angle of text
            float centerPointX = ((topLeftX + topRightX) / 2) * dipsPerMm;
            float centerPointY = ((topLeftY + bottomLeftY) / 2) * dipsPerMm;
            var   centerPoint  = new Vector2(centerPointX, centerPointY);

            Matrix3x2 angle = GetRotationAngle(bottomLeftX, bottomRightX, bottomLeftY, bottomRightY, centerPoint);

            args.DrawingSession.Transform = angle;

            var textFormat = new CanvasTextFormat()
            {
                FontSize     = height - 5,
                WordWrapping = CanvasWordWrapping.NoWrap,
                FontFamily   = "Ink Free"
            };

            // Build string to be drawn to canvas
            string textLine = string.Empty;

            foreach (var item in childIds)
            {
                int id = int.Parse(item.ToString());

                // Deconstruct the tuple to get the recognized text from it
                (string text, _) = recoText[id];

                textLine += text + " ";
            }

            var textLayout = new CanvasTextLayout(sender.Device, textLine, textFormat, width, height);

            // Associate correct color with each word in string
            int index = 0;

            foreach (var item in childIds)
            {
                int id = int.Parse(item.ToString());

                // Deconstruct the tuple to get the recognized text and color from it
                (string text, Color color) = recoText[id];

                textLayout.SetColor(index, text.Length, color);

                index += text.Length + 1;
            }

            args.DrawingSession.DrawTextLayout(textLayout, floatX * dipsPerMm, floatY * dipsPerMm, Colors.Black);
            args.DrawingSession.Transform = initialTransformation;
        }
Example #32
0
 //x
 private void OnDraw(CanvasControl sender, CanvasDrawEventArgs args)
 {
     var sz = new Size(ParentWidth, ParentHeight);
     DoEffect(args.DrawingSession, sz, (float)GlowAmount, GlowColor, ((SolidColorBrush)GlowFill).Color, ExpandAmount);
 }
 private void Img_Draw(CanvasControl sender, CanvasDrawEventArgs args)
 {
     args.DrawingSession.FillRectangle(new Rect(new Point(), sender.Size), sender.Tag as CanvasImageBrush);
 }
Example #34
0
 // Draw to the CanvasControl.
 void Canvas_Draw(CanvasControl sender, CanvasDrawEventArgs args)
 {
     Draw(args.DrawingSession, "Canvas\nControl", sender.Size);
 }
Example #35
0
        void canvas_Draw(CanvasControl sender, CanvasDrawEventArgs args)
        {
            // We animate the source image by changing which character is highlighted in yellow.
            // Therefore there can be two changed regions: the highlighted character has changed from
            // white to yellow, while the previous highlight has changed from yellow back to white.

            // Look up the bounds of the two changed characters.
            var highlightBounds = GetCharacterBounds(highlightedCharacter);
            var previousBounds  = GetCharacterBounds(previousHighlight);

            // Tell our effects that the highlighted character region has changed.
            blurEffect.InvalidateSourceRectangle(args.DrawingSession, 0, highlightBounds);
            shadowEffect.InvalidateSourceRectangle(args.DrawingSession, 0, highlightBounds);

            // Query what part of the output image will change as a result.
            var highlightInvalidRects = compositeEffect.GetInvalidRectangles(args.DrawingSession);
            var highlightInvalidUnion = GetRectangleUnion(highlightInvalidRects);

            // Also tell the effects about the previously highlighted character.
            blurEffect.InvalidateSourceRectangle(args.DrawingSession, 0, previousBounds);
            shadowEffect.InvalidateSourceRectangle(args.DrawingSession, 0, previousBounds);

            // Query the output region again. This will return a superset of highlightInvalidRects,
            // as it now accounts for the change to previousBounds as well as highlightBounds.
            var totalInvalidRects = compositeEffect.GetInvalidRectangles(args.DrawingSession);
            var totalInvalidUnion = GetRectangleUnion(totalInvalidRects);

            // We can also look up in the opposite direction: given that we are going to redraw only
            // the totalInvalidUnion area, what portion of each source image is needed to do that?
            // When using filter kernels like blur, this will be larger than just highlightBounds+previousBounds.
            var requiredSourceRects = compositeEffect.GetRequiredSourceRectangles(args.DrawingSession,
                                                                                  totalInvalidUnion,
                                                                                  new ICanvasEffect[] { blurEffect, shadowEffect },
                                                                                  new uint[] { 0, 0 },
                                                                                  new Rect[2] {
                sourceRenderTarget.Bounds, sourceRenderTarget.Bounds
            });

            // How about if we were going to redraw only highlightBounds, skipping previousBounds?
            // (we don't actually do this, but do display what source regions it would require).
            var blurSourceRect   = compositeEffect.GetRequiredSourceRectangle(args.DrawingSession, highlightInvalidUnion, blurEffect, 0, sourceRenderTarget.Bounds);
            var shadowSourceRect = compositeEffect.GetRequiredSourceRectangle(args.DrawingSession, highlightInvalidUnion, shadowEffect, 0, sourceRenderTarget.Bounds);

            // Draw text into the source rendertarget.
            using (var drawingSession = sourceRenderTarget.CreateDrawingSession())
            {
                // To make sure the correct requiredSourceRects were reported, we clear the background outside
                // that region to magenta. If everything is working correctly, this should never be picked up by
                // effect drawing, as we only leave magenta in the areas we don't expect the effects to read from.
                drawingSession.Clear(Colors.Magenta);

                // Clear the requiredSourceRects to transparent.
                drawingSession.Blend = CanvasBlend.Copy;

                foreach (var r in requiredSourceRects)
                {
                    drawingSession.FillRectangle(r, Colors.Transparent);
                }

                // Draw the text characters.
                drawingSession.Blend = CanvasBlend.SourceOver;

                for (int i = 0; i < characterLayouts.Count; i++)
                {
                    var color = (i == highlightedCharacter) ? Colors.Yellow : Colors.White;

                    drawingSession.DrawTextLayout(characterLayouts[i], characterPositions[i], color);
                }
            }

            // Draw the effect graph (which reads from sourceRenderTarget) into destRenderTarget.
            using (var drawingSession = destRenderTarget.CreateDrawingSession())
            {
                // Slightly darken down the existing contents of the output rendertarget. This causes everything
                // except totalInvalidUnion to gradually fade out, so we can see which areas are getting redrawn.
                // If this FillRectangle was removed, the result of redrawing only the changed region would be
                // identical to if we redrew the whole thing every time (by removing the CreateLayer call).
                drawingSession.FillRectangle(destRenderTarget.Bounds, Color.FromArgb(16, 0, 0, 0));

                // Clip our drawing to the totalInvalidUnion rectangle,
                // which should be the only part of the output that has changed.
                using (var layer = drawingSession.CreateLayer(1, totalInvalidUnion))
                {
                    drawingSession.Clear(Colors.CornflowerBlue);
                    drawingSession.DrawImage(compositeEffect, totalInvalidUnion, totalInvalidUnion);
                }
            }

            if (!ThumbnailGenerator.IsDrawingThumbnail)
            {
                args.DrawingSession.Transform = Matrix3x2.CreateTranslation(gap, gap);

                // Display sourceRenderTarget.
                args.DrawingSession.DrawImage(sourceRenderTarget);

                // Display highlightBounds, blurSourceRect, and shadowSourceRect.
                args.DrawingSession.DrawRectangle(highlightBounds, Colors.Gray);
                args.DrawingSession.DrawRectangle(blurSourceRect, Colors.Blue);
                args.DrawingSession.DrawRectangle(shadowSourceRect, Colors.Blue);
            }

            args.DrawingSession.Transform = Matrix3x2.CreateTranslation(gap, gap * 2 + height);

            // Display destRenderTarget.
            args.DrawingSession.DrawImage(destRenderTarget);

            // Display highlightInvalidRects.
            foreach (var i in highlightInvalidRects)
            {
                args.DrawingSession.DrawRectangle(i, Colors.DarkBlue);
            }

            previousHighlight = highlightedCharacter;

            // When generating thumbnails, repeat the first draw a bunch of times to reach a more interesting image.
            if (ThumbnailGenerator.IsDrawingThumbnail && highlightedCharacter < characterLayouts.Count * 5 / 6)
            {
                highlightedCharacter++;
                canvas_Draw(sender, args);
            }
        }
Example #36
0
        private void Canvas_Draw(CanvasControl sender, CanvasDrawEventArgs args)
        {
            strokeStyle.StartCap  = StartCap;
            strokeStyle.EndCap    = EndCap;
            strokeStyle.DashStyle = DashStyle;
            strokeStyle.DashCap   = DashCap;
            strokeStyle.LineJoin  = LineJoin;

            var ds = args.DrawingSession;

            var width  = (float)sender.ActualWidth;
            var height = (float)sender.ActualHeight;

            var col1Left  = width * 0.1f;
            var col1Right = width * 0.4f;
            var col2Left  = width * 0.6f;
            var col2Right = width * 0.9f;

            var row1Top    = height * 0.1f;
            var row1Bottom = height * 0.4f;
            var row2Top    = height * 0.6f;
            var row2Bottom = height * 0.9f;

            //
            // Draw hairlines showing the start/end points of the line.
            // This helps demonstrate the behavior of start/end cap.
            //
            ds.DrawLine(
                col1Left,
                row1Top,
                col1Left,
                row1Bottom,
                Colors.Aqua,
                1.0f,
                this.hairlineStrokeStyle);

            ds.DrawLine(
                col1Right,
                row1Top,
                col1Right,
                row1Bottom,
                Colors.Aqua,
                1.0f,
                this.hairlineStrokeStyle);

            //
            // Draw the demo shapes with the chosen stroke style
            //
            var strokeWidth = (float)Math.Max(5, Math.Min(30, width / 50));

            ds.DrawLine(
                col1Left,
                (row1Top + row1Bottom) / 2,
                col1Right,
                (row1Top + row1Bottom) / 2,
                Colors.Green,
                strokeWidth,
                this.strokeStyle);

            ds.DrawRectangle(
                new Rect(new Point(col2Left, row1Top), new Point(col2Right, row1Bottom)),
                Colors.Green,
                strokeWidth,
                this.strokeStyle);

            ds.DrawRoundedRectangle(
                new Rect(new Point(col1Left, row2Top), new Point(col1Right, row2Bottom)),
                width * 0.1f,
                height * 0.1f,
                Colors.Green,
                strokeWidth,
                this.strokeStyle);

            ds.DrawEllipse(
                (col2Left + col2Right) / 2,
                (row2Top + row2Bottom) / 2,
                (col2Right - col2Left) / 2,
                (row2Bottom - row2Top) / 2,
                Colors.Green,
                strokeWidth,
                this.strokeStyle);

            //
            // Explain what is going on if this combination of properties leaves dots invisible
            //
            bool hasDots = DashStyle == CanvasDashStyle.Dot ||
                           DashStyle == CanvasDashStyle.DashDot ||
                           DashStyle == CanvasDashStyle.DashDotDot;

            if (hasDots && DashCap == CanvasCapStyle.Flat)
            {
                ds.DrawText("Dots have zero size when DashCap = CanvasCapStyle.Flat", col1Left, 0, Colors.White);
            }
        }
        private void CanvasControl_Draw(CanvasControl sender, CanvasDrawEventArgs args)
        {
            var drawingSession = args.DrawingSession;

            drawingSession.DrawImage(_effect);
        }
Example #38
0
        public void Render(CanvasDrawEventArgs args, long delta)
        {
            Rect bounds    = ApplicationView.GetForCurrentView().VisibleBounds;
            Rect imgBounds = Grid.Bounds;

            // Calculate scale
            float     ratio = GetRatio(bounds, imgBounds);
            Matrix3x2 scale = Matrix3x2.CreateScale(ratio, ratio);

            // Draw TicTacToe Grid
            Transform2DEffect Img = new Transform2DEffect()
            {
                Source = Grid
            };

            Img.TransformMatrix = scale;

            Vector2 startPoint = GetStartPoint(bounds, imgBounds, ratio);

            args.DrawingSession.DrawImage(Img, startPoint);

            // Draw State
            for (byte i = 0; i < 3; i++)
            {
                for (byte j = 0; j < 3; j++)
                {
                    Vector2 location = startPoint + new Vector2(i * ratio * 166, j * ratio * 166);

                    if (Game[i, j] % 2 == 0)
                    {
                        Transform2DEffect ImgX = new Transform2DEffect()
                        {
                            Source = X
                        };
                        ImgX.TransformMatrix = scale;

                        args.DrawingSession.DrawImage(ImgX, location);
                    }
                    else if (Game[i, j] % 2 == 1)
                    {
                        Transform2DEffect ImgO = new Transform2DEffect()
                        {
                            Source = O
                        };
                        ImgO.TransformMatrix = scale;

                        args.DrawingSession.DrawImage(ImgO, location);
                    }
                }
            }

            // Display Game result
            if (State != Result.Game)
            {
                // Display PAUSE TEXT
                args.DrawingSession.FillRectangle((float)bounds.Width / 2 - 300, (float)bounds.Height / 2 - 75, 600, 150, Color.FromArgb(255, 255, 0, 0));

                CanvasTextFormat format = new CanvasTextFormat()
                {
                    FontSize = 92
                };
                args.DrawingSession.DrawText("GAME OVER", (float)bounds.Width / 2 - 250, (float)bounds.Height / 2 - 65, Color.FromArgb(255, 0, 0, 0), format);
            }
        }
Example #39
0
        public void Update(GameState gameState, CanvasDrawEventArgs args)
        {
            var(playerX, playerY, xPlus, yPlus) = zoomer.Update(gameState);

            var scale = (float)zoomer.GetTimes();

            // walls
            foreach (var segment in gameState.PerimeterSegments)
            {
                var width = 1_000_000;

                var xOffset = 0f;

                if (segment.Start.y > segment.End.y)
                {
                    xOffset = -width / 2f;
                }
                else if (segment.Start.y < segment.End.y)
                {
                    xOffset = width / 2f;
                }

                var yOffset = 0f;

                if (segment.Start.x > segment.End.x)
                {
                    yOffset = width / 2f;
                }
                else if (segment.Start.x < segment.End.x)
                {
                    yOffset = -width / 2f;
                }


                DrawLine(
                    segment.Start.x + xOffset,
                    segment.Start.y + yOffset,
                    segment.End.x + xOffset,
                    segment.End.y + yOffset,
                    Color.FromArgb(0x11, 0x00, 0x00, 0x00),
                    width,
                    CanvasCapStyle.Square);
            }

            // goals
            DrawFilledCircle(
                gameState.LeftGoal.Posistion.x, gameState.LeftGoal.Posistion.y, Constants.goalLen, Color.FromArgb(0xff, 0xff, 0xff, 0xff));
            DrawFilledCircle(
                gameState.RightGoal.Posistion.x, gameState.RightGoal.Posistion.y, Constants.goalLen, Color.FromArgb(0xff, 0xff, 0xff, 0xff));


            // has ball highlight
            DrawCircle(gameState.GameBall.Posistion.x, gameState.GameBall.Posistion.y, Constants.BallRadius,
                       Color.FromArgb((byte)((gameState.CountDownState.Countdown ? gameState.CountDownState.BallOpacity : 1) * 0xff), 0xff, 0xff, 0xff), 35 / scale);


            // players bodies
            foreach (var playerPair in gameState.players)
            {
                DrawFilledCircle(playerPair.Value.PlayerBody.Position.x, playerPair.Value.PlayerBody.Position.y, Constants.playerCenterRadius, Color.FromArgb(0xff, playerPair.Value.PlayerBody.R, playerPair.Value.PlayerBody.G, playerPair.Value.PlayerBody.B));
                //DrawFilledCircle(playerPair.Value.PlayerBody.Position.x, playerPair.Value.PlayerBody.Position.y, Constants.footLen, Color.FromArgb(playerPair.Value.PlayerBody.A, playerPair.Value.PlayerBody.R, playerPair.Value.PlayerBody.G, playerPair.Value.PlayerBody.B));
            }


            // draw number of boosts
            foreach (var playerPair in gameState.players)
            {
                if (playerPair.Value.Boosts > 0)
                {
                    DrawCircle(playerPair.Value.PlayerFoot.Position.x, playerPair.Value.PlayerFoot.Position.y,
                               Constants.PlayerRadius + (playerPair.Value.Boosts * 2.0 / scale) + (2 / scale),
                               Color.FromArgb(0x22, playerPair.Value.PlayerFoot.R, playerPair.Value.PlayerFoot.G, playerPair.Value.PlayerFoot.B),
                               (float)(playerPair.Value.Boosts * 4.0 / scale));
                }
            }

            // players feet
            foreach (var playerPair in gameState.players)
            {
                DrawFilledCircle(playerPair.Value.PlayerFoot.Position.x, playerPair.Value.PlayerFoot.Position.y, Constants.PlayerRadius, Color.FromArgb(playerPair.Value.PlayerFoot.A, playerPair.Value.PlayerFoot.R, playerPair.Value.PlayerFoot.G, playerPair.Value.PlayerFoot.B));

                //if (playerPair.Value.BoostVelocity.Length > 10)
                //{
                //    var boostV = playerPair.Value.BoostVelocity;//.NewAdded(playerPair.Value.PlayerBody.Velocity).NewAdded(playerPair.Value.PlayerFoot.Velocity).NewAdded(playerPair.Value.ExternalVelocity).NewAdded(playerPair.Value.BoostVelocity);
                //    DrawLine(
                //        playerPair.Value.PlayerFoot.Position.x,
                //        playerPair.Value.PlayerFoot.Position.y,
                //        playerPair.Value.PlayerFoot.Position.x + (boostV.x * 15),
                //        playerPair.Value.PlayerFoot.Position.y + (boostV.y * 15),
                //        Color.FromArgb(0x20, playerPair.Value.PlayerFoot.R, playerPair.Value.PlayerFoot.G, playerPair.Value.PlayerFoot.B),
                //        Constants.PlayerRadius * 2);
                //}

                //var vel = playerPair.Value.PlayerBody.Velocity;//.NewAdded(playerPair.Value.PlayerBody.Velocity).NewAdded(playerPair.Value.PlayerFoot.Velocity).NewAdded(playerPair.Value.ExternalVelocity).NewAdded(playerPair.Value.BoostVelocity);
                //DrawLine(
                //    playerPair.Value.PlayerFoot.Position.x,
                //    playerPair.Value.PlayerFoot.Position.y,
                //    playerPair.Value.PlayerFoot.Position.x + (vel.x * 15),
                //    playerPair.Value.PlayerFoot.Position.y + (vel.y * 15),
                //    Color.FromArgb(0x20, playerPair.Value.PlayerFoot.R, playerPair.Value.PlayerFoot.G, playerPair.Value.PlayerFoot.B),
                //    Constants.PlayerRadius );
            }

            // ball
            DrawFilledCircle(gameState.GameBall.Posistion.x, gameState.GameBall.Posistion.y, Constants.BallRadius, Color.FromArgb(
                                 (byte)((gameState.CountDownState.Countdown ? gameState.CountDownState.BallOpacity : 1) * 0xff)
                                 , 0x00, 0x00, 0x00));

            // ball wall
            if (gameState.CountDownState.Countdown)
            {
                DrawCircle(gameState.CountDownState.X, gameState.CountDownState.Y, gameState.CountDownState.Radius - (gameState.CountDownState.StrokeThickness / 2.0),
                           Color.FromArgb((byte)((1 - gameState.CountDownState.BallOpacity) * 0xff), 0x88, 0x88, 0x88), (float)gameState.CountDownState.StrokeThickness);
            }

            // score
            leftScore.Text  = gameState.RightScore + "";
            rightScore.Text = gameState.LeftScore + "";

            // goals scored
            foreach (var goalScored in gameState.GoalsScored.Except(goalScoreds))
            {
                //Task.Run(() =>
                //{
                //    bell.Volume = 3;
                //    bell.AudioBalance = goalScored.LeftScored ? 0 : 1;
                //    bell.Play();
                //});
                goalScoreds.Add(goalScored);
            }

            var goalAnimationLength = 120.0;

            goalScoreds = goalScoreds.Where(x => gameState.Frame - x.Frame < goalAnimationLength).ToList();
            foreach (var goalSocred in goalScoreds)
            {
                DrawLine(
                    goalSocred.Posistion.x + (goalSocred.Surface.x * 1000 * (gameState.Frame - goalSocred.Frame)),
                    goalSocred.Posistion.y + (goalSocred.Surface.y * 1000 * (gameState.Frame - goalSocred.Frame)),
                    goalSocred.Posistion.x - (goalSocred.Surface.x * 1000 * (gameState.Frame - goalSocred.Frame)),
                    goalSocred.Posistion.y - (goalSocred.Surface.y * 1000 * (gameState.Frame - goalSocred.Frame)),
                    Color.FromArgb((byte)(1.0 - (((gameState.Frame - goalSocred.Frame) / goalAnimationLength)) * 0xff), 0x00, 0x00, 0x00), 1 / scale,
                    CanvasCapStyle.Round);
            }

            // collisions
            foreach (var collision in gameState.collisions.Except(collisions))
            {
                if (collision.Force.Length > 100)
                {
                    //    Task.Run(() =>
                    //{
                    //var item = collisionSounds.First.Value;
                    //collisionSounds.RemoveFirst();
                    //collisionSounds.AddLast(item);

                    //    item.Volume = (collision.Force.Length * collision.Force.Length / 100.0);
                    //    item.AudioBalance = collision.Position.x / FieldDimensions.Default.xMax;
                    //    item.Play();
                    //});
                }
                collisions.Add(collision);
            }

            var timeDenom = 100.0;

            collisions = collisions.Where(x => gameState.Frame - x.Frame < x.Force.Length / timeDenom).Take(10).ToList();
            foreach (var collision in collisions)
            {
                DrawLine(
                    collision.Position.x + ((collision.Force.y + (collision.Force.x / 10.0)) * .5 * (gameState.Frame - collision.Frame)),
                    collision.Position.y - ((collision.Force.x + (collision.Force.y / 10.0)) * .5 * (gameState.Frame - collision.Frame)),
                    collision.Position.x + ((collision.Force.y + (collision.Force.x / 10.0)) * 1 * (gameState.Frame - collision.Frame)),
                    collision.Position.y - ((collision.Force.x + (collision.Force.y / 10.0)) * 1 * (gameState.Frame - collision.Frame)),
                    Color.FromArgb((byte)(1.0 - (((gameState.Frame - collision.Frame) / (collision.Force.Length / timeDenom))) * 0xff), 0x00, 0x00, 0x00), 1 / scale,
                    CanvasCapStyle.Round);

                DrawLine(
                    collision.Position.x - ((collision.Force.y + (collision.Force.x / 10.0)) * .5 * (gameState.Frame - collision.Frame)),
                    collision.Position.y + ((collision.Force.x + (collision.Force.y / 10.0)) * .5 * (gameState.Frame - collision.Frame)),
                    collision.Position.x - ((collision.Force.y + (collision.Force.x / 10.0)) * 1 * (gameState.Frame - collision.Frame)),
                    collision.Position.y + ((collision.Force.x + (collision.Force.y / 10.0)) * 1 * (gameState.Frame - collision.Frame)),
                    Color.FromArgb((byte)(1.0 - (((gameState.Frame - collision.Frame) / (collision.Force.Length / timeDenom))) * 0xff), 0x00, 0x00, 0x00), 1 / scale,
                    CanvasCapStyle.Round);

                DrawLine(
                    collision.Position.x + ((collision.Force.y - (collision.Force.x / 10.0)) * .5 * (gameState.Frame - collision.Frame)),
                    collision.Position.y - ((collision.Force.x - (collision.Force.y / 10.0)) * .5 * (gameState.Frame - collision.Frame)),
                    collision.Position.x + ((collision.Force.y - (collision.Force.x / 10.0)) * 1 * (gameState.Frame - collision.Frame)),
                    collision.Position.y - ((collision.Force.x - (collision.Force.y / 10.0)) * 1 * (gameState.Frame - collision.Frame)),
                    Color.FromArgb((byte)(1.0 - (((gameState.Frame - collision.Frame) / (collision.Force.Length / timeDenom))) * 0xff), 0x00, 0x00, 0x00), 1 / scale,
                    CanvasCapStyle.Round);

                DrawLine(
                    collision.Position.x - ((collision.Force.y - (collision.Force.x / 10.0)) * .5 * (gameState.Frame - collision.Frame)),
                    collision.Position.y + ((collision.Force.x - (collision.Force.y / 10.0)) * .5 * (gameState.Frame - collision.Frame)),
                    collision.Position.x - ((collision.Force.y - (collision.Force.x / 10.0)) * 1 * (gameState.Frame - collision.Frame)),
                    collision.Position.y + ((collision.Force.x - (collision.Force.y / 10.0)) * 1 * (gameState.Frame - collision.Frame)),
                    Color.FromArgb((byte)(1.0 - (((gameState.Frame - collision.Frame) / (collision.Force.Length / timeDenom))) * 0xff), 0x00, 0x00, 0x00), 1 / scale,
                    CanvasCapStyle.Round);
            }

            foreach (var collision in gameState.debugs.Where(x => gameState.Frame - x.Frame < 180))
            {
                DrawCircle(collision.Target.x, collision.Target.y, Constants.BallRadius, Colors.Black, 1 / scale);
            }

            // draw throw preview
            foreach (var playerPair in gameState.players)
            {
                //if (gameState.GameBall.OwnerOrNull == playerPair.Key)
                //{
                var toThrow = playerPair.Value.ProposedThrow;//.NewAdded(playerPair.Value.PlayerBody.Velocity).NewAdded(playerPair.Value.PlayerFoot.Velocity).NewAdded(playerPair.Value.ExternalVelocity).NewAdded(playerPair.Value.BoostVelocity);
                DrawLine(
                    playerPair.Value.PlayerFoot.Position.x,
                    playerPair.Value.PlayerFoot.Position.y,
                    playerPair.Value.PlayerFoot.Position.x + (toThrow.x * 30),
                    playerPair.Value.PlayerFoot.Position.y + (toThrow.y * 30),
                    Color.FromArgb(0xff, playerPair.Value.PlayerFoot.R, playerPair.Value.PlayerFoot.G, playerPair.Value.PlayerFoot.B),
                    1 / scale,
                    CanvasCapStyle.Round);
                //}
            }

            void DrawFilledCircle(double x, double y, double rad, Color color)
            {
                args.DrawingSession.FillCircle(
                    (float)((x * scale) + xPlus), (float)((y * scale) + yPlus), (float)(rad * scale), color);
            }

            void DrawCircle(double x, double y, double rad, Color color, float strokeWidth)
            {
                args.DrawingSession.DrawCircle(
                    (float)((x * scale) + xPlus), (float)((y * scale) + yPlus), (float)(rad * scale), color, strokeWidth * scale);
            }

            void DrawLine(double x1, double y1, double x2, double y2, Color color, float strokeWidth, CanvasCapStyle capStyle)
            {
                args.DrawingSession.DrawLine(
                    new Vector2((float)((x1 * scale) + xPlus), (float)((y1 * scale) + yPlus)),
                    new Vector2((float)((x2 * scale) + xPlus), (float)((y2 * scale) + yPlus)),
                    color,
                    strokeWidth * scale,
                    new CanvasStrokeStyle
                {
                    EndCap = capStyle
                });
            }
        }
Example #40
0
        /// <summary>
        ///     Draw the canvas and its contents
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="args"></param>
        void CanvasControl_Draw(CanvasControl sender, CanvasDrawEventArgs args)
        {
            // Get Screen Size/Bounds
            var bounds      = ApplicationView.GetForCurrentView().VisibleBounds;
            var scaleFactor = DisplayInformation.GetForCurrentView().RawPixelsPerViewPixel;
            var size        = new Size(bounds.Width * scaleFactor, bounds.Height * scaleFactor);

            //Calculate Canvase Size
            double width  = size.Width - 200;
            double height = size.Height - 180;

            //Calculate Seperator
            double scale = 7;

            _Space     = height / scale;
            _PixelSize = height / (scale * 1000);

            //Set Text Properties
            CanvasTextFormat textFormat = new CanvasTextFormat();

            textFormat.FontSize = 14;

            CanvasTextFormat textFormatFat = new CanvasTextFormat();

            textFormatFat.FontSize   = 16;
            textFormatFat.FontWeight = Windows.UI.Text.FontWeights.Medium;

            //Set Canvas Size
            GridCanvas.Width  = width;
            GridCanvas.Height = height;

            //Draw Grid
            for (int i = (int)_Space; i < width; i += (int)_Space)
            {
                args.DrawingSession.DrawLine(i, 0, i, (int)height, Colors.LightGray);
                args.DrawingSession.DrawText((Math.Round(i / _Space) - 1).ToString(), i + 3, 0, Colors.LightGray, textFormat);
            }

            for (int i = (int)_Space; i < height; i += (int)_Space)
            {
                args.DrawingSession.DrawLine(0, i, (int)width, i, Colors.LightGray);
                args.DrawingSession.DrawText((Math.Round(i / _Space) - 1).ToString(), 0, i + 3, Colors.LightGray, textFormat);
            }


            //Draw Anchors
            foreach (Anchor anchor in _Pozyx.Anchors)
            {
                args.DrawingSession.DrawEllipse((float)(anchor.X * _PixelSize + _Space), (float)(anchor.Y * _PixelSize + _Space), 5, 5, Colors.Blue);
                args.DrawingSession.FillCircle((float)(anchor.X * _PixelSize + _Space), (float)(anchor.Y * _PixelSize + _Space), 5, Colors.Blue);
                args.DrawingSession.DrawText("ID: 0X" + anchor.Id.ToString("X4"), (float)(anchor.X * _PixelSize + _Space), (float)(anchor.Y * _PixelSize + _Space + 2), Colors.SlateGray, textFormatFat);
                args.DrawingSession.DrawText(anchor.X + "," + anchor.Y + "," + anchor.Z, (float)(anchor.X * _PixelSize + _Space), (float)(anchor.Y * _PixelSize + _Space + 20), Colors.DarkGray, textFormat);
            }

            // Draw table big
            args.DrawingSession.DrawRectangle((float)(1980 * _PixelSize + _Space), (float)(2000 * _PixelSize + _Space), (float)(3600 * _PixelSize), (float)(1200 * _PixelSize), Colors.Cyan, 5);

            // Draw table circle
            // args.DrawingSession.DrawEllipse((float)(2030 * pixelSize + space), (float)(2310 * pixelSize + space), (float)(600 * pixelSize), (float)(600 * pixelSize), Colors.Cyan, 5);

            // Draw Test Path
            //args.DrawingSession.DrawRectangle((float)(1170 * _PixelSize + _Space), (float)(1220 * _PixelSize + _Space), (float)(5000 * _PixelSize), (float)(2500 * _PixelSize), Colors.BlanchedAlmond, 29);

            // Draw line
            for (int i = 0; i < _LinePoints.Count - 1; i++)
            {
                args.DrawingSession.DrawLine(_LinePoints[i][0], _LinePoints[i][1], _LinePoints[i + 1][0], _LinePoints[i + 1][1], Windows.UI.Colors.Green);
            }

            // Draw line friend
            for (int i = 0; i < _FriendLine.Count - 1; i++)
            {
                args.DrawingSession.DrawLine(_FriendLine[i][0], _FriendLine[i][1], _FriendLine[i + 1][0], _FriendLine[i + 1][1], Windows.UI.Colors.Purple);
            }

            if (_LinePoints.Count >= 1)
            {
                // Draw Tag
                args.DrawingSession.FillCircle(_LinePoints.Last()[0], _LinePoints.Last()[1], 5, Colors.Green);
            }

            if (_FriendLine.Count >= 1)
            {
                // Draw friend
                args.DrawingSession.FillCircle(_FriendLine.Last()[0], _FriendLine.Last()[1], 5, Colors.Purple);
            }
        }
 private void CanvasControl_OnDraw(CanvasControl sender, CanvasDrawEventArgs args)
 {
     _chartRenderer.RenderData(chartCanvas, args, statusColor, DataStrokeThickness, _data, false, _max);
 }
Example #42
0
        private void Canvas_Draw(CanvasControl sender, CanvasDrawEventArgs args)
        {
            if (ItemTemplate == null)
            {
                return;
            }
            if (ItemsSource == null)
            {
                return;
            }

            /*
             * var items = ItemsSource.Select(o => {
             *  var item = ItemTemplate.LoadContent() as LineChartItem;
             *  item.DataContext = o;
             *  return item;
             * }).ToList();
             */
            List <LineChartItem> items = new List <LineChartItem>();

            foreach (LineChartItem item in ItemsSource)
            {
                items.Add(item);
            }

            if (!items.Any())
            {
                return;
            }

            var availableWidth  = (float)_canvas.ActualWidth;
            var availableHeight = (float)_canvas.ActualHeight;
            var fill            = Fill ?? new SolidColorBrush(DefaultColors.GetRandom());
            var elementWidth    = availableWidth / (items.Count - 1);
            var radius          = (float)(Thickness * 2);

            var min  = items.Min(i => i.Value);
            var max  = items.Max(i => i.Value);
            var diff = max - min;
            var d    = diff * 0.01;

            #region Add X captions
            _xCap.Children.Clear();
            _xCap.Children.Add(new TextBlock {
                Text = "Test",//items.First().Key.ToString(),
                HorizontalAlignment = HorizontalAlignment.Left,
                VerticalAlignment   = VerticalAlignment.Stretch
            });
            _xCap.Children.Add(new TextBlock {
                Text = "Test", //items.Last().Key.ToString(),
                HorizontalAlignment = HorizontalAlignment.Right,
                VerticalAlignment   = VerticalAlignment.Stretch
            });
            #endregion

            #region Add Y captions
            _yCap.Children.Clear();
            if (YAxis == YMode.FromMin)
            {
                _yCap.Children.Add(new TextBlock {
                    Text = min.ToString(),
                    HorizontalAlignment = HorizontalAlignment.Stretch,
                    VerticalAlignment   = VerticalAlignment.Bottom
                });
            }
            else
            {
                _yCap.Children.Add(new TextBlock {
                    Text = "0",
                    HorizontalAlignment = HorizontalAlignment.Stretch,
                    VerticalAlignment   = VerticalAlignment.Bottom
                });
                _yCap.Children.Add(new TextBlock {
                    Text = min.ToString(),
                    HorizontalAlignment = HorizontalAlignment.Stretch,
                    VerticalAlignment   = VerticalAlignment.Bottom,
                    Margin = new Thickness(0, 0, 0, -10 + min * availableHeight / max)
                });
            }
            _yCap.Children.Add(new TextBlock {
                Text = max.ToString(),
                HorizontalAlignment = HorizontalAlignment.Stretch,
                VerticalAlignment   = VerticalAlignment.Top,
            });
            #endregion

            // Draw lines
            using (var builder = new CanvasPathBuilder(sender)) {
                for (var i = 0; i < items.Count; i++)
                {
                    var item = items[i];
                    var x    = i * elementWidth;
                    var y    = availableHeight -
                               (YAxis == YMode.FromMin
                            ? (float)((item.Value - min) * availableHeight / diff)
                            : (float)(item.Value * availableHeight / max));
                    // Fixes for edge points
                    if (max - item.Value < d)
                    {
                        y += radius;
                    }
                    if (item.Value - min < d)
                    {
                        y -= radius;
                    }
                    // Main drawing
                    if (i == 0)
                    {
                        builder.BeginFigure(x, y);
                    }
                    else
                    {
                        builder.AddLine(x, y);
                    }
                }
                builder.EndFigure(CanvasFigureLoop.Open);
                using (var geometry = CanvasGeometry.CreatePath(builder))
                    args.DrawingSession.DrawGeometry(geometry, fill.Color, (float)Thickness);
                // Draw axis
                var color = ForegroundColor;
                args.DrawingSession.DrawLine(0, 0, 0, availableHeight, Colors.Black, 1);
                args.DrawingSession.DrawLine(0, availableHeight, availableWidth, availableHeight, Colors.Black, 1);
            }
        }
Example #43
0
        private void Canvas_Draw(CanvasControl sender, CanvasDrawEventArgs args)
        {
            if (testBitmaps == null)
                return;

            var ds = args.DrawingSession;

            float senderSize = Math.Min((float)sender.Size.Width, (float)sender.Size.Height);
            float marginSize = senderSize / 50.0f;

            // There are 11 cells, so divide the target into a 4x3 grid (with one empty cell).
            float cellWidthInclMargin = (float)sender.Size.Width / 4.0f;
            float cellWidth = cellWidthInclMargin - marginSize;

            float cellHeightInclMargin = (float)sender.Size.Height / 3.0f;
            float cellHeight = cellHeightInclMargin - marginSize;

            const int cellsPerRow = 4;
            for (int cellY = 0; cellY < 3; ++cellY)
            {
                for (int cellX = 0; cellX < cellsPerRow; ++cellX)
                {
                    int bitmapIndex = (cellsPerRow * cellY) + cellX;
                    Rect cellRect = new Rect(cellX * cellWidthInclMargin, cellY * cellHeightInclMargin, cellWidth, cellHeight);
                    if (bitmapIndex < testBitmaps.Length)
                    {
                        var image = testBitmaps[bitmapIndex];

                        var bitmap = image as CanvasBitmap;

                        if (bitmap != null)
                        {
                            ds.DrawImage(bitmap, cellRect);
                        }
#if WINDOWS_UWP
                        else
                        {
                            var virtualBitmap = image as CanvasVirtualBitmap;
                            ds.DrawImage(virtualBitmap, cellRect, virtualBitmap.Bounds);
                        }
#endif
                    }
                    else
                    {
                        // X out the cell, just to show it's not glitched out or anything.
                        ds.DrawLine((float)cellRect.Left, (float)cellRect.Top, (float)cellRect.Right, (float)cellRect.Bottom, Colors.White);
                        ds.DrawLine((float)cellRect.Right, (float)cellRect.Top, (float)cellRect.Left, (float)cellRect.Bottom, Colors.White);
                    }
                }
            }
        }
Example #44
0
 void canvasControl_Draw(CanvasControl sender, CanvasDrawEventArgs args)
 {
     args.DrawingSession.DrawEllipse(155, 115, 80, 30, Colors.Black, 3);
     args.DrawingSession.DrawText("Hello, world!", 100, 100, Colors.Yellow);
 }
Example #45
0
 /// <summary>
 /// 
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="args"></param>
 private void CanvasControl_Draw(CanvasControl sender, CanvasDrawEventArgs args)
 {
     Draw(args.DrawingSession);
 }
 private void Canvas12_Draw(CanvasControl sender, CanvasDrawEventArgs args)
 {
     DrawCanvasState(sender, args.DrawingSession, ++drawCount12);
 }
        private void Canvas_Draw(CanvasControl sender, CanvasDrawEventArgs args)
        {
            var ds = args.DrawingSession;

            foreach (var link in Links)
            {
                var centerPoint = (link.Node1.Position + link.Node2.Position) / 2;

                //if (Math.Abs(link.Node1.PositionX - link.Node2.PositionX) > Math.Abs(link.Node1.PositionY - link.Node2.PositionY))
                //{
                //    ds.DrawText(link.Weight.ToString(), centerPoint.X, centerPoint.Y - 10, foregroundColor);
                //}

                ds.DrawEllipse((float)Canvas.ActualWidth / 2, (float)Canvas.ActualHeight / 2, 500, 500, foregroundColor);

                using (var builder = new CanvasPathBuilder(sender))
                {
                    builder.BeginFigure(link.Node1.Position);
                    builder.AddArc(link.Node2.Position, arcRadiusX, arcRadiusY, 0, CanvasSweepDirection.Clockwise, CanvasArcSize.Small);
                    builder.EndFigure(CanvasFigureLoop.Open);

                    using (var geometry = CanvasGeometry.CreatePath(builder))
                    {
                        ds.DrawGeometry(geometry, foregroundColor, strokeWidth);
                    }
                }
            }

            foreach (var node in Nodes)
            {
                DrawNode(ds, node);
            }
        }
 private void OnDraw(CanvasControl sender, CanvasDrawEventArgs args)
 {
     var currentShape = this.availableShapes.FirstOrDefault(s => s.Key == ShapeType);
     if(args.DrawingSession == null)
         currentShape = this.DefaultShape;
     currentShape.Value.Invoke(sender, args.DrawingSession);
 }
Example #49
0
        private void Canvas_Draw(CanvasControl sender, CanvasDrawEventArgs args)
        {
            EnsureLayout(sender);

            if (ShowLayoutRectangles)
            {
                foreach (var layoutRectangle in layoutRectangles)
                {
                    args.DrawingSession.DrawRectangle(layoutRectangle, Colors.Gray);
                }
            }

            if (ShowSelectionBox)
            {
                args.DrawingSession.DrawRectangle(layoutBox, Colors.LightGray, 2.0f, dashedStroke);
            }

            var brush = new CanvasSolidColorBrush(sender, Colors.LightSkyBlue);

            foreach (LayoutBox l in layoutBoxes)
            {
                if (l.GlyphRuns.Count > 0)
                {
                    float layoutAdvance = 0;
                    foreach (var g in l.GlyphRuns)
                    {
                        layoutAdvance += g.GetAdvance();
                    }

                    float x = (float)l.Rectangle.Left;


                    if (CurrentTextDirection == TextDirection.RightToLeft)
                    {
                        x = (float)l.Rectangle.Right - layoutAdvance;
                    }

                    int[] bidiOrdering = l.ProduceBidiOrdering();

                    foreach (int glyphRunIndex in bidiOrdering)
                    {
                        GlyphRun g = l.GlyphRuns[glyphRunIndex];

                        //
                        // The Arabic test string contains control characters. A typical text renderer will just not draw these.
                        //
                        if (g.FormattingSpan.Script.Shape == CanvasScriptShape.NoVisual)
                        {
                            continue;
                        }

                        if (g.Glyphs.Count > 0)
                        {
                            float advance = g.GetAdvance();

                            Vector2 position;
                            position.X = x;
                            position.Y = (float)l.Rectangle.Bottom;

                            if (g.FormattingSpan.BidiLevel % 2 != 0)
                            {
                                position.X += advance;
                            }

                            args.DrawingSession.DrawGlyphRun(
                                position,
                                g.FormattingSpan.FontFace,
                                g.FormattingSpan.FontSize,
                                g.Glyphs.ToArray(),
                                false, // isSideways
                                g.FormattingSpan.BidiLevel,
                                brush);

                            x += advance;
                        }
                    }
                }
            }
        }
        void Canvas_Draw(CanvasControl sender, CanvasDrawEventArgs args)
        {
            using (var session = args.DrawingSession)
            {
                var blur = new GaussianBlurEffect
                {
                    BlurAmount = 50.0f, // increase this to make it more blurry or vise versa.
                    //Optimization = EffectOptimization.Balanced, // default value
                    //BorderMode = EffectBorderMode.Soft // default value
                    Source = _bitmap
                };

                session.DrawImage(blur, new Rect(0, 0, sender.ActualWidth, sender.ActualHeight),
                    new Rect(0, 0, _bitmap.SizeInPixels.Width, _bitmap.SizeInPixels.Height), 0.9f);
            }
        }
 private void CanvasMinus_Draw(CanvasControl sender, CanvasDrawEventArgs args)
 {
     DrawHorizontalLine(sender, args);
     DrawBorder(sender, args);
 }
Example #52
0
        private void Canvas_Draw(CanvasControl sender, CanvasDrawEventArgs args)
        {
            EnsureResources(sender, sender.Size);

            float strokeWidth = CurrentTextLengthOption == TextLengthOption.Paragraph ? 2.0f : 15.0f;

            args.DrawingSession.DrawGeometry(textGeometry, Colors.White, strokeWidth, dashedStroke);

            if (ShowNonOutlineText)
            {
                Color semitrans = Colors.CornflowerBlue;
                semitrans.A = 127;
                args.DrawingSession.DrawTextLayout(textLayout, 0, 0, semitrans);
            }
        }
Example #53
0
        private void DrawCanvas_Draw(CanvasControl sender, CanvasDrawEventArgs args)
        {
            if (_isFirstCall)
            {
                _isFirstCall = false; PanZoomReset();
            }

            if (sender == EditCanvas)
            {
                Draw(DrawModel.BackData);
                Draw(DrawModel.EditData);
                if (SelectorGrid.Visibility == Visibility.Visible)
                {
                    UpdateSelectorGrid();
                }
            }
            else if (sender == OverCanvas)
            {
                Draw(DrawModel.EditData);
            }
            else if (sender == Pick1Canvas)
            {
                Draw(DrawModel.Picker1Data);
            }
            else if (sender == Pick2Canvas)
            {
                Draw(DrawModel.Picker2Data);
            }

            void Draw(IDrawData data)
            {
                if (data is null)
                {
                    return;
                }

                var(scale, offset) = CanvasScaleOffset[sender];
                var ds = args.DrawingSession;

                foreach (var(P, (K, S, W), (A, R, G, B)) in data.Parms)
                {
                    var isFilled = S == StrokeType.Filled;
                    var V        = W * scale;
                    if (V < 1)
                    {
                        V = 1;
                    }
                    if (K < ShapeType.SimpleShapeMask)
                    {
                        var color  = Color.FromArgb(A, R, G, B);
                        var stroke = StrokeStyle(S);
                        switch (K)
                        {
                        case ShapeType.Line:
                            for (int i = 0; i < P.Length; i += 2)
                            {
                                var a = P[i] * scale + offset;
                                var b = P[i + 1] * scale + offset;
                                ds.DrawLine(a, b, color, V, stroke);
                            }
                            break;

                        case ShapeType.Circle:
                            if (isFilled)
                            {
                                for (int i = 0; i < P.Length; i += 2)
                                {
                                    var a = P[i] * scale + offset;
                                    var b = P[i + 1] * scale;
                                    ds.FillCircle(a, b.X, color);
                                }
                            }
                            else
                            {
                                for (int i = 0; i < P.Length; i += 2)
                                {
                                    var a = P[i] * scale + offset;
                                    var b = P[i + 1] * scale;
                                    ds.DrawCircle(a, b.X, color, V, stroke);
                                }
                            }
                            break;

                        case ShapeType.Ellipse:
                            if (isFilled)
                            {
                                for (int i = 0; i < P.Length; i += 2)
                                {
                                    var a = P[i] * scale + offset;
                                    var b = P[i + 1] * scale;
                                    ds.FillEllipse(a, b.X, b.Y, color);
                                }
                            }
                            else
                            {
                                for (int i = 0; i < P.Length; i += 2)
                                {
                                    var a = P[i] * scale + offset;
                                    var b = P[i + 1] * scale;
                                    ds.DrawEllipse(a, b.X, b.Y, color, V, stroke);
                                }
                            }
                            break;

                        case ShapeType.EqualRect:
                            var d = P[0] * scale;
                            if (isFilled)
                            {
                                for (int i = 1; i < P.Length; i++)
                                {
                                    var a = P[i] * scale + offset;
                                    ds.FillRectangle(a.X, a.Y, d.X, d.Y, color);
                                }
                            }
                            else
                            {
                                for (int i = 1; i < P.Length; i++)
                                {
                                    var a = P[i] * scale + offset;
                                    ds.DrawRectangle(a.X, a.Y, d.X, d.Y, color, V, stroke);
                                }
                            }
                            break;

                        case ShapeType.CornerRect:
                            if (isFilled)
                            {
                                for (int i = 0; i < P.Length; i += 2)
                                {
                                    var a = P[i] * scale + offset;
                                    var b = P[i + 1] * scale;
                                    ds.FillRectangle(a.X, a.Y, b.X, b.Y, color);
                                }
                            }
                            else
                            {
                                for (int i = 0; i < P.Length; i += 2)
                                {
                                    var a = P[i] * scale + offset;
                                    var b = P[i + 1] * scale;
                                    ds.DrawRectangle(a.X, a.Y, b.X, b.Y, color, V, stroke);
                                }
                            }
                            break;

                        case ShapeType.CenterRect:
                            if (isFilled)
                            {
                                for (int i = 0; i < P.Length; i += 2)
                                {
                                    var a = P[i] * scale + offset;
                                    var b = P[i + 1] * scale;
                                    var e = a - b;
                                    var f = 2 * b;
                                    ds.FillRectangle(e.X, e.Y, f.X, f.Y, color);
                                }
                            }
                            else
                            {
                                for (int i = 0; i < P.Length; i += 2)
                                {
                                    var a = P[i] * scale + offset;
                                    var b = P[i + 1] * scale;
                                    var e = a - b;
                                    var f = 2 * b;
                                    ds.DrawRectangle(e.X, e.Y, f.X, f.Y, color, V, stroke);
                                }
                            }
                            break;

                        case ShapeType.RoundedRect:
                            var r = 8 * scale;
                            if (isFilled)
                            {
                                for (int i = 0; i < P.Length; i += 2)
                                {
                                    var a = P[i] * scale + offset;
                                    var b = P[i + 1] * scale;
                                    var e = a - b;
                                    var f = 2 * b;
                                    ds.FillRoundedRectangle(e.X, e.Y, f.X, f.Y, r, r, color);
                                }
                            }
                            else
                            {
                                for (int i = 0; i < P.Length; i += 2)
                                {
                                    var a = P[i] * scale + offset;
                                    var b = P[i + 1] * scale;
                                    var e = a - b;
                                    var f = 2 * b;
                                    ds.DrawRoundedRectangle(e.X, e.Y, f.X, f.Y, r, r, color, V, stroke);
                                }
                            }
                            break;

                        case ShapeType.Pin2:
                        {
                            var b = 2 * scale;
                            if (isFilled)
                            {
                                for (int i = 0; i < P.Length; i++)
                                {
                                    var a = P[i] * scale + offset;
                                    ds.FillCircle(a, b, color);
                                    ds.DrawCircle(a, b + V, Colors.Black, V, stroke);
                                }
                            }
                            else
                            {
                                for (int i = 0; i < P.Length; i++)
                                {
                                    var a = P[i] * scale + offset;
                                    ds.DrawCircle(a, b - V, Colors.Black, V, stroke);
                                    ds.DrawCircle(a, b, color, V, stroke);
                                    ds.DrawCircle(a, b + V, Colors.Black, V, stroke);
                                }
                            }
                        }
                        break;

                        case ShapeType.Pin4:
                        {
                            var b = 4 * scale;
                            if (isFilled)
                            {
                                for (int i = 0; i < P.Length; i++)
                                {
                                    var a = P[i] * scale + offset;
                                    ds.FillCircle(a, b, color);
                                    ds.DrawCircle(a, b + V, Colors.Black, V, stroke);
                                }
                            }
                            else
                            {
                                for (int i = 0; i < P.Length; i++)
                                {
                                    var a = P[i] * scale + offset;
                                    ds.DrawCircle(a, b - V, Colors.Black, V, stroke);
                                    ds.DrawCircle(a, b, color, V, stroke);
                                    ds.DrawCircle(a, b + V, Colors.Black, V, stroke);
                                }
                            }
                        }
                        break;

                        case ShapeType.Grip2:
                        {
                            var e = 2 * scale;
                            var f = 2 * e;
                            if (isFilled)
                            {
                                for (int i = 0; i < P.Length; i++)
                                {
                                    var a = P[i] * scale + offset;
                                    ds.FillRectangle(a.X - e, a.Y - e, f, f, color);
                                }
                            }
                            else
                            {
                                for (int i = 0; i < P.Length; i += 2)
                                {
                                    var a = P[i] * scale + offset;
                                    ds.DrawRectangle(a.X - e, a.Y - e, f, f, color, V, stroke);
                                }
                            }
                        }
                        break;

                        case ShapeType.Grip4:
                        {
                            var e = 4 * scale;
                            var f = 2 * e;
                            if (isFilled)
                            {
                                for (int i = 0; i < P.Length; i++)
                                {
                                    var a = P[i] * scale + offset;
                                    ds.FillRectangle(a.X - e, a.Y - e, f, f, color);
                                }
                            }
                            else
                            {
                                for (int i = 0; i < P.Length; i += 2)
                                {
                                    var a = P[i] * scale + offset;
                                    ds.DrawRectangle(a.X - e, a.Y - e, f, f, color, V, stroke);
                                }
                            }
                        }
                        break;
                        }
                    }
                    else
                    {
                        using (var pb = new CanvasPathBuilder(ds))
                        {
                            pb.BeginFigure(P[0] * scale + offset);
                            if ((K & ShapeType.JointedLines) != 0 || (K & ShapeType.ClosedLines) != 0)
                            {
                                for (int i = 1; i < P.Length; i++)
                                {
                                    pb.AddLine(P[i] * scale + offset);
                                }
                            }
                            else
                            {
                                var N = P.Length;
                                for (var i = 0; i < N - 2;)
                                {
                                    pb.AddCubicBezier(P[i] * scale + offset, P[++i] * scale + offset, P[++i] * scale + offset);
                                }
                            }
                            if ((K & ShapeType.ClosedLines) != 0)
                            {
                                pb.EndFigure(CanvasFigureLoop.Closed);
                            }
                            else
                            {
                                pb.EndFigure(CanvasFigureLoop.Open);
                            }

                            using (var geo = CanvasGeometry.CreatePath(pb))
                            {
                                if (isFilled)
                                {
                                    ds.FillGeometry(geo, Color.FromArgb(A, R, G, B));
                                }
                                else
                                {
                                    ds.DrawGeometry(geo, Color.FromArgb(A, R, G, B), V, StrokeStyle(S));
                                }
                            }
                        }
                    }
                }

                foreach (var((P, T), (A, R, G, B)) in data.Text)
                {
                    var p = P * scale + offset;
                    ds.DrawText(T, p, Color.FromArgb(A, R, G, B));
                }
            }
        }
Example #54
0
        private void Canvas_Draw(CanvasControl sender, CanvasDrawEventArgs args)
        {
            var size = sender.Size;
            var ds = args.DrawingSession;

            // Animate and then display the current image effect.
            animationFunction((float)timer.Elapsed.TotalSeconds);

            ds.DrawImage(effect, (size.ToVector2() - currentEffectSize) / 2);

            // Draw text showing which effects are in use, but only if the screen is large enough to fit it.
            const float minSizeToShowText = 500;

            if ((size.Width + size.Height) / 2 > minSizeToShowText && !ThumbnailGenerator.IsDrawingThumbnail)
            {
                string text = activeEffectNames;

                if (textLabel != null)
                {
                    text += "\n\n" + textLabel;
                }

                ds.DrawText(text, 0, 80, Colors.White, textFormat);
            }

            sender.Invalidate();
        }
Example #55
0
        private void Ground_Draw(CanvasControl sender, CanvasDrawEventArgs args)
        {
            args.DrawingSession.DrawImage(bitmapOrb, xPos, yPos);

            ground.Invalidate();
        }
Example #56
0
        private void canvasControl_Draw(CanvasControl sender, CanvasDrawEventArgs args)
        {
            if (needToCreateSizeDependentResources)
            {
                CreateSizeDependentResources();
            }

            if (needToRedrawInkSurface)
            {
                ClearInkSurface();
                DrawStrokeCollectionToInkSurface(inkManager.GetStrokes());

                needToRedrawInkSurface = false;
            }

            DrawBackgroundText(args.DrawingSession);

            if (pendingDry != null && deferredDryDelay == 0)
            {
                // Incremental draw only.
                DrawStrokeCollectionToInkSurface(pendingDry);

                // Register to call EndDry on the next-but-one draw,
                // by which time our dry ink will be visible.
                deferredDryDelay = 1;
                CompositionTarget.Rendering += DeferredEndDry;
            }

            args.DrawingSession.DrawImage(renderTarget);

            DrawForegroundText(args.DrawingSession);
            DrawSelectionBoundingRect(args.DrawingSession);
            DrawSelectionLasso(sender, args.DrawingSession);
        }
Example #57
0
        private void Canvas_Draw(CanvasControl sender, CanvasDrawEventArgs args)
        {
            if (ItemTemplate == null)
            {
                return;
            }
            if (ItemsSource == null)
            {
                return;
            }
            var items = ItemsSource.Cast <LineChartItem>().ToList();

            if (!items.Any())
            {
                return;
            }

            var availableWidth  = (float)_canvas.ActualWidth;
            var availableHeight = (float)_canvas.ActualHeight;
            var fill            = Fill ?? new SolidColorBrush(DefaultColors.GetRandom());
            var elementWidth    = (availableWidth - (Thickness * 2)) / (items.Count - 1);
            var radius          = (float)(Thickness * 2);

            var min  = items.Min(i => i.Value);
            var max  = items.Max(i => i.Value);
            var diff = max - min;
            var d    = diff * 0.01;

            #region Add X captions
            _xCap.Children.Clear();
            _xCap.Children.Add(new TextBlock {
                //  Text = items.First().Key.ToString(),
                HorizontalAlignment = HorizontalAlignment.Left,
                VerticalAlignment   = VerticalAlignment.Stretch
            });
            _xCap.Children.Add(new TextBlock {
                //  Text = items.Last().Key.ToString(),
                HorizontalAlignment = HorizontalAlignment.Right,
                VerticalAlignment   = VerticalAlignment.Stretch
            });
            #endregion

            /*
             #region Add Y captions
             * _yCap.Children.Clear();
             * if (YAxis == YMode.FromMin) {
             *  _yCap.Children.Add(new TextBlock {
             *      Text = min.ToString(),
             *      HorizontalAlignment = HorizontalAlignment.Stretch,
             *      VerticalAlignment = VerticalAlignment.Bottom
             *  });
             * }
             * else {
             *  _yCap.Children.Add(new TextBlock {
             *      Text = "0",
             *      HorizontalAlignment = HorizontalAlignment.Stretch,
             *      VerticalAlignment = VerticalAlignment.Bottom
             *  });
             *  _yCap.Children.Add(new TextBlock {
             *      Text = min.ToString(),
             *      HorizontalAlignment = HorizontalAlignment.Stretch,
             *      VerticalAlignment = VerticalAlignment.Bottom,
             *      Margin = new Thickness(0, 0, 0, -10 + min * availableHeight / max)
             *  });
             * }
             * _yCap.Children.Add(new TextBlock {
             *  Text = max.ToString(),
             *  HorizontalAlignment = HorizontalAlignment.Stretch,
             *  VerticalAlignment = VerticalAlignment.Top,
             * });
             #endregion
             *
             */
            IList <Vector2> array         = new List <Vector2>();
            IList <Vector2> controlPoints = new List <Vector2>();

            for (var i = 0; i < items.Count; i++)
            {
                var item = items[i];
                var x    = (float)(i * (elementWidth) + Thickness);
                var y    = availableHeight -
                           (YAxis == YMode.FromMin
                            ? (float)((item.Value - min) * availableHeight / diff)
                            : (float)(item.Value * availableHeight / max));
                // Fixes for edge points
                if (max - item.Value < d)
                {
                    y += radius;
                }
                if (item.Value - min < d)
                {
                    y -= radius;
                }

                array.Add(new Vector2(x, y));
            }

            for (int i = 1; i < array.Count - 1; i++)
            {
                Vector2[] controlPoint2 = CalculateControlPoints(array[i - 1], array[i], array[i + 1]);
                controlPoints.Add(controlPoint2[0]);
                controlPoints.Add(controlPoint2[1]);
            }

            // Fill area
            using (var fillBuilder = new CanvasPathBuilder(sender)) {
                // Draw lines
                using (var drawBuilder = new CanvasPathBuilder(sender)) {
                    for (int i = 0; i < array.Count; i++)
                    {
                        if (i == 0)
                        {
                            drawBuilder.BeginFigure(array[i]);
                            fillBuilder.BeginFigure(array[i]);
                        }
                        else if (i == 1 && array.Count == 2)
                        {
                            drawBuilder.AddCubicBezier(array[0], array[1], array[1]);
                            fillBuilder.AddCubicBezier(array[0], array[1], array[1]);
                        }
                        else if (i == 1 && array.Count > 2)
                        {
                            drawBuilder.AddCubicBezier(array[0], controlPoints[0], array[1]);
                            fillBuilder.AddCubicBezier(array[0], controlPoints[0], array[1]);
                        }
                        else if (i < array.Count - 1)
                        {
                            drawBuilder.AddCubicBezier(controlPoints[i * 2 - 3], controlPoints[i * 2 - 2], array[i]);
                            fillBuilder.AddCubicBezier(controlPoints[i * 2 - 3], controlPoints[i * 2 - 2], array[i]);
                        }
                        else if (array.Count > 1)
                        {
                            drawBuilder.AddCubicBezier(controlPoints[i * 2 - 3], array[i], array[i]);
                            fillBuilder.AddCubicBezier(controlPoints[i * 2 - 3], array[i], array[i]);
                        }
                    }

                    drawBuilder.EndFigure(CanvasFigureLoop.Open);
                    using (var geometry = CanvasGeometry.CreatePath(drawBuilder)) {
                        CanvasStrokeStyle strokeStyle = new CanvasStrokeStyle {
                            EndCap   = CanvasCapStyle.Round,
                            StartCap = CanvasCapStyle.Round
                        };

                        Color startColor  = fill.Color;
                        Color startColor2 = fill.Color;
                        startColor2.A = 150;

                        CanvasLinearGradientBrush ee = new CanvasLinearGradientBrush(_canvas, startColor, startColor2)
                        {
                            StartPoint = new Vector2(0, 0),
                            EndPoint   = new Vector2(0, availableHeight)
                        };

                        args.DrawingSession.DrawGeometry(geometry, ee, (float)Thickness, strokeStyle);
                    }

                    fillBuilder.AddLine(array.Last().X, availableHeight);
                    fillBuilder.AddLine(array[0].X, availableHeight);
                    fillBuilder.EndFigure(CanvasFigureLoop.Closed);
                    using (var geometry = CanvasGeometry.CreatePath(fillBuilder)) {
                        Color startColor = fill.Color;
                        startColor.A = 50;

                        CanvasLinearGradientBrush ee = new CanvasLinearGradientBrush(_canvas, startColor, Colors.Transparent)
                        {
                            StartPoint = new Vector2(0, 0),
                            EndPoint   = new Vector2(0, availableHeight)
                        };
                        args.DrawingSession.FillGeometry(geometry, ee);
                    }
                }
            }


            args.DrawingSession.DrawLine(
                0,
                availableHeight,
                availableWidth,
                availableHeight + 16,
                Color.FromArgb(35, 255, 255, 255), 0.5f);

            // Draw axis
            Color color = ((SolidColorBrush)Foreground).Color;
            color.A = 40;

            CanvasStrokeStyle strokeStyle2 = new CanvasStrokeStyle {
                CustomDashStyle = new float[] { 2, 4 },
            };

            var part = (availableHeight - 2 * radius) / 3;

            for (int i = 0; i < 4; i++)
            {
                var yPos = radius + i * part;
                args.DrawingSession.DrawLine(0, yPos, availableWidth, yPos, color, 1, strokeStyle2);
            }
        }
Example #58
0
 private void canvas_Draw(CanvasControl sender, CanvasDrawEventArgs args)
 {
     //only draw if image is loaded
     if (bitmapImg != null)
     {
         args.DrawingSession.DrawImage(bitmapImg, bitmapRect);
         sender.Invalidate();
     }
 }
Example #59
0
        private void Canvas_Draw(CanvasControl sender, CanvasDrawEventArgs args)
        {
            EnsureResources(sender, sender.Size);

            currentDrawingSession = args.DrawingSession;

            textLayout.SetBrush(0, testString.Length, null);
            if (hasSelection)
            {
                int firstIndex = Math.Min(selectionStartIndex, selectionEndIndex);
                int length = Math.Abs(selectionEndIndex - selectionStartIndex) + 1;
                CanvasTextLayoutRegion[] descriptions = textLayout.GetCharacterRegions(firstIndex, length);
                foreach (CanvasTextLayoutRegion description in descriptions)
                {
                    args.DrawingSession.FillRectangle(InflateRect(description.LayoutBounds), Colors.White);
                }
                textLayout.SetBrush(firstIndex, length, selectionTextBrush);
            }

            EnsureInlineObjects();

            args.DrawingSession.DrawTextLayout(textLayout, 0, 0, textBrush);

            if (ShowPerCharacterLayoutBounds)
            {
                for (int i = 0; i < testString.Length; i++)
                {
                    CanvasTextLayoutRegion textLayoutRegion;
                    textLayout.GetCaretPosition(i, false, out textLayoutRegion);

                    args.DrawingSession.DrawRectangle(textLayoutRegion.LayoutBounds, Colors.Blue, 2);
                }
            }

            if (ShowDrawBounds)
            {
                args.DrawingSession.DrawRectangle(textLayout.DrawBounds, Colors.Green, 2);
            }

            if (ShowLayoutBounds)
            {
                args.DrawingSession.DrawRectangle(textLayout.LayoutBounds, Colors.Red, 2, dashedStroke);
            }

        }