protected void canvasControl_Draw(CanvasControl sender, CanvasDrawEventArgs args)
        {
            if (Points.Count > 0)
            {
                var ds = args.DrawingSession;
                ds.Transform = Matrix3x2.CreateRotation((float)(this.Rotation * Math.PI / 180f), PolyLineCenter);

                CanvasPathBuilder pathBuilder = new CanvasPathBuilder(sender);
                pathBuilder.BeginFigure((float)Points[0].X, (float)Points[0].Y);

                for (int i = 1; i < Points.Count; i++)
                {
                    pathBuilder.AddLine((float)Points[i].X, (float)Points[i].Y);
                }

                pathBuilder.EndFigure(CanvasFigureLoop.Open);

                CanvasGeometry canvasGeometry = CanvasGeometry.CreatePath(pathBuilder);

                CanvasCommandList cl = new CanvasCommandList(sender);
                using (CanvasDrawingSession clds = cl.CreateDrawingSession())
                {
                    ds.DrawGeometry(canvasGeometry, PolyLineColor, PolyLineStrokeWidth);
                }

                GaussianBlurEffect blur = new GaussianBlurEffect();
                blur.Source     = cl;
                blur.BlurAmount = PolyLineStrokeWidth;
                args.DrawingSession.DrawImage(blur);
            }
        }
Exemplo n.º 2
0
        void DrawShadow(CanvasControl canvasCtrl, CanvasDrawingSession drawSession, List <ShadowParam> shadowParams)
        {
            var    canvasCommandList = new CanvasCommandList(canvasCtrl);
            var    content           = _contentPresenter.Content as FrameworkElement;
            var    contentWidth      = content.ActualWidth + content.Margin.Left + content.Margin.Right;
            var    contentHeight     = content.ActualHeight + content.Margin.Top + content.Margin.Bottom;
            var    radius            = GetActualCornerRadius(contentWidth);
            double maxOffset_Y       = shadowParams.Max(param => param.Offset_Y);

            _shadowCanvas.VerticalAlignment   = content.VerticalAlignment;
            _shadowCanvas.HorizontalAlignment = content.HorizontalAlignment;

            using (var ds = canvasCommandList.CreateDrawingSession())
            {
                ds.FillRoundedRectangle(new Rect(0, 0, contentWidth, contentHeight), radius, radius, Color.FromArgb(255, 0, 0, 0));
            }

            CompositeEffect compositeEffect = CreateEffects(shadowParams, canvasCommandList);

            var    bound        = compositeEffect.GetBounds(drawSession);
            double shadowWidth  = Math.Abs(bound.X);
            double shadowHeight = Math.Abs(bound.Y);

            UpdateLayout(maxOffset_Y, bound, shadowWidth, shadowHeight);

            DrawEffect(drawSession, compositeEffect, shadowWidth, shadowHeight);
        }
Exemplo n.º 3
0
        public async Task Save(StorageFile file)
        {
            var image = GetImage();

            // Measure the extent of the image (which may be cropped).
            Rect imageBounds;

            using (var commandList = new CanvasCommandList(sourceBitmap.Device))
            using (var drawingSession = commandList.CreateDrawingSession())
            {
                imageBounds = image.GetBounds(drawingSession);
            }

            // Rasterize the image into a rendertarget.
            using (var renderTarget = new CanvasRenderTarget(sourceBitmap.Device, (float)imageBounds.Width, (float)imageBounds.Height, 96))
            {
                using (var drawingSession = renderTarget.CreateDrawingSession())
                {
                    drawingSession.Blend = CanvasBlend.Copy;

                    drawingSession.DrawImage(image, -(float)imageBounds.X, -(float)imageBounds.Y);
                }

                // Save it out.
                var format = file.FileType.Equals(".png", StringComparison.OrdinalIgnoreCase) ? CanvasBitmapFileFormat.Png : CanvasBitmapFileFormat.Jpeg;

                using (var stream = await file.OpenAsync(FileAccessMode.ReadWrite))
                {
                    stream.Size = 0;

                    await renderTarget.SaveAsync(stream, format);
                }
            }
        }
Exemplo n.º 4
0
        /// <summary>
        /// Renders text into an intermediate bitmap and sets this bitmap as the input to the flame
        /// effect graph. The effect graph must already be created before calling this method.
        /// </summary>
        private void SetupText()
        {
            textCommandList = new CanvasCommandList(this.canvas);

            using (var ds = textCommandList.CreateDrawingSession())
            {
                ds.Clear(Color.FromArgb(0, 0, 0, 0));

                ds.DrawText(
                    text,
                    0,
                    0,
                    Colors.White,
                    new CanvasTextFormat
                {
                    FontFamily         = "Segoe UI",
                    FontSize           = fontSize,
                    ParagraphAlignment = Windows.UI.Text.ParagraphAlignment.Center,
                    VerticalAlignment  = CanvasVerticalAlignment.Top
                });
            }

            // Hook up the bitmap to the inputs of the flame effect graph.
            morphology.Source   = textCommandList;
            composite.Inputs[1] = textCommandList;
        }
Exemplo n.º 5
0
        public void PaintSet(ICanvasResourceCreator rc, CanvasBitmap cb, float R, Color co)
        {
            //Paint:绘画
            Paint = new CanvasCommandList(rc);

            using (CanvasDrawingSession ds = Paint.CreateDrawingSession())
            {
                ds.FillEllipse(0, 0, R, R, PaintBrush(rc, R, PaintHard, PaintOpacity, co));

                ICanvasImage ci = new ScaleEffect
                {
                    Source = cb,
                    Scale  = new Vector2(2 * R / cb.SizeInPixels.Width)
                };
                ds.DrawImage(ci, -R, -R, ci.GetBounds(rc), 1, CanvasImageInterpolation.HighQualityCubic, CanvasComposite.DestinationIn);
            }



            //Show:展示
            var radius = (float)Math.Sqrt(R);

            PaintShow = new CanvasCommandList(rc);

            using (CanvasDrawingSession ds = PaintShow.CreateDrawingSession())
            {
                ds.FillEllipse(0, 0, radius, radius, PaintBrush(rc, radius, PaintHard, PaintOpacity, Colors.White));
                ICanvasImage ci = new ScaleEffect
                {
                    Source = cb,
                    Scale  = new Vector2(2 * radius / cb.SizeInPixels.Width)
                };
                ds.DrawImage(ci, -radius, -radius, ci.GetBounds(rc), 1, CanvasImageInterpolation.HighQualityCubic, CanvasComposite.DestinationIn);
            }
        }
        protected ICanvasBrush GetBackgroundBrush(ICanvasAnimatedControl sender, CanvasAnimatedDrawEventArgs args, string item, TimeSpan ellapsed)
        {
            var commands = new CanvasCommandList(sender);
            var b        = TransformBounds(Bounds);

            using (var session = commands.CreateDrawingSession())
            {
                session.Clear(Color.FromArgb(255, 255, 255, 255));
                session.DrawLine((float)b.X, (float)b.Y, (float)b.X + (float)b.Width, (float)b.Y + (float)b.Height, Colors.Black);
                session.DrawLine((float)b.X, (float)b.Y + (float)b.Height, (float)b.X + (float)b.Width, (float)b.Y, Colors.Black);
                session.DrawText(item, TransformBounds(Bounds), Color.FromArgb(155, 63, 63, 63), new CanvasTextFormat()
                {
                    HorizontalAlignment = CanvasHorizontalAlignment.Center,
                    VerticalAlignment   = CanvasVerticalAlignment.Center,
                    FontSize            = 30f
                });
            }

            var brush = new CanvasImageBrush(sender, commands);

            brush.SourceRectangle = b;
            brush.Transform       = Matrix3x2.CreateTranslation((float)b.X, (float)b.Y);


            return(brush);
        }
