private static async Task <CompositionDrawingSurface> GetCompositionDrawingSurface(Compositor compositor, RenderTargetBitmap renderTargetBitmap)
        {
            IBuffer pixels = await renderTargetBitmap.GetPixelsAsync();

            using (var canvasDevice = new CanvasDevice())
                using (CompositionGraphicsDevice graphicsDevice = CanvasComposition.CreateCompositionGraphicsDevice(compositor, canvasDevice))
                {
                    float dpi = DisplayInformation.GetForCurrentView().LogicalDpi;
                    using (var canvasBitmap = CanvasBitmap.CreateFromBytes(canvasDevice, pixels.ToArray(),
                                                                           renderTargetBitmap.PixelWidth, renderTargetBitmap.PixelHeight,
                                                                           DirectXPixelFormat.B8G8R8A8UIntNormalized, dpi))
                    {
                        CompositionDrawingSurface surface = graphicsDevice.CreateDrawingSurface(
                            new Size(renderTargetBitmap.PixelWidth, renderTargetBitmap.PixelHeight),
                            DirectXPixelFormat.B8G8R8A8UIntNormalized, DirectXAlphaMode.Premultiplied);
                        using (CanvasDrawingSession session = CanvasComposition.CreateDrawingSession(surface))
                        {
                            session.DrawImage(canvasBitmap, 0, 0,
                                              new Rect(0, 0, canvasBitmap.Size.Width, canvasBitmap.Size.Height));
                        }

                        return(surface);
                    }
                }
        }
Esempio n. 2
0
        private void Setup()
        {
            _canvasDevice = new CanvasDevice();

            var compositionGraphicsDevice = CanvasComposition.CreateCompositionGraphicsDevice(
                Window.Current.Compositor,
                _canvasDevice);

            var compositor = Window.Current.Compositor;

            _surface = compositionGraphicsDevice.CreateDrawingSurface(
                new Size(1000, 600),
                DirectXPixelFormat.B8G8R8A8UIntNormalized,
                DirectXAlphaMode.Premultiplied);
            // 现在只有这个参数能在 Composition 使用

            var visual = compositor.CreateSpriteVisual();

            visual.RelativeSizeAdjustment = Vector2.One;
            var brush = compositor.CreateSurfaceBrush(_surface);

            brush.Stretch = CompositionStretch.Uniform;
            visual.Brush  = brush;
            ElementCompositionPreview.SetElementChildVisual(this, visual);

            _compositionGraphicsDevice = compositionGraphicsDevice;
        }
        public void DrawTile(Rect rect, int tileRow, int tileColumn)
        {
            Color waterColor = Color.FromArgb(255, 172, 199, 242);
            Action <CanvasBitmap> drawAction = (CanvasBitmap bitmap) =>
            {
                lock (sync)
                {
                    using (var drawingSession = CanvasComposition.CreateDrawingSession(drawingSurface, rect))
                    {
                        drawingSession.Clear(waterColor);
                        if (bitmap != null)
                        {
                            drawingSession.DrawImage(bitmap);
                        }
                    }
                }
            };

            if (TileCache.Tiles.ContainsKey(TileCache.GetTileKey(ZoomLevel, tileColumn, tileRow)))
            {
                drawAction(TileCache.Tiles[TileCache.GetTileKey(ZoomLevel, tileColumn, tileRow)]);
            }
            else
            {
                drawAction(null);

                //TODO handle the error case where the load fails
                CanvasBitmap.LoadAsync(CanvasDevice.GetSharedDevice(), TileCache.GetTileUri(ZoomLevel, tileColumn, tileRow), 96).AsTask().ContinueWith((bm) =>
                {
                    TileCache.AddImage(ZoomLevel, tileColumn, tileRow, bm.Result);
                    //redraw the tile once we have the image downloaded
                    drawAction(bm.Result);
                });
            }
        }
Esempio n. 4
0
 public CompositionMaskHelper(Compositor compositor)
 {
     _compositor        = compositor;
     _canvasDevice      = new CanvasDevice();
     _compositionDevice = CanvasComposition.CreateCompositionGraphicsDevice(_compositor, _canvasDevice);
     _surfaceFactory    = SurfaceFactory.CreateFromCompositor(_compositor);
 }