Exemplo n.º 7
0
        // This is the Draw method used by the CanvasControl. The CanvasControl gives us the ability
        // to quickly draw images, other shapes and text.
        void canvasControl_Draw(CanvasControl sender, CanvasDrawEventArgs args)
        {
            CanvasCommandList cl = new CanvasCommandList(sender);

            using (CanvasDrawingSession clds = cl.CreateDrawingSession())
            {
                for (int i = 0; i < 100; i++)
                {
                    for (int x = 0; x < field.field.GetLength(0); x++)
                    {
                        for (int y = 0; y < field.field.GetLength(1); y++)
                        {
                            clds.Antialiasing = CanvasAntialiasing.Antialiased;
                            clds.FillRectangle(x * (0 + 75), y * (0 + 75), 70, 70, RndColor());
                        }
                    }
                }
            }
            args.DrawingSession.DrawImage(cl);

            if (Enemies.Count < 2)
            {
                Enemies.Add(new Enemy(rnd.Next(0, 6)));
                Enemies.Add(new Enemy(rnd.Next(0, 6)));
            }

            for (int i = 0; i < Enemies.Count; i++)
            {
                Enemies[i].Draw(args, enemyBitmap);
                if (Enemies[i].column > 600)
                {
                    Enemies.RemoveAt(i);
                }
            }
        }
Exemplo n.º 8
0
        private CanvasCommandList GenerateTextDisplay(ICanvasResourceCreator resourceCreator, float width, float height)
        {
            var cl = new CanvasCommandList(resourceCreator);

            using (var ds = cl.CreateDrawingSession())
            {
                float top = height - offset;

                float center    = width / 4.0f;
                float symbolPos = center - 5.0f;
                float labelPos  = center + 5.0f;

                for (int i = firstLine; i < lastLine; ++i)
                {
                    float y     = top + lineHeight * i;
                    int   index = i;

                    if (index < characters.Length)
                    {
                        ds.DrawText(string.Format("{0}", (char)characters[index].Code), symbolPos, y, Colors.White, symbolText);
                        ds.DrawText(string.Format("0x{0:X} - {1}", characters[index].Code, characters[index].Label), labelPos, y, Colors.White, labelText);
                    }
                }
            }

            return(cl);
        }
Exemplo n.º 9
0
        public static void Invert()
        {
            //Undo:撤销
            Undo undo = new Undo();

            undo.MaskInstantiation(App.Model.MaskRenderTarget, App.Model.MaskAnimatedTarget);
            App.UndoAdd(undo);

            CanvasCommandList vcl = new CanvasCommandList(App.Model.VirtualControl);

            using (var ds = vcl.CreateDrawingSession())
            {
                ds.Clear(Colors.White);
            }

            CanvasCommandList acl = new CanvasCommandList(App.Model.AnimatedControl);

            using (var ds = acl.CreateDrawingSession())
            {
                ds.Clear(Colors.White);
            }
            App.Mask(vcl, acl, 4);//反选


            //重新设置描边
            App.Model.isReStroke = true;
            App.Model.isAnimated = true;

            if (App.Model.isMask == true)
            {
                App.Model.isReRender = true; //重新渲染
                App.Model.Refresh++;         //画布刷新
            }
        }
Exemplo n.º 10
0
        // TODO: Create a ShadowEffect : Effect that can be used as a parameter to add a shadow
        // to other draw functions.
        public void FillEllipseShadow(
            Rectangle rectangle,
            Color color,
            float shadowBlur = 8.0f)
        {
            rectangle = rectangle.Inflate(-2 * shadowBlur, -2 * shadowBlur);

            var   centerPoint = rectangle.Center;
            float radiusX     = rectangle.Width / 2;
            float radiusY     = rectangle.Height / 2f;
            var   winColor    = global::Windows.UI.Color.FromArgb(color.A, color.R, color.G, color.B);

            CanvasCommandList commandList = new CanvasCommandList(GraphicsManager.Shared.GetCanvasDevice());

            using (var drawingSession = commandList.CreateDrawingSession())
            {
                drawingSession.FillEllipse(centerPoint.X, centerPoint.Y, radiusX, radiusY, winColor);
                //this._session.FillEllipse(centerPoint.X, centerPoint.Y, radiusX, radiusY, winColor);
            };

            GaussianBlurEffect effect = new GaussianBlurEffect()
            {
                Source     = commandList,
                BlurAmount = shadowBlur,
            };

            //var sourceRect = new global::Windows.Foundation.Rect(rectangle.X, rectangle.Y, rectangle.Width, rectangle.Height);
            //var destinationRect = new global::Windows.Foundation.Rect(rectangle.X, rectangle.Y, rectangle.Width, rectangle.Height);

            this._session.DrawImage(effect); //, destinationRect, sourceRect);
            //this._session.DrawRectangle(destinationRect, winColor);
        }
Exemplo n.º 11
0
        public CanvasCommandList GetCanvasImage(ICanvasResourceCreator resourceCreator, float scaleX, float scaleY)
        {
            lock (this)
            {
                var commandList = new CanvasCommandList(resourceCreator);
                using (var session = commandList.CreateDrawingSession())
                {
                    var width  = _composition.Bounds.Width * scaleX;
                    var height = _composition.Bounds.Height * scaleY;
                    if (_bitmapCanvas == null || _bitmapCanvas.Width < width || _bitmapCanvas.Height < height)
                    {
                        _bitmapCanvas?.Dispose();
                        _bitmapCanvas = new BitmapCanvas(width, height);
                    }

                    using (_bitmapCanvas.CreateSession(resourceCreator.Device, (float)width,
                                                       (float)height, session))
                    {
                        _bitmapCanvas.Clear(Colors.Transparent);
                        LottieLog.BeginSection("Drawable.Draw");
                        if (_compositionLayer == null)
                        {
                            return(null);
                        }

                        _matrix.Reset();
                        _matrix = MatrixExt.PreScale(_matrix, scaleX, scaleY);
                        _compositionLayer.Draw(_bitmapCanvas, _matrix, _alpha);
                        LottieLog.EndSection("Drawable.Draw");
                    }
                }

                return(commandList);
            }
        }
Exemplo n.º 12
0
        public void UpdateMask()
        {
            var start = _canvas.Size.ToVector2() * _canvas.Center.ToVector2();
            var end   = new Vector2(start.X > _canvas.Size.Width - start.X ? 0.0f : (float)_canvas.Size.Width,
                                    start.Y > _canvas.Size.Height - start.Y ? 0.0f : (float)_canvas.Size.Height);

            var radius = (end - start).Length();

            var commandList = new CanvasCommandList(_canvas);

            using (var drawingSession = commandList.CreateDrawingSession())
            {
                using (var brush = new CanvasRadialGradientBrush(_canvas, Colors.White, Colors.Black)
                {
                    Center = start,
                    RadiusX = radius,
                    RadiusY = radius
                })
                    drawingSession.FillRectangle(new Rect(new Point(0, 0), _canvas.Size), brush);
            }


            _dissolveEffect.Source2 = new Transform2DEffect
            {
                Source = commandList
            };
        }
Exemplo n.º 13
0
        public async Task Save(StorageFile file)
        {
            var image = GetImage();

            // Measure the extent of the image (which may be cropped).
            Rect imageBounds;

            using (var commandList = new CanvasCommandList(sourceBitmap.Device))
                using (var drawingSession = commandList.CreateDrawingSession())
                {
                    imageBounds = image.GetBounds(drawingSession);
                }

            // Rasterize the image into a rendertarget.
            using (var renderTarget = new CanvasRenderTarget(sourceBitmap.Device, (float)imageBounds.Width, (float)imageBounds.Height, 96))
            {
                using (var drawingSession = renderTarget.CreateDrawingSession())
                {
                    drawingSession.Blend = CanvasBlend.Copy;

                    drawingSession.DrawImage(image, -(float)imageBounds.X, -(float)imageBounds.Y);
                }

                // Save it out.
                var format = file.FileType.Equals(".png", StringComparison.OrdinalIgnoreCase) ? CanvasBitmapFileFormat.Png : CanvasBitmapFileFormat.Jpeg;

                using (var stream = await file.OpenAsync(FileAccessMode.ReadWrite))
                {
                    stream.Size = 0;

                    await renderTarget.SaveAsync(stream, format);
                }
            }
        }
Exemplo n.º 14
0
        /// <summary>
        /// Renders text into a command list and sets this as the input to the flame
        /// effect graph. The effect graph must already be created before calling this method.
        /// </summary>
        private void SetupText(ICanvasResourceCreator resourceCreator)
        {
            textCommandList = new CanvasCommandList(resourceCreator);

            using (var ds = textCommandList.CreateDrawingSession())
            {
                ds.Clear(Color.FromArgb(0, 0, 0, 0));

                ds.DrawText(
                    text,
                    0,
                    0,
                    Colors.White,
                    new CanvasTextFormat
                {
                    FontFamily          = "Segoe UI",
                    FontSize            = fontSize,
                    HorizontalAlignment = CanvasHorizontalAlignment.Center,
                    VerticalAlignment   = CanvasVerticalAlignment.Top
                });
            }

            // Hook up the command list to the inputs of the flame effect graph.
            morphology.Source    = textCommandList;
            composite.Sources[1] = textCommandList;
        }
        /// <summary>
        /// Renders text into a command list and sets this as the input to the flame
        /// effect graph. The effect graph must already be created before calling this method.
        /// </summary>
        private void SetupText(ICanvasResourceCreator resourceCreator)
        {
            textCommandList = new CanvasCommandList(resourceCreator);

            using (var ds = textCommandList.CreateDrawingSession())
            {
                ds.Clear(Colors.Transparent);

                ds.DrawText(
                    "Windows.UI.Composition",
                    0,
                    0,
                    Colors.White,
                    new Microsoft.Graphics.Canvas.Text.CanvasTextFormat
                {
                    FontFamily          = "Segoe UI",
                    FontSize            = 20,
                    HorizontalAlignment = CanvasHorizontalAlignment.Center,
                    VerticalAlignment   = CanvasVerticalAlignment.Top
                });
            }

            // Hook up the command list to the inputs of the flame effect graph.
            morphology.Source    = textCommandList;
            composite.Sources[1] = textCommandList;
        }
Exemplo n.º 16
0
        public override ICanvasImage GetRender(ICanvasResourceCreator resourceCreator, Layerage layerage)
        {
            if (layerage.Children.Count == 0)
            {
                return(null);
            }

            ICanvasImage childImage = LayerBase.Render(resourceCreator, layerage);

            if (childImage is null)
            {
                return(null);
            }

            CanvasCommandList command = new CanvasCommandList(resourceCreator);

            using (CanvasDrawingSession drawingSession = command.CreateDrawingSession())
            {
                if (this.Transform.IsCrop)
                {
                    CanvasGeometry geometryCrop = this.Transform.CropTransformer.ToRectangle(resourceCreator);

                    using (drawingSession.CreateLayer(1, geometryCrop))
                    {
                        drawingSession.DrawImage(childImage);
                    }
                }
                else
                {
                    drawingSession.DrawImage(childImage);
                }
            }
            return(command);
        }
Exemplo n.º 17
0
        private CanvasCommandList GenerateTextDisplay(ICanvasResourceCreator resourceCreator, float width, float height)
        {
            var cl = new CanvasCommandList(resourceCreator);

            using (var ds = cl.CreateDrawingSession())
            {
                float top = height - mOffset;

                float center    = width / 2.0f;
                float symbolPos = center - 5.0f;
                float labelPos  = center + 5.0f;

                for (int i = mFirstLine; i < mLastLine; ++i)
                {
                    float y     = top + mLineHeight * i;
                    int   index = i;

                    if (index < characters.Length)
                    {
                        ds.DrawText(characters[index], labelPos, y, Color.FromArgb(0xff, 0x53, 0xef, 0xef), symbolText);
                    }
                }
            }

            return(cl);
        }
Exemplo n.º 18
0
        public void ProcessFrame(ProcessVideoFrameContext context)
        {
            var inputSurface  = context.InputFrame.Direct3DSurface;
            var outputSurface = context.OutputFrame.Direct3DSurface;

            using (var inputBitmap = CanvasBitmap.CreateFromDirect3D11Surface(canvasDevice, inputSurface))
                using (var renderTarget = CanvasRenderTarget.CreateFromDirect3D11Surface(canvasDevice, outputSurface))
                    using (var ds = renderTarget.CreateDrawingSession())
                        using (var brush = new CanvasImageBrush(canvasDevice, inputBitmap))
                            using (var textCommandList = new CanvasCommandList(canvasDevice))
                            {
                                using (var clds = textCommandList.CreateDrawingSession())
                                {
                                    clds.DrawText(
                                        "Win2D\nMediaClip",
                                        (float)inputBitmap.Size.Width / 2,
                                        (float)inputBitmap.Size.Height / 2,
                                        brush,
                                        new CanvasTextFormat()
                                    {
                                        FontSize   = (float)inputBitmap.Size.Width / 5,
                                        FontWeight = new FontWeight()
                                        {
                                            Weight = 999
                                        },
                                        HorizontalAlignment = CanvasHorizontalAlignment.Center,
                                        VerticalAlignment   = CanvasVerticalAlignment.Center
                                    });
                                }

                                var background = new GaussianBlurEffect()
                                {
                                    BlurAmount = 10,
                                    BorderMode = EffectBorderMode.Hard,
                                    Source     = new BrightnessEffect()
                                    {
                                        BlackPoint = new Vector2(0.5f, 0.7f),
                                        Source     = new SaturationEffect()
                                        {
                                            Saturation = 0,
                                            Source     = inputBitmap
                                        }
                                    }
                                };

                                var shadow = new ShadowEffect()
                                {
                                    Source     = textCommandList,
                                    BlurAmount = 10
                                };

                                var composite = new CompositeEffect()
                                {
                                    Sources = { background, shadow, textCommandList }
                                };

                                ds.DrawImage(composite);
                            }
        }
Exemplo n.º 19
0
        private async void DialController_ButtonClicked(RadialController sender, RadialControllerButtonClickedEventArgs args)
        {
            try
            {
                ShowBusyIndicator("saving file...");

                var picker = new FileSavePicker();
                picker.FileTypeChoices.Add("Jpegs", new List <string>()
                {
                    ".jpg"
                });

                var file = await picker.PickSaveFileAsync();

                if (file == null)
                {
                    return;
                }

                using (var stream = await file.OpenAsync(FileAccessMode.ReadWrite))
                {
                    // watermark the image
                    var device = CanvasDevice.GetSharedDevice();

                    var bounds = virtualBitmap.Bounds;

                    var text = new CanvasCommandList(device);
                    using (var ds = text.CreateDrawingSession())
                    {
                        ds.DrawText("Created by Dial-In", bounds, Colors.White,
                                    new CanvasTextFormat
                        {
                            VerticalAlignment   = CanvasVerticalAlignment.Bottom,
                            HorizontalAlignment = CanvasHorizontalAlignment.Right,
                            FontFamily          = "Segoe UI",
                            FontSize            = (float)(bounds.Height / 12)
                        });
                    }

                    var effect = new BlendEffect()
                    {
                        Background = virtualBitmap,
                        Foreground = text,
                        Mode       = BlendEffectMode.Difference
                    };

                    // save the image to final file
                    await CanvasImage.SaveAsync(effect, bounds, 96, device, stream, CanvasBitmapFileFormat.Jpeg);
                }
            }
            catch (Exception ex)
            {
                await new MessageDialog($"Something went wrong saving the image: {ex}", "Exception").ShowAsync();
            }
            finally
            {
                HideBusyIndicator();
            }
        }
Exemplo n.º 20
0
 static void ValidateCanDrawImage(CanvasDevice device, ICanvasImage image)
 {
     using (var commandList = new CanvasCommandList(device))
         using (var drawingSession = commandList.CreateDrawingSession())
         {
             drawingSession.DrawImage(image);
         }
 }