Esempio n. 5
0
        /// <summary>
        ///     This method allows us to reuse a background image that has already been processed.
        /// </summary>
        /// <param name="pixels">The pixel buffer.</param>
        /// <param name="bitmap">The output from RenderTargetBitmap.</param>
        /// <param name="dpi">The view DPI where the background was rendered.</param>
        /// <param name="areaToRender">The region of the background we wish to cut out.</param>
        /// <returns>A <see cref="CompositionSurfaceBrush" /> containing the portion of the background we want.</returns>
        private CompositionSurfaceBrush CreateBackgroundBrush(IBuffer pixels, RenderTargetBitmap bitmap, float dpi,
                                                              Rect areaToRender)
        {
            // load the pixels from RenderTargetBitmap onto a CompositionDrawingSurface
            CompositionDrawingSurface uiElementBitmapSurface;

            using (
                // this is the entire background image
                // Note we are using the display DPI here.
                var canvasBitmap = CanvasBitmap.CreateFromBytes(
                    _canvasDevice, pixels.ToArray(),
                    bitmap.PixelWidth,
                    bitmap.PixelHeight,
                    DirectXPixelFormat.B8G8R8A8UIntNormalized,
                    dpi)
                )
            {
                // we create a surface we can draw on in memory.
                // note we are using the desired size of our overlay
                uiElementBitmapSurface =
                    _compositionDevice.CreateDrawingSurface(
                        new Size(areaToRender.Width, areaToRender.Height),
                        DirectXPixelFormat.B8G8R8A8UIntNormalized, DirectXAlphaMode.Premultiplied);
                using (var session = CanvasComposition.CreateDrawingSession(uiElementBitmapSurface))
                {
                    // here we draw just the part of the background image we wish to use to overlay
                    session.DrawImage(canvasBitmap, 0, 0, areaToRender);
                }
            }

            var backgroundBrush = _compositor.CreateSurfaceBrush(uiElementBitmapSurface);

            backgroundBrush.Stretch = CompositionStretch.UniformToFill;
            return(backgroundBrush);
        }
Esempio n. 6
0
        public FrameServerHandler(MediaPlayer player, FrameworkElement container, string id, IPropertySet properties)
        {
            CanvasDevice      = CanvasDevice.GetSharedDevice();
            Container         = container;
            ID                = id;
            Player            = player;
            ContainerVisual   = ElementCompositionPreview.GetElementVisual(container);
            Compositor        = ContainerVisual.Compositor;
            CompositionDevice = CanvasComposition.CreateCompositionGraphicsDevice(Compositor, CanvasDevice);
            SpriteVisual      = Compositor.CreateSpriteVisual();
            SurfaceBrush      = Compositor.CreateSurfaceBrush();

            SpriteVisual.Brush   = SurfaceBrush;
            SurfaceBrush.Stretch = CompositionStretch.Uniform;
            ElementCompositionPreview.SetElementChildVisual(container, SpriteVisual);
            var sizeAni = Compositor.CreateExpressionAnimation("Container.Size");

            sizeAni.SetReferenceParameter("Container", ContainerVisual);
            SpriteVisual.StartAnimation("Size", sizeAni);

            CanvasDevice.DeviceLost += CanvasDevice_DeviceLost;

            Container.SizeChanged += Container_SizeChanged;

            player.IsVideoFrameServerEnabled = true;
            player.VideoFrameAvailable      += Player_VideoFrameAvailable;
            player.MediaOpened += Player_MediaOpened;
            //createDestinationTarget();
        }