Exemplo n.º 21
0
        public void ProcessFrame(ProcessVideoFrameContext context)
        {
            var inputSurface = context.InputFrame.Direct3DSurface;
            var outputSurface = context.OutputFrame.Direct3DSurface;

            using (var inputBitmap = CanvasBitmap.CreateFromDirect3D11Surface(canvasDevice, inputSurface))
            using (var renderTarget = CanvasRenderTarget.CreateFromDirect3D11Surface(canvasDevice, outputSurface))
            using (var ds = renderTarget.CreateDrawingSession())
            using (var brush = new CanvasImageBrush(canvasDevice, inputBitmap))
            using (var textCommandList = new CanvasCommandList(canvasDevice))
            {
                using (var clds = textCommandList.CreateDrawingSession())
                {
                    clds.DrawText(
                        "Win2D\nMediaClip",
                        (float)inputBitmap.Size.Width / 2,
                        (float)inputBitmap.Size.Height / 2,
                        brush,
                        new CanvasTextFormat()
                        {
                            FontSize = (float)inputBitmap.Size.Width / 5,
                            FontWeight = new FontWeight() { Weight = 999 },
                            HorizontalAlignment = CanvasHorizontalAlignment.Center,
                            VerticalAlignment = CanvasVerticalAlignment.Center
                        });
                }

                var background = new GaussianBlurEffect()
                {
                    BlurAmount = 10,
                    BorderMode = EffectBorderMode.Hard,
                    Source = new BrightnessEffect()
                    {
                        BlackPoint = new Vector2(0.5f, 0.7f),
                        Source = new SaturationEffect()
                        {
                            Saturation = 0,
                            Source = inputBitmap
                        }
                    }
                };

                var shadow = new ShadowEffect()
                {
                    Source = textCommandList,
                    BlurAmount = 10
                };

                var composite = new CompositeEffect()
                {
                    Sources = { background, shadow, textCommandList }
                };

                ds.DrawImage(composite);
            }
        }
        private static CanvasCommandList GetMarqueeToolGeometry(CanvasDrawingSession drawingSession, ICanvasResourceCreator resourceCreator, CanvasGeometry canvasGeometry)
        {
            CanvasCommandList canvasCommandList = new CanvasCommandList(resourceCreator);

            using (CanvasDrawingSession ds = canvasCommandList.CreateDrawingSession())
            {
                ds.FillGeometry(canvasGeometry, Windows.UI.Colors.DodgerBlue);
            }
            return(canvasCommandList);
        }
Exemplo n.º 23
0
        public void LiquifyFill(ICanvasResourceCreator rc)//填充蓝色渐变圆形
        {
            Liquify = new CanvasCommandList(rc);

            using (var ds = Liquify.CreateDrawingSession())
            {
                //画渐变圆形
                CanvasRadialGradientBrush brush = PaintBrush(rc, new Vector2(LiquifySize), LiquifySize, 0, LiquifyAmount / 100, LiquifyColor);
                ds.FillCircle(LiquifySize, LiquifySize, LiquifySize, brush);
            }
        }
Exemplo n.º 24
0
 private void TheCanvas_CreateResources(CanvasAnimatedControl sender, CanvasCreateResourcesEventArgs args)
 {
     _helloWorld = new CanvasCommandList(sender);
     using (var session = _helloWorld.CreateDrawingSession())
     {
         session.DrawText("Hello, World!", 100, 100, Colors.Black, new CanvasTextFormat()
         {
             FontSize = 80
         });
     }
 }
        private static CanvasCommandList GetMarqueeToolRectangular(CanvasDrawingSession drawingSession, ICanvasResourceCreator resourceCreator, TransformerRect transformerRect)
        {
            CanvasCommandList canvasCommandList = new CanvasCommandList(resourceCreator);

            using (CanvasDrawingSession ds = canvasCommandList.CreateDrawingSession())
            {
                Rect rect = transformerRect.ToRect();
                ds.FillRectangle(rect, Windows.UI.Colors.DodgerBlue);
            }
            return(canvasCommandList);
        }
Exemplo n.º 26
0
        async Task GenerateIcon(AppInfo appInfo, IconInfo iconInfo, StorageFolder folder)
        {
            // Draw the icon image into a command list.
            var iconImage = new CanvasCommandList(device);

            using (var ds = iconImage.CreateDrawingSession())
            {
                appInfo.DrawIconImage(ds, iconInfo);
            }

            // Rasterize into a rendertarget.
            var renderTarget = new CanvasRenderTarget(device, iconInfo.Width, iconInfo.Height, 96);

            using (var ds = renderTarget.CreateDrawingSession())
            {
                // Initialize with the appropriate background color.
                ds.Clear(iconInfo.TransparentBackground ? Colors.Transparent : appInfo.BackgroundColor);

                // Work out where to position the icon image.
                var imageBounds = iconImage.GetBounds(ds);

                imageBounds.Height *= 1 + iconInfo.BottomPadding;

                float scaleUpTheSmallerIcons = Math.Max(1, 1 + (60f - iconInfo.Width) / 50f);

                float imageScale = appInfo.ImageScale * scaleUpTheSmallerIcons;

                ds.Transform = Matrix3x2.CreateTranslation((float)-imageBounds.X, (float)-imageBounds.Y) *
                               Utils.GetDisplayTransform(renderTarget.Size.ToVector2(), new Vector2((float)imageBounds.Width, (float)imageBounds.Height)) *
                               Matrix3x2.CreateScale(imageScale, renderTarget.Size.ToVector2() / 2);

                // Optional shadow effet.
                if (appInfo.AddShadow)
                {
                    var shadow = new ShadowEffect
                    {
                        Source     = iconImage,
                        BlurAmount = 12,
                    };

                    ds.DrawImage(shadow);
                }

                // draw the main icon image.
                ds.DrawImage(iconImage);
            }

            // Save to a file.
            using (var stream = await folder.OpenStreamForWriteAsync(iconInfo.Filename, CreationCollisionOption.ReplaceExisting))
            {
                await renderTarget.SaveAsync(stream.AsRandomAccessStream(), CanvasBitmapFileFormat.Png);
            }
        }
Exemplo n.º 27
0
 public void Draw(ICanvasResourceCreator creator, CanvasDrawingSession ds, double W, double H, float X = 0, float Y = 0)
 {
     if (this.OutPut != null)
     {
         CanvasCommandList CommandList = new CanvasCommandList(creator);
         using (var dds = CommandList.CreateDrawingSession())
         {
             dds.FillRectangle(0, 0, (float)W, (float)H, this.Brush);
             dds.DrawImage(this.OutPut, 0, 0, new Rect(0, 0, W, H), 1, CanvasImageInterpolation.NearestNeighbor, CanvasComposite.DestinationIn);
         }
         ds.DrawImage(CommandList, X, Y);
     }
 }
Exemplo n.º 28
0
 private void canvas1_CreateResources(Microsoft.Graphics.Canvas.UI.Xaml.CanvasAnimatedControl sender, Microsoft.Graphics.Canvas.UI.CanvasCreateResourcesEventArgs args)
 {
     cl = new CanvasCommandList(sender);
     using (CanvasDrawingSession clds = cl.CreateDrawingSession())
     {
         clds.DrawText("Demo", new Vector2((float)Frame.Height / 2, (float)Frame.Width / 2), Colors.Red);
         for (int i = 0; i < 100; i++)
         {
             clds.DrawText("Hello, World!", RndPosition(), Color.FromArgb(255, RndByte(), RndByte(), RndByte()));
             clds.DrawCircle(RndPosition(), RndRadius(), Color.FromArgb(255, RndByte(), RndByte(), RndByte()));
         }
     }
 }
Exemplo n.º 29
0
        private void canvas_CreateResources(
            Microsoft.Graphics.Canvas.UI.Xaml.CanvasAnimatedControl sender,
            Microsoft.Graphics.Canvas.UI.CanvasCreateResourcesEventArgs args)
        {
            CanvasCommandList cl = new CanvasCommandList(sender);

            using (CanvasDrawingSession clds = cl.CreateDrawingSession())
            {
                canvas.Width             = 600;
                canvas.Height            = 600;
                canvas.TargetElapsedTime = TargetElapsedTime;
            }
        }
Exemplo n.º 30
0
        public void LiquifyDraw(ICanvasResourceCreator rc, Vector2 end, Vector2 start)//描边一个位图,用于涂抹改变方向时改变颜色的R与B分量
        {
            float R = 128 + (end.X - start.X) / 10 * 128;
            float G = 128 + (end.Y - start.Y) / 10 * 128;

            Liquify = new CanvasCommandList(rc);
            using (var ds = Liquify.CreateDrawingSession())
            {
                //画圆环
                var co = Color.FromArgb((byte)(255 * LiquifyAmount / 100), (byte)R, (byte)G, 255);
                ds.FillCircle(LiquifySize, LiquifySize, LiquifySize, co);
            }
        }
        private static CanvasCommandList GetMarqueeToolEllipse(CanvasDrawingSession drawingSession, ICanvasResourceCreator resourceCreator, TransformerRect transformerRect)
        {
            CanvasCommandList canvasCommandList = new CanvasCommandList(resourceCreator);

            using (CanvasDrawingSession ds = canvasCommandList.CreateDrawingSession())
            {
                Vector2 centerPoint = transformerRect.Center;
                float   width       = transformerRect.Width / 2;
                float   height      = transformerRect.Height / 2;

                drawingSession.FillEllipse(centerPoint, width, height, Windows.UI.Colors.DodgerBlue);
            }
            return(canvasCommandList);
        }
Exemplo n.º 32
0
        public void CanvasImage_SaveAsync_SourceIsCommandList()
        {
            TestSaveAsync(device =>
            {
                var cl = new CanvasCommandList(device);

                using (var ds = cl.CreateDrawingSession())
                {
                    ds.Clear(Colors.CornflowerBlue);
                }

                return(cl);
            });
        }
Exemplo n.º 33
0
        public void DrawInkDoesNotModifyContextState()
        {
            Point[] points =
            {
                new Point(0, 0),
                new Point(100, 100),
            };

            var strokeBuilder = new InkStrokeBuilder();

            var stroke1 = strokeBuilder.CreateStroke(points);

            strokeBuilder.SetDefaultDrawingAttributes(new InkDrawingAttributes
            {
                Color = Colors.Yellow,
                DrawAsHighlighter = true
            });

            var stroke2 = strokeBuilder.CreateStroke(points);

            using (var device = new CanvasDevice())
            using (var target = new CanvasCommandList(device))
            using (var drawingSession = target.CreateDrawingSession())
            {
                var originalProperties = GetPropertyValues(drawingSession);

                drawingSession.DrawInk(new InkStroke[] { stroke1 });

                var propertiesAfterDraw1 = GetPropertyValues(drawingSession);

                drawingSession.DrawInk(new InkStroke[] { stroke2 });

                var propertiesAfterDraw2 = GetPropertyValues(drawingSession);

                CollectionAssert.AreEqual(originalProperties, propertiesAfterDraw1);
                CollectionAssert.AreEqual(originalProperties, propertiesAfterDraw2);
            }
        }
Exemplo n.º 34
0
        public void Draw(ICanvasAnimatedControl sender, CanvasDrawingSession drawingSession)
        {
            if (currentThunder == null)
            {
                return;
            }
            // 保护原先画布的混合模式
            var previousBlend = drawingSession.Blend;
            drawingSession.Blend = blendState;
            var builder = new CanvasPathBuilder(sender);
            builder.BeginFigure(0, 0);
            for (int i = 0; i < currentThunder.LifeLong; i++)
            {
                builder.AddLine(currentThunder.Path[i].X, currentThunder.Path[i].Y);
            }
            builder.EndFigure(CanvasFigureLoop.Open);
            builder.SetSegmentOptions(CanvasFigureSegmentOptions.ForceRoundLineJoin);

            // Draw the particle.
            var path = CanvasGeometry.CreatePath(builder);
            var NormalizeLifeTime = currentThunder.TimeSinceStart / currentThunder.Duration;
            byte opacity = (byte)((NormalizeLifeTime - 1) * (NormalizeLifeTime - 1) * 255);
            CanvasCommandList cl = new CanvasCommandList(sender);
            using (CanvasDrawingSession clds = cl.CreateDrawingSession())
            {
                clds.DrawGeometry(path, currentThunder.Position, Color.FromArgb((byte)(0.75f * opacity), 255, 255, 255), 6 * currentThunder.Luminace);
            }
            var lightAmount = 20.6f * currentThunder.Luminace * (NormalizeLifeTime - 1) * (NormalizeLifeTime - 1);
            blur.Source = cl;
            blur.BlurAmount = lightAmount;
            drawingSession.DrawImage(blur);
            drawingSession.DrawGeometry(path, currentThunder.Position, Color.FromArgb(opacity, 255, 240, 180), 2 * currentThunder.Luminace);
            drawingSession.Blend = previousBlend;
            if (NormalizeLifeTime > 1)
            {
                currentThunder = null;
            }
        }
        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);
        }
Exemplo n.º 36
0
        private void DoUIElementsEffect(CanvasControl sender, CanvasDrawingSession ds)
        {
            foreach (var elm in _uielements)
            {
                var offset = (float)ExpandAmount / 2;
                using (var cl = new CanvasCommandList(ds))
                {
                    using (var clds = cl.CreateDrawingSession())
                    {
                        using (var canvasbmp = CanvasBitmap.CreateFromBytes(sender.Device, elm.Item1, elm.Item2, elm.Item3, Windows.Graphics.DirectX.DirectXPixelFormat.B8G8R8A8UIntNormalized))
                        {
                            clds.DrawImage(canvasbmp, 0, 0);
                        }

                    }

                    _eg.Setup(cl, (float)GlowAmount, GlowColor);
                    ds.DrawImage(_eg.Output, offset + (float)elm.Item4, offset + (float)elm.Item5);
                }
              
            }
            
        }
Exemplo n.º 37
0
        async Task GenerateIcon(AppInfo appInfo, IconInfo iconInfo, StorageFolder folder)
        {
            // Draw the icon image into a command list.
            var commandList = new CanvasCommandList(device);

            using (var ds = commandList.CreateDrawingSession())
            {
                appInfo.DrawIconImage(ds, iconInfo);
            }

            ICanvasImage iconImage = commandList;

            // Rasterize into a rendertarget.
            var renderTarget = new CanvasRenderTarget(device, iconInfo.Width, iconInfo.Height, 96);

            using (var ds = renderTarget.CreateDrawingSession())
            {
                // Initialize with the appropriate background color.
                ds.Clear(iconInfo.TransparentBackground ? Colors.Transparent : appInfo.BackgroundColor);

                // Work out where to position the icon image.
                var imageBounds = iconImage.GetBounds(ds);

                imageBounds.Height *= 1 + iconInfo.BottomPadding;

                float scaleUpTheSmallerIcons = Math.Max(1, 1 + (60f - iconInfo.Width) / 50f);

                float imageScale = appInfo.ImageScale * scaleUpTheSmallerIcons;

                var transform = Matrix3x2.CreateTranslation((float)-imageBounds.X, (float)-imageBounds.Y) *
                                Utils.GetDisplayTransform(renderTarget.Size.ToVector2(), new Vector2((float)imageBounds.Width, (float)imageBounds.Height)) *
                                Matrix3x2.CreateScale(imageScale, renderTarget.Size.ToVector2() / 2);

                if (iconInfo.Monochrome)
                {
                    // Optionally convert to monochrome.
                    iconImage = new DiscreteTransferEffect
                    {
                        Source = new Transform2DEffect
                        {
                            Source = new LuminanceToAlphaEffect { Source = iconImage },
                            TransformMatrix = transform
                        },

                        RedTable   = new float[] { 1 },
                        GreenTable = new float[] { 1 },
                        BlueTable  = new float[] { 1 },
                        AlphaTable = new float[] { 0, 1 }
                    };
                }
                else
                {
                    ds.Transform = transform;

                    // Optional shadow effect.
                    if (appInfo.AddShadow)
                    {
                        var shadow = new ShadowEffect
                        {
                            Source = iconImage,
                            BlurAmount = 12,
                        };

                        ds.DrawImage(shadow);
                    }
                }

                // draw the main icon image.
                ds.DrawImage(iconImage);
            }

            // Save to a file.
            using (var stream = await folder.OpenStreamForWriteAsync(iconInfo.Filename, CreationCollisionOption.ReplaceExisting))
            {
                await renderTarget.SaveAsync(stream.AsRandomAccessStream(), CanvasBitmapFileFormat.Png);
            }
        }