Esempio n. 7
0
        public void DrawString(string c)
        {
            sofar += c;
            using (
                var drawingSession = CanvasComposition.CreateDrawingSession(drawingSurface,
                                                                            new Rect(0, 0, ActualWidth, ActualHeight)))
            {
                CanvasTextFormat tf = new CanvasTextFormat()
                {
                    FontSize = 72
                };

                float            xLoc   = 100.0f;
                float            yLoc   = 100.0f;
                CanvasTextFormat format = new CanvasTextFormat
                {
                    FontSize     = 30.0f,
                    WordWrapping = CanvasWordWrapping.NoWrap
                };
                CanvasTextLayout textLayout = new CanvasTextLayout(drawingSession, sofar, format, 0.0f,
                                                                   0.0f);
                Rect theRectYouAreLookingFor = new Rect(xLoc + textLayout.DrawBounds.X,
                                                        yLoc + textLayout.DrawBounds.Y, textLayout.DrawBounds.Width, textLayout.DrawBounds.Height);
                drawingSession.DrawRectangle(theRectYouAreLookingFor, Colors.Green, 1.0f);
                drawingSession.DrawTextLayout(textLayout, xLoc, yLoc, Colors.Yellow);

                drawingSession.DrawInk(list);
            }
        }
        CompositionDrawingSurface ApplyBlurEffect(CanvasBitmap bitmap, Windows.UI.Composition.CompositionGraphicsDevice device, Size sizeTarget)
        {
            GaussianBlurEffect blurEffect = new GaussianBlurEffect()
            {
                Source     = bitmap,
                BlurAmount = 20.0f,
                BorderMode = EffectBorderMode.Hard,
            };

            float fDownsample = .3f;
            Size  sizeSource  = bitmap.Size;

            if (sizeTarget == Size.Empty)
            {
                sizeTarget = sizeSource;
            }

            sizeTarget = new Size(sizeTarget.Width * fDownsample, sizeTarget.Height * fDownsample);
            CompositionDrawingSurface blurSurface = device.CreateDrawingSurface(sizeTarget, DirectXPixelFormat.B8G8R8A8UIntNormalized, DirectXAlphaMode.Premultiplied);

            using (var ds = CanvasComposition.CreateDrawingSession(blurSurface))
            {
                Rect destination = new Rect(0, 0, sizeTarget.Width, sizeTarget.Height);
                ds.Clear(Windows.UI.Color.FromArgb(255, 255, 255, 255));
                ds.DrawImage(blurEffect, destination, new Rect(0, 0, sizeSource.Width, sizeSource.Height));
            }

            return(blurSurface);
        }
Esempio n. 9
0
#pragma warning disable 1998
        public async Task Draw(CompositionGraphicsDevice device, Object drawingLock, CompositionDrawingSurface surface, Size size)
        {
            using (var ds = CanvasComposition.CreateDrawingSession(surface)) {
                ds.Clear(Colors.Transparent);
                ds.FillCircle(new Vector2(_radius, _radius), _radius, _color);
            }
        }
        private static async Task <CompositionDrawingSurface> LoadFromUri(CanvasDevice canvasDevice, CompositionGraphicsDevice compositionDevice, Uri uri, Size sizeTarget)
        {
            CanvasBitmap bitmap = await CanvasBitmap.LoadAsync(canvasDevice, uri);

            Size sizeSource = bitmap.Size;

            if (sizeTarget.IsEmpty)
            {
                sizeTarget = sizeSource;
            }

            var surface = compositionDevice.CreateDrawingSurface(
                sizeTarget,
                DirectXPixelFormat.B8G8R8A8UIntNormalized,
                DirectXAlphaMode.Premultiplied);

            using (var ds = CanvasComposition.CreateDrawingSession(surface))
            {
                ds.Clear(Color.FromArgb(0, 0, 0, 0));
                ds.DrawImage(
                    bitmap,
                    new Rect(0, 0, sizeTarget.Width, sizeTarget.Height),
                    new Rect(0, 0, sizeSource.Width, sizeSource.Height),
                    1,
                    CanvasImageInterpolation.HighQualityCubic);
            }

            return(surface);
        }
Esempio n. 11
0
 void RenderFrame()
 {
     if (destinationTarget != null)
     {
         lock (ResourceLock)
         {
             var args = new VideoEffectHandlerArgs()
             {
                 InputFrame  = sourceTarget,
                 OutputFrame = destinationTarget,
                 ID          = ID,
                 Properties  = Properties,
                 Device      = CanvasDevice
             };
             bool effectsAdded = VideoEffectManager.ProcessFrame(args);
             using (var ds = CanvasComposition.CreateDrawingSession(DrawingSurface))
             {
                 ds.DrawImage(destinationTarget);
             }
         }
     }
     else
     {
         Container.RunOnUIThread(createDestinationTarget);
     }
 }