Exemplo n.º 38
0
        /// <summary>
        /// Renders text into a command list and sets this as the input to the flame
        /// effect graph. The effect graph must already be created before calling this method.
        /// </summary>
        private void SetupText(ICanvasResourceCreator resourceCreator)
        {
            textCommandList = new CanvasCommandList(resourceCreator);

            using (var ds = textCommandList.CreateDrawingSession())
            {
                ds.Clear(Color.FromArgb(0, 0, 0, 0));

                ds.DrawText(
                    text,
                    0,
                    0,
                    Colors.White,
                    new CanvasTextFormat
                    {
                        FontFamily = "Segoe UI",
                        FontSize = fontSize,
                        HorizontalAlignment = CanvasHorizontalAlignment.Center,
                        VerticalAlignment = CanvasVerticalAlignment.Top
                    });
            }

            // Hook up the command list to the inputs of the flame effect graph.
            morphology.Source = textCommandList;
            composite.Sources[1] = textCommandList;
        }
Exemplo n.º 39
0
        private void DoEffect(CanvasDrawingSession ds, Size size, float amount)
        {
            size.Width = size.Width - ExpandAmount;
            size.Height = size.Height - ExpandAmount;

            var offset = (float)(ExpandAmount / 2);           

            using (var textLayout = CreateTextLayout(ds, size))
            using (var textCommandList = new CanvasCommandList(ds))
            {
                using (var textDs = textCommandList.CreateDrawingSession())
                {                     
                    textDs.DrawTextLayout(textLayout, 0, 0, GlowColor);
                }

                glowEffectGraph.Setup(textCommandList, amount);
                ds.DrawImage(glowEffectGraph.Output, offset, offset);

                ds.DrawTextLayout(textLayout, offset, offset, TextColor);
            }
        }
Exemplo n.º 40
0
        private ICanvasImage CreateAlphaMask()
        {
            if (!AlphaMaskEffect.IsSupported)
            {
                return CreateNotSupportedMessage(requiresWin10_14393);
            }

            textLabel = requiresWin10_14393;

            // Draw an alpha gradient into a command list.
            var alphaGradientBrush = new CanvasRadialGradientBrush(canvas, Colors.Black, Colors.Transparent)
            {
                Center = bitmapTiger.Size.ToVector2() / 2,

                RadiusX = (float)bitmapTiger.Size.Width,
                RadiusY = (float)bitmapTiger.Size.Height
            };

            var alphaMask = new CanvasCommandList(canvas);

            using (var drawingSession = alphaMask.CreateDrawingSession())
            {
                drawingSession.FillRectangle(bitmapTiger.Bounds, alphaGradientBrush);
            }

            // Apply the alpha mask to the tiger bitmap.
            var alphaMaskEffect = new AlphaMaskEffect
            {
                Source = bitmapTiger,
                AlphaMask = alphaMask
            };

            // Composite the alpha masked image on top of a background checker pattern.
            var compositeEffect = new CompositeEffect
            {
                Sources = { CreateCheckeredBackground(), alphaMaskEffect }
            };

            animationFunction = elapsedTime => { };

            return compositeEffect;
        }
        static void DrawSecondsText(CanvasDrawingSession ds, Vector2 pos, int seconds)
        {
            // The text is drawn via a command list so we can use DrawImage to specify a difference CanvasComposite mode.
            using (var cl = new CanvasCommandList(ds))
            {
                using (var clds = cl.CreateDrawingSession())
                {
                    clds.DrawText(seconds.ToString(), Vector2.Zero, Colors.White, textFormat);
                }

                Rect textBounds = cl.GetBounds(ds);
                var offset = new Vector2((float)textBounds.Left, (float)textBounds.Top);

                ds.DrawImage(cl, pos + offset, cl.GetBounds(ds), 1, CanvasImageInterpolation.NearestNeighbor, CanvasComposite.MaskInvert);
            }
        }
Exemplo n.º 42
0
        private void DoPathEffect(CanvasControl sender, CanvasDrawingSession ds )
        {    
            using (var thBuilder = new Microsoft.Graphics.Canvas.Geometry.CanvasPathBuilder(sender))
            {
                var pthConverter = new PathToD2DPathGeometryConverter();

                foreach(var path in _paths)
                {
                    var offset = (float)ExpandAmount / 2;
                    using (var cl = new CanvasCommandList(ds))
                    using (var pthGeo = pthConverter.parse(path, thBuilder))
                    {
                        using (var clds = cl.CreateDrawingSession())
                        {
                            clds.FillGeometry(pthGeo,0,0, GlowColor);
                        }

                        _eg.Setup(cl, (float)GlowAmount, GlowColor);
                        ds.DrawImage(_eg.Output, offset, offset);
                        ds.FillGeometry(pthGeo,offset, offset, ((SolidColorBrush)GlowFill).Color);
                    }
                    
                }

            }
        }
Exemplo n.º 43
0
        private void CanvasControl_OnCreateResources(CanvasAnimatedControl sender, CanvasCreateResourcesEventArgs args)
        {
            //init tanks
            InitTanks();
            foreach (var tank in Tanks)
            {

                CanvasCommandList ccl = new CanvasCommandList(sender);
                using (CanvasDrawingSession cds = ccl.CreateDrawingSession())
                {
                    //draw each tank

                    //tank base
                    cds.DrawRectangle(new Rect(-tank.size / 2, -tank.size / 2, tank.size * 2, tank.size), FractionColors[tank.fraction]);
                    //cannon
                    cds.DrawRectangle(new Rect(-tank.size / 2, -tank.size / 2 + (tank.size / 1.5f), tank.size * 3, tank.size / 2), FractionColors[tank.fraction]);
                    //"wheels"

                }
                //set the effect source
                tank.rotationEffect.Source = ccl;
                tank.translationEffect.Source = tank.rotationEffect;
            }

            CanvasCommandList pccl = new CanvasCommandList(sender);
            using (CanvasDrawingSession pds = pccl.CreateDrawingSession())
            {
                pds.DrawCircle(0, 0, 5.0f, new CanvasSolidColorBrush(pds, Colors.Yellow));
            }
            projectilePrototype.translationEffect = new Transform2DEffect();
            projectilePrototype.translationEffect.Source = pccl;

        }