Esempio n. 12
0
        private CompositionDrawingSurface SampleImageColor(CanvasBitmap bitmap, CompositionGraphicsDevice device, Size sizeTarget)
        {
            // Extract the color to tint the blur with
            Color predominantColor = ExtractPredominantColor(bitmap.GetPixelColors(), bitmap.Size);

            Size sizeSource = bitmap.Size;

            if (sizeTarget.IsEmpty)
            {
                sizeTarget = sizeSource;
            }

            // Create a heavily blurred version of the image
            GaussianBlurEffect blurEffect = new GaussianBlurEffect()
            {
                Source     = bitmap,
                BlurAmount = 20.0f
            };

            CompositionDrawingSurface surface = device.CreateDrawingSurface(sizeTarget,
                                                                            DirectXPixelFormat.B8G8R8A8UIntNormalized, DirectXAlphaMode.Premultiplied);

            using (var ds = CanvasComposition.CreateDrawingSession(surface))
            {
                Rect destination = new Rect(0, 0, sizeTarget.Width, sizeTarget.Height);
                ds.FillRectangle(destination, predominantColor);
                ds.DrawImage(blurEffect, destination, new Rect(0, 0, sizeSource.Width, sizeSource.Height), .6f);
            }

            return(surface);
        }
Esempio n. 13
0
        void DrawDrawingSurface()
        {
            ++drawCount;

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

                var rect = new Rect(new Point(2, 2), (drawingSurface.Size.ToVector2() - new Vector2(4, 4)).ToSize());

                ds.FillRoundedRectangle(rect, 15, 15, Colors.LightBlue);
                ds.DrawRoundedRectangle(rect, 15, 15, Colors.Gray, 2);

                ds.DrawText("This is a composition drawing surface", rect, Colors.Black, new CanvasTextFormat()
                {
                    FontFamily          = "Comic Sans MS",
                    FontSize            = 32,
                    WordWrapping        = CanvasWordWrapping.WholeWord,
                    VerticalAlignment   = CanvasVerticalAlignment.Center,
                    HorizontalAlignment = CanvasHorizontalAlignment.Center
                });

                ds.DrawText("Draws: " + drawCount, rect, Colors.Black, new CanvasTextFormat()
                {
                    FontSize            = 10,
                    VerticalAlignment   = CanvasVerticalAlignment.Bottom,
                    HorizontalAlignment = CanvasHorizontalAlignment.Center
                });
            }
        }
        private void Form1_Load(object sender, EventArgs e)
        {
            // This container visual is optional - content could go directly into the root
            // containerVisual. This lets you overlay just the picture box, and you could add
            // other container visuals to overlay other areas of the UI.
            pictureOverlayVisual        = compositor.CreateContainerVisual();
            pictureOverlayVisual.Offset = new Vector3(pictureBox1.Bounds.Left, pictureBox1.Bounds.Top, 0);
            pictureOverlayVisual.Size   = new Vector2(pictureBox1.Width, pictureBox1.Height);
            containerVisual.Children.InsertAtTop(pictureOverlayVisual);

            rectWidth  = pictureBox1.Width / 2;
            rectHeight = pictureBox1.Height / 2;

            // Get graphics device.
            compositionGraphicsDevice = CanvasComposition.CreateCompositionGraphicsDevice(compositor, canvasDevice);

            // Create surface.
            var noiseDrawingSurface = compositionGraphicsDevice.CreateDrawingSurface(
                new Windows.Foundation.Size(rectWidth, rectHeight),
                DirectXPixelFormat.B8G8R8A8UIntNormalized,
                DirectXAlphaMode.Premultiplied);

            // Draw to surface and create surface brush.
            var noiseFilePath = AppDomain.CurrentDomain.BaseDirectory + "Assets\\NoiseAsset_256X256.png";

            LoadSurface(noiseDrawingSurface, noiseFilePath);
            noiseSurfaceBrush = compositor.CreateSurfaceBrush(noiseDrawingSurface);

            // Add composition content to tree.
            AddCompositionContent();
        }
 /// <summary>
 /// Redraws the mask surface with the given size and geometry
 /// </summary>
 /// <param name="surface">CompositionDrawingSurface</param>
 /// <param name="size">Size ofthe Mask Surface</param>
 /// <param name="geometry">Geometry of the Mask Surface</param>
 /// <returns>Task</returns>
 public Task RedrawMaskSurfaceAsync(CompositionDrawingSurface surface, Size size, CanvasGeometry geometry)
 {
     return(Task.Run(() =>
     {
         //
         // Since the drawing is done asynchronously and multiple threads could
         // be trying to get access to the device/surface at the same time, we need
         // to do any device/surface work under a lock.
         //
         lock (_drawingLock)
         {
             // Render the mask to the surface
             using (var session = CanvasComposition.CreateDrawingSession(surface))
             {
                 // If the geometry is not null then fill the geometry area
                 // with white. The rest of the area on the surface will be transparent.
                 // When this mask is applied to a visual, only the area that is white
                 // will be visible.
                 if (geometry != null)
                 {
                     session.Clear(Colors.Transparent);
                     session.FillGeometry(geometry, Colors.White);
                 }
                 else
                 {
                     // If the geometry is null, then the entire mask should be filled white
                     // so that the masked visual can be seen completely.
                     session.Clear(Colors.White);
                 }
             }
         }
     }));
 }
Esempio n. 16
0
        void DrawText(CanvasTextLayout textLayout)
        {
            #region unused
            // text drawer method 1 - no anti-aliasing feature
            //var layout = new CanvasTextLayout(_device, Text, textformat, (float)Width, (float)Height);
            //var geometry = CanvasGeometry.CreateText(layout);
            //var compPath = new CompositionPath(geometry);
            //var pathGeo = _compositor.CreatePathGeometry(compPath);

            // set to container
            //var w = _compositor.CreateSpriteShape(pathGeo);
            //w.FillBrush = _compositor.CreateColorBrush(Color.FromArgb(0xd7, 0xff, 0xff, 0xff));
            //_shape.Shapes.Add(w);
            #endregion

            // text drawer - with anti-aliasing feature
            using var ds = CanvasComposition.CreateDrawingSession(_drawsurface);

            ds.Antialiasing = CanvasAntialiasing.Antialiased;
            //ds.DrawText(Text, rectext, Color.FromArgb(0xd7, 0xff, 0xff, 0xff), textformat);
            ds.DrawTextLayout(textLayout, (float)Width / 2, (float)Height / 2, Color.FromArgb(0xd7, 0xff, 0xff, 0xff));
            ds.Flush();
            ds.Dispose();

            // set to container
            var brush  = _compositor.CreateSurfaceBrush(_drawsurface);
            var sprite = _compositor.CreateSpriteVisual();
            sprite.Brush = brush;
            sprite.Size  = _size;
            _shape.Children.InsertAtTop(sprite);
        }
Esempio n. 17
0
        /// <summary>

        /// Creates an instance of the ColorBloomTransitionHelper.

        /// Any visuals to be later created and animated will be hosted within the specified UIElement.

        /// </summary>

        public ColorBloomTransitionHelper(UIElement hostForVisual)

        {
            this.hostForVisual = hostForVisual;



            // we have an element in the XAML tree that will host our Visuals

            var visual = ElementCompositionPreview.GetElementVisual(hostForVisual);

            _compositor = visual.Compositor;



            // create a container

            // adding children to this container adds them to the live visual tree

            _containerForVisuals = _compositor.CreateContainerVisual();

            ElementCompositionPreview.SetElementChildVisual(hostForVisual, _containerForVisuals);
            _canvasDevice   = new CanvasDevice();
            _graphicsDevice = CanvasComposition.CreateCompositionGraphicsDevice(_compositor, _canvasDevice);

            // Create the circle mask

            _circleMaskSurface = LoadCircle(200, Colors.White);
        }