Exemplo n.º 44
0
        public void EditRegionMask(List<Vector2> points, float zoomFactor)
        {
            if (regionMask == null)
            {
                // Demand-create our region mask image.
                regionMask = new CanvasRenderTarget(SourceBitmap.Device, Parent.Size.X, Parent.Size.Y, 96);
            }
            else
            {
                // Back up the previous mask, to support undo.
                previousRegionMask = currentRegionMask;
            }

            // Prepare an ICanvasImage holding the edit to be applied.
            ICanvasImage editMask;

            if (RegionSelectionMode == SelectionMode.MagicWand)
            {
                // Magic wand selection is already an image.
                editMask = GetMagicWandMask(points, zoomFactor);
            }
            else
            {
                // Capture selection geometry into a command list.
                var commandList = new CanvasCommandList(regionMask.Device);

                using (var drawingSession = commandList.CreateDrawingSession())
                {
                    // If this was just a touch without move, treat it as selecting the entire image.
                    var dragRange = points.Select(point => Vector2.Distance(point, points[0])).Max() * zoomFactor;

                    if (dragRange < 10)
                    {
                        drawingSession.Clear(Colors.White);
                    }
                    else
                    {
                        // Draw selection geometry.
                        var geometry = GetSelectionGeometry(drawingSession, points);

                        drawingSession.FillGeometry(geometry, Colors.White);
                    }
                }

                editMask = commandList;
            }

            // Apply the edit.
            using (var drawingSession = regionMask.CreateDrawingSession())
            {
                CanvasComposite compositeMode;

                switch (RegionSelectionOperation)
                {
                    case SelectionOperation.Replace:
                        drawingSession.Clear(Colors.Transparent);
                        compositeMode = CanvasComposite.SourceOver;
                        break;

                    case SelectionOperation.Add:
                        compositeMode = CanvasComposite.SourceOver;
                        break;

                    case SelectionOperation.Subtract:
                        compositeMode = CanvasComposite.DestinationOut;
                        break;

                    case SelectionOperation.Invert:
                        compositeMode = CanvasComposite.Xor;
                        break;

                    default:
                        throw new NotSupportedException();
                }

                drawingSession.DrawImage(editMask, Vector2.Zero, regionMask.Bounds, 1, CanvasImageInterpolation.Linear, compositeMode);
            }

            // Back up the mask, so we can recover from lost devices.
            currentRegionMask = regionMask.GetPixelBytes();

            cachedRegionMask.Reset();

            CanUndo = true;
        }
Exemplo n.º 45
0
        void CreateLinearGradient(ICanvasResourceCreator resourceCreator)
        {
            var commandList = new CanvasCommandList(resourceCreator);

            using (var drawingSession = commandList.CreateDrawingSession())
            {
                var brush = new CanvasLinearGradientBrush(resourceCreator, Colors.White, Colors.Black)
                {
                    StartPoint = new Vector2(-tigerSize.X / 4, 0),
                    EndPoint = new Vector2(tigerSize.X * 5 / 4, 0),
                };

                // Expand the bounds to avoid going past the edge of the gradient as we rotate it.
                var expandedBounds = new Rect((-tigerSize).ToPoint(), (tigerSize * 2).ToPoint());

                drawingSession.FillRectangle(expandedBounds, brush);
            }

            linearGradient = new Transform2DEffect
            {
                Source = commandList
            };
        }
Exemplo n.º 46
0
        void CreateRadialGradient(ICanvasResourceCreator resourceCreator)
        {
            radialGradient = new CanvasCommandList(resourceCreator);

            using (var drawingSession = radialGradient.CreateDrawingSession())
            {
                var sqrt2 = (float)Math.Sqrt(2);

                var brush = new CanvasRadialGradientBrush(resourceCreator, Colors.White, Colors.Black)
                {
                    Center = tigerSize / 2,

                    RadiusX = tigerSize.X / sqrt2,
                    RadiusY = tigerSize.Y / sqrt2,
                };

                drawingSession.FillRectangle(bitmapTiger.Bounds, brush);
            }
        }
Exemplo n.º 47
0
        void CreateLinearGradient(ICanvasResourceCreator resourceCreator)
        {
            var commandList = new CanvasCommandList(resourceCreator);

            using (var drawingSession = commandList.CreateDrawingSession())
            {
                var brush = new CanvasLinearGradientBrush(resourceCreator, Colors.White, Colors.Black)
                {
                    StartPoint = new Vector2(-tigerSize.X / 4, 0),
                    EndPoint = new Vector2(tigerSize.X * 5 / 4, 0),
                };

                drawingSession.FillRectangle(bitmapTiger.Bounds, brush);
            }

            // Wrap the gradient with a border effect to avoid edge artifacts as we rotate it.
            linearGradient = new Transform2DEffect
            {
                Source = new BorderEffect
                {
                    Source = commandList
                }
            };
        }
Exemplo n.º 48
0
        ICanvasImage WrapSourceWithIntermediateImage(PerDeviceResources resources, IntermediateMode mode)
        {
            switch (mode)
            {
                case IntermediateMode.ImageEffect:
                    // We can either feed our graphics through an image effect...
                    resources.SaturationEffect.Source = GetSourceBitmap(resources) ??
                                                        WrapSourceWithIntermediateImage(resources, IntermediateMode.None);

                    resources.AddMessage("SaturationEffect ->\n");

                    return resources.SaturationEffect;

                case IntermediateMode.CommandList:
                    var cl = new CanvasCommandList(resources.ResourceCreator);
                    using (var ds = cl.CreateDrawingSession())
                    {
                        DrawSourceGraphic(resources, ds, 0);
                    }
                    resources.AddMessage("CommandList ->\n");
                    return cl;

                case IntermediateMode.ImageEffectInCommandList:
                    var cl2 = new CanvasCommandList(resources.ResourceCreator);
                    using (var ds = cl2.CreateDrawingSession())
                    {
                        ds.DrawImage(WrapSourceWithIntermediateImage(resources, IntermediateMode.ImageEffect));
                    }
                    resources.AddMessage("CommandList ->\n");
                    return cl2;

                default:
                    // ... or draw them into a rendertarget.
                    var renderTarget = GetIntermediateRenderTarget(resources, mode);

                    using (var ds = renderTarget.CreateDrawingSession())
                    {
                        DrawSourceGraphic(resources, ds, 0);
                    }

                    var pixels = renderTarget.SizeInPixels;
                    resources.AddMessage("RenderTarget (dpi: {0}, size: {1}, pixels: {2},{3}) ->\n", renderTarget.Dpi, renderTarget.Size, pixels.Width, pixels.Height);

                    return renderTarget;
            }
        }
Exemplo n.º 49
0
        private void DoEffect(CanvasDrawingSession ds, Size size, float amount, Windows.UI.Color glowColor, Windows.UI.Color fillColor, double expandAmount)
        {
            var offset = (float)expandAmount / 2;
            //using (var textLayout = CreateTextLayout(ds, size))
            using (var cl = new CanvasCommandList(ds))
            {
                using (var clds = cl.CreateDrawingSession())
                {
                    clds.FillRectangle(0, 0, (float)size.Width, (float)size.Height, glowColor);
                }

                glowEffectGraph.Setup(cl, amount);
                ds.DrawImage(glowEffectGraph.Output, offset, offset);
                ds.FillRectangle(offset, offset, (float)size.Width, (float)size.Height, fillColor);
            }
        }
        /// <summary>
        /// Renders text into a command list and sets this as the input to the flame
        /// effect graph. The effect graph must already be created before calling this method.
        /// </summary>
        private void SetupText(ICanvasResourceCreator resourceCreator)
        {
            textCommandList = new CanvasCommandList(resourceCreator);

            using (var ds = textCommandList.CreateDrawingSession())
            {
                ds.Clear(Colors.Transparent);

                ds.DrawText(
                    "Windows.UI.Composition",
                    0,
                    0,
                    Colors.White,
                    new Microsoft.Graphics.Canvas.Text.CanvasTextFormat
                    {
                        FontFamily = "Segoe UI",
                        FontSize = 20,
                        HorizontalAlignment = CanvasHorizontalAlignment.Center,
                        VerticalAlignment = CanvasVerticalAlignment.Top
                    });
            }

            // Hook up the command list to the inputs of the flame effect graph.
            morphology.Source = textCommandList;
            composite.Sources[1] = textCommandList;
        }