Esempio n. 18
0
        private void Setup()
        {
            _canvasDevice = new CanvasDevice();

            _compositionGraphicsDevice = CanvasComposition.CreateCompositionGraphicsDevice(
                Windows.UI.Xaml.Window.Current.Compositor,
                _canvasDevice);

            _compositor = Windows.UI.Xaml.Window.Current.Compositor;

            _surface = _compositionGraphicsDevice.CreateDrawingSurface(
                new Windows.Foundation.Size(400, 400),
                DirectXPixelFormat.B8G8R8A8UIntNormalized,
                DirectXAlphaMode.Premultiplied);    // This is the only value that currently works with
                                                    // the composition APIs.

            var visual = _compositor.CreateSpriteVisual();

            visual.RelativeSizeAdjustment = Vector2.One;
            var brush = _compositor.CreateSurfaceBrush(_surface);

            brush.HorizontalAlignmentRatio = 0.5f;
            brush.VerticalAlignmentRatio   = 0.5f;
            brush.Stretch = CompositionStretch.Uniform;
            visual.Brush  = brush;
            ElementCompositionPreview.SetElementChildVisual(this, visual);
            StartCaptureInternal(MainPage.targetcap);
        }
Esempio n. 19
0
        public Screenshot()
        {
            _canvasDevice = new CanvasDevice();

            _compositionGraphicsDevice = CanvasComposition.CreateCompositionGraphicsDevice(
                Window.Current.Compositor,
                _canvasDevice);

            _compositor = Window.Current.Compositor;

            _surface = _compositionGraphicsDevice.CreateDrawingSurface(
                new Size(400, 400),
                DirectXPixelFormat.B8G8R8A8UIntNormalized,
                DirectXAlphaMode.Premultiplied);    // This is the only value that currently works with
                                                    // the composition APIs.

            //var visual = _compositor.CreateSpriteVisual();
            //visual.RelativeSizeAdjustment = Vector2.One;
            //var brush = _compositor.CreateSurfaceBrush(_surface);
            //brush.HorizontalAlignmentRatio = 0.5f;
            //brush.VerticalAlignmentRatio = 0.5f;
            //brush.Stretch = CompositionStretch.Uniform;
            //visual.Brush = brush;
            //ElementCompositionPreview.SetElementChildVisual(this, visual);
        }
Esempio n. 20
0
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="compositor">Compositor</param>
        /// <param name="useSharedCanvasDevice">Whether to use a shared CanvasDevice or to create a new one.</param>
        /// <param name="useSoftwareRenderer">Whether to use Software Renderer when creating a new CanvasDevice.</param>
        public CompositionGenerator(Compositor compositor, bool useSharedCanvasDevice = true, bool useSoftwareRenderer = false)
        {
            if (compositor == null)
            {
                throw new ArgumentNullException(nameof(compositor), "Compositor cannot be null!");
            }

            // Compositor
            _compositor = compositor;

            // Disposing Lock
            _disposingLock = new object();

            // Canvas Device
            _canvasDevice = useSharedCanvasDevice ?
                            CanvasDevice.GetSharedDevice() : new CanvasDevice(useSoftwareRenderer);
            _isCanvasDeviceCreator = !useSharedCanvasDevice;

            _canvasDevice.DeviceLost += DeviceLost;

            // Composition Graphics Device
            _graphicsDevice          = CanvasComposition.CreateCompositionGraphicsDevice(_compositor, _canvasDevice);
            _isGraphicsDeviceCreator = true;

            _graphicsDevice.RenderingDeviceReplaced += RenderingDeviceReplaced;
            if (!DesignMode.DesignModeEnabled)
            {
                DisplayInformation.DisplayContentsInvalidated += OnDisplayContentsInvalidated;
            }
        }
        /// <summary>
        /// Initializes the Composition Brush.
        /// </summary>
        protected override void OnConnected()
        {
            base.OnConnected();

            // Delay creating composition resources until they're required.
            if (CompositionBrush == null)
            {
                // Abort if effects aren't supported.
                if (!CompositionCapabilities.GetForCurrentView().AreEffectsSupported())
                {
                    return;
                }

                var size = new Vector2(SurfaceWidth, SurfaceHeight);

                var device   = CanvasDevice.GetSharedDevice();
                var graphics = CanvasComposition.CreateCompositionGraphicsDevice(Window.Current.Compositor, device);

                var surface = graphics.CreateDrawingSurface(size.ToSize(), DirectXPixelFormat.B8G8R8A8UIntNormalized, DirectXAlphaMode.Premultiplied);

                using (var session = CanvasComposition.CreateDrawingSession(surface))
                {
                    // Call Implementor to draw on session.
                    if (!OnDraw(device, session, size))
                    {
                        return;
                    }
                }

                _surfaceBrush         = Window.Current.Compositor.CreateSurfaceBrush(surface);
                _surfaceBrush.Stretch = CompositionStretch.Fill;

                CompositionBrush = _surfaceBrush;
            }
        }
Esempio n. 22
0
        public async Task DrawSurface(CompositionDrawingSurface surface, Uri uri, Size size)
        {
            var canvasDevice = CanvasComposition.GetCanvasDevice(_graphicsDevice);

            using (var canvasBitmap = await CanvasBitmap.LoadAsync(canvasDevice, uri))
            {
                var bitmapSize = canvasBitmap.Size;

                //
                // Because the drawing is done asynchronously and multiple threads could
                // be trying to get access to the device/surface at the same time, we need
                // to do any device/surface work under a lock.
                //
                lock (_drawingLock)
                {
                    Size surfaceSize = size;
                    if (surfaceSize.IsEmpty)
                    {
                        // Resize the surface to the size of the image
                        CanvasComposition.Resize(surface, bitmapSize);
                        surfaceSize = bitmapSize;
                    }

                    // Draw the image to the surface
                    using (var session = CanvasComposition.CreateDrawingSession(surface))
                    {
                        session.Clear(Windows.UI.Color.FromArgb(0, 0, 0, 0));
                        session.DrawImage(canvasBitmap, new Rect(0, 0, surfaceSize.Width, surfaceSize.Height), new Rect(0, 0, bitmapSize.Width, bitmapSize.Height));
                    }
                }
            }
        }
        private void CompositionHostControl_Loaded(object sender, RoutedEventArgs e)
        {
            _currentDpi = WindowsMedia.VisualTreeHelper.GetDpi(this);

            _rectWidth  = CompositionHostElement.ActualWidth / 2;
            _rectHeight = CompositionHostElement.ActualHeight / 2;

            // Get graphics device.
            _compositionGraphicsDevice = CanvasComposition.CreateCompositionGraphicsDevice(_compositor, _canvasDevice);

            // Create surface.
            var noiseDrawingSurface = _compositionGraphicsDevice.CreateDrawingSurface(
                new Windows.Foundation.Size(_rectWidth, _rectHeight),
                DirectXPixelFormat.B8G8R8A8UIntNormalized,
                DirectXAlphaMode.Premultiplied);

            // Draw to surface and create surface brush.
            var noiseFilePath = AppDomain.CurrentDomain.BaseDirectory + "Assets\\NoiseAsset_256X256.png";

            LoadSurface(noiseDrawingSurface, noiseFilePath);
            _noiseSurfaceBrush = _compositor.CreateSurfaceBrush(noiseDrawingSurface);

            // Add composition content to tree.
            _compositionHost.SetChild(_containerVisual);
            AddCompositionContent();

            ToggleAcrylic();
        }
Esempio n. 24
0
        internal void ReDraw(Rect viewPort, float zoom)
        {
            var toDraw = GetDrawingBoundaries(viewPort);
            var scale  = _screenScale * zoom;
            var rect   = ScaleRect(toDraw, scale);
            var dpi    = BaseCanvasDPI * (float)scale;

            try
            {
                using (var drawingSession = CanvasComposition.CreateDrawingSession(_drawingSurface, rect, dpi))
                {
                    drawingSession.Clear(Colors.White);
                    foreach (var drawable in _visibleList)
                    {
                        drawable.Draw(drawingSession, toDraw);
                    }
                }
            }
            catch (ArgumentException)
            {
                /* CanvasComposition.CreateDrawingSession has an internal
                 * limit on the size of the updateRectInPixels parameter,
                 * which we don't know, so we can get an ArgumentException
                 * if there is a lot of extreme zooming and panning
                 * Therefore, the only solution is to silently catch the
                 * exception and allow the app to continue
                 */
            }
        }