Exemplo n.º 51
0
        static void DrawTile(CanvasDrawingSession ds, float width, float height)
        {
            using (var cl = new CanvasCommandList(ds))
            {
                using (var clds = cl.CreateDrawingSession())
                {
                    var text = string.Format("{0}\n{1}", DateTime.Now.ToString("ddd"), DateTime.Now.ToString("HH:mm"));

                    var textFormat = new CanvasTextFormat()
                    {
                        FontFamily = "Segoe UI Black",
                        HorizontalAlignment = CanvasHorizontalAlignment.Right,
                        VerticalAlignment = CanvasVerticalAlignment.Center,
                        FontSize = 20,
                        LineSpacing = 20
                    };

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

                var effect = new GaussianBlurEffect()
                {
                    Source = cl,
                    BlurAmount = 1,
                };

                ds.Clear(Colors.Orange);

                var bounds = effect.GetBounds(ds);
                var ratio = bounds.Height / bounds.Width;
                var destHeight = height * ratio;

                ds.DrawImage(effect, new Rect(0, height / 2 - destHeight / 2, width, destHeight), bounds);

                ds.DrawText(string.Format("Generated by Win2D\n{0}\n{1}", DateTime.Now.ToString("d"), DateTime.Now.ToString("t")),
                    12, 12, Colors.Black,
                    new CanvasTextFormat()
                    {
                        HorizontalAlignment = CanvasHorizontalAlignment.Left,
                        VerticalAlignment = CanvasVerticalAlignment.Top,
                        FontSize = 12
                    });
            }
        }
Exemplo n.º 52
0
        private async void DoStreamsEffect(CanvasControl sender, CanvasDrawingSession ds)
        {
            foreach (var stream in _streams)
            {
                var offset = (float)ExpandAmount / 2;
                using (var cl = new CanvasCommandList(ds))
                {
                    using (var clds = cl.CreateDrawingSession())
                    {
                        stream.Seek(0);
                        var canvasbmp = await CanvasBitmap.LoadAsync(sender, stream);
                        clds.DrawImage(canvasbmp, 0, 0);
                    }

                    _eg.Setup(cl, (float)GlowAmount, GlowColor);
                    ds.DrawImage(_eg.Output, offset, offset);
                }

                
            }
        }
Exemplo n.º 53
0
        private async void OnSaveAsClicked(object sender, RoutedEventArgs e)
        {
            // the button should be disabled if there's no bitmap loaded
            Debug.Assert(virtualBitmap != null);

            var picker = new FileSavePicker();
            picker.FileTypeChoices.Add("Jpegs", new List<string>() { ".jpg" });

            var file = await picker.PickSaveFileAsync();
            if (file == null)
                return;

            using (var stream = await file.OpenAsync(FileAccessMode.ReadWrite))
            {
                // Stamp a big "Win2D" over the image before we save it, to demonstrate
                // that the image really has been processed.
                var device = CanvasDevice.GetSharedDevice();

                var bounds = virtualBitmap.Bounds;

                var text = new CanvasCommandList(device);
                using (var ds = text.CreateDrawingSession())
                {
                    ds.DrawText("Win2D", bounds, Colors.White,
                        new CanvasTextFormat()
                        {
                            VerticalAlignment = CanvasVerticalAlignment.Center,
                            HorizontalAlignment = CanvasHorizontalAlignment.Center,
                            FontFamily = "Comic Sans MS",
                            FontSize = (float)(bounds.Height / 4)
                        });
                }

                var effect = new BlendEffect()
                {
                    Background = virtualBitmap,
                    Foreground = text,
                    Mode = BlendEffectMode.Difference
                };

                try
                {
                    await CanvasImage.SaveAsync(effect, bounds, 96, device, stream, CanvasBitmapFileFormat.Jpeg);
                    var message = string.Format("Finished saving '{0}'", file.Name);
                    var messageBox = new MessageDialog(message, "Virtual Bitmap Example").ShowAsync();
                }
                catch
                {
                    var message = string.Format("Error saving '{0}'", file.Name);
                    var messageBox = new MessageDialog(message, "Virtual Bitmap Example").ShowAsync();
                }
            }
        }
        private void Canvas_Draw(ICanvasAnimatedControl sender, CanvasAnimatedDrawEventArgs args)
        {
            var cl = new CanvasCommandList(sender);
            using (var clds = cl.CreateDrawingSession())
            {
                if (_bytes != null)
                {
                    using (var bitmap = CanvasBitmap.CreateFromBytes(sender, _bytes, _widthInPixels, _heightInPixels, DirectXPixelFormat.B8G8R8A8UIntNormalized, _dpi))
                    {
                        clds.DrawImage(bitmap);
                    }
                    clds.FillRectangle(0, 0, _widthInPixels, _heightInPixels, _maskColor);
                }
                else
                {
                    clds.FillRectangle(0, 0, (float)sender.Size.Width, (float)sender.Size.Height, _maskColor);
                }
            }

            _effect.Source = cl;
            args.DrawingSession.DrawImage(_effect);
        }
Exemplo n.º 55
0
        private ICanvasImage CreateNotSupportedMessage(string message)
        {
            var commandList = new CanvasCommandList(canvas);

            var textFormat = new CanvasTextFormat
            {
                FontSize = 16,
                HorizontalAlignment = CanvasHorizontalAlignment.Center,
                VerticalAlignment = CanvasVerticalAlignment.Center
            };

            using (var ds = commandList.CreateDrawingSession())
            {
                ds.DrawText(message, bitmapTiger.Bounds, Colors.Red, textFormat);
            }

            animationFunction = elapsedTime => { };

            return commandList;
        }
Exemplo n.º 56
0
 static void ValidateCanDrawImage(CanvasDevice device, ICanvasImage image)
 {
     using (var commandList = new CanvasCommandList(device))
     using (var drawingSession = commandList.CreateDrawingSession())
     {
         drawingSession.DrawImage(image);
     }
 }
Exemplo n.º 57
0
        private CanvasCommandList GenerateTextDisplay(ICanvasResourceCreator resourceCreator, float width, float height)
        {
            var cl = new CanvasCommandList(resourceCreator);

            using (var ds = cl.CreateDrawingSession())
            {
                float top = height - offset;

                float center = width / 4.0f;
                float symbolPos = center - 5.0f;
                float labelPos = center + 5.0f;

                for (int i = firstLine; i < lastLine; ++i)
                {
                    float y = top + lineHeight * i;
                    int index = i;

                    if (index < characters.Length)
                    {
                        ds.DrawText(string.Format("{0}", (char)characters[index].Code), symbolPos, y, Colors.White, symbolText);
                        ds.DrawText(string.Format("0x{0:X} - {1}", characters[index].Code, characters[index].Label), labelPos, y, Colors.White, labelText);
                    }
                }
            }

            return cl;
        }
Exemplo n.º 58
0
        void DrawShadow(CanvasControl canvasCtrl, CanvasDrawingSession drawSession, List<ShadowParam> shadowParams)
        {
            var canvasCommandList = new CanvasCommandList(canvasCtrl);
            var content = _contentPresenter.Content as FrameworkElement;
            var contentWidth = content.ActualWidth + content.Margin.Left + content.Margin.Right;
            var contentHeight = content.ActualHeight + content.Margin.Top + content.Margin.Bottom;
            var radius = GetActualCornerRadius(contentWidth);
            double maxOffset_Y = shadowParams.Max(param => param.Offset_Y);

            _shadowCanvas.VerticalAlignment = content.VerticalAlignment;
            _shadowCanvas.HorizontalAlignment = content.HorizontalAlignment;

            using (var ds = canvasCommandList.CreateDrawingSession())
            {
                ds.FillRoundedRectangle(new Rect(0, 0, contentWidth, contentHeight), radius, radius, Color.FromArgb(255, 0, 0, 0));
            }

            CompositeEffect compositeEffect = CreateEffects(shadowParams, canvasCommandList);

            var bound = compositeEffect.GetBounds(drawSession);
            double shadowWidth = Math.Abs(bound.X);
            double shadowHeight = Math.Abs(bound.Y);

            UpdateLayout(maxOffset_Y, bound, shadowWidth, shadowHeight);

            DrawEffect(drawSession, compositeEffect, shadowWidth, shadowHeight);
        }