Esempio n. 25
0
 public async Task Draw(CompositionGraphicsDevice device, Object drawingLock, CompositionDrawingSurface surface, Size size)
 {
     using (var ds = CanvasComposition.CreateDrawingSession(surface)) {
         ds.Clear(_backgroundColor);
         ds.DrawText(_text, new Rect(0, 0, surface.Size.Width, surface.Size.Height), _textColor, _textFormat);
     }
 }
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="compositor">Compositor</param>
        /// <param name="graphicsDevice">CompositionGraphicsDevice</param>
        /// <param name="sharedLock">shared lock</param>
        public CompositionMaskGenerator(Compositor compositor, CompositionGraphicsDevice graphicsDevice = null,
                                        object sharedLock = null)
        {
            if (compositor == null)
            {
                throw new ArgumentNullException(nameof(compositor), "Compositor cannot be null!");
            }

            _compositor  = compositor;
            _drawingLock = sharedLock ?? new object();

            if (_canvasDevice == null)
            {
                _canvasDevice             = CanvasDevice.GetSharedDevice();
                _canvasDevice.DeviceLost += DeviceLost;
            }

            if (graphicsDevice == null)
            {
                // Create the Composition Graphics Device
                _graphicsDevice  = CanvasComposition.CreateCompositionGraphicsDevice(_compositor, _canvasDevice);
                _isDeviceCreator = true;
            }
            else
            {
                _graphicsDevice  = graphicsDevice;
                _isDeviceCreator = false;
            }

            // Subscribe to events
            _graphicsDevice.RenderingDeviceReplaced       += RenderingDeviceReplaced;
            DisplayInformation.DisplayContentsInvalidated += OnDisplayContentsInvalidated;
        }
Esempio n. 27
0
 public void InitializeComposition()
 {
     compositor  = ElementCompositionPreview.GetElementVisual(this as UIElement).Compositor;
     win2dDevice = CanvasDevice.GetSharedDevice();
     comositionGraphicsDevice = CanvasComposition.CreateCompositionGraphicsDevice(compositor, win2dDevice);
     myDrawingVisual          = compositor.CreateSpriteVisual();
     ElementCompositionPreview.SetElementChildVisual(virtualSurfaceHost, myDrawingVisual);
 }
 internal void InitializeComposition()
 {
     _compositor  = ElementCompositionPreview.GetElementVisual(this).Compositor;
     _win2DDevice = CanvasDevice.GetSharedDevice();
     _comositionGraphicsDevice = CanvasComposition.CreateCompositionGraphicsDevice(_compositor, _win2DDevice);
     _myDrawingVisual          = _compositor.CreateSpriteVisual();
     ElementCompositionPreview.SetElementChildVisual(this, _myDrawingVisual);
 }
Esempio n. 29
0
 void DrawSoftwareBitmap(SoftwareBitmap softwareBitmap, Size renderSize)
 {
     using (var drawingSession = CanvasComposition.CreateDrawingSession(_drawingSurface))
         using (var bitmap = CanvasBitmap.CreateFromSoftwareBitmap(drawingSession.Device, softwareBitmap))
         {
             drawingSession.DrawImage(bitmap,
                                      new Rect(0, 0, renderSize.Width, renderSize.Height));
         }
 }
        /// <summary>
        /// Handles the DeviceLost event
        /// </summary>
        /// <param name="sender">CanvasDevice</param>
        /// <param name="args">event arguments</param>
        private void DeviceLost(CanvasDevice sender, object args)
        {
            sender.DeviceLost -= DeviceLost;

            _canvasDevice             = CanvasDevice.GetSharedDevice();
            _canvasDevice.DeviceLost += DeviceLost;

            CanvasComposition.SetCanvasDevice(_graphicsDevice, _canvasDevice);
        }