示例#1
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);
        }
        private CompositionDrawingSurface ApplyBlurEffect(CanvasBitmap bitmap, CompositionGraphicsDevice device, Size sizeTarget)
        {
            GaussianBlurEffect blurEffect = new GaussianBlurEffect()
            {
                Source     = bitmap,
                BlurAmount = 10.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.DrawImage(blurEffect, destination, new Rect(0, 0, sizeSource.Width, sizeSource.Height));
                ds.FillRectangle(destination, Windows.UI.Color.FromArgb(60, 0, 0, 0));
            }

            return(blurSurface);
        }
        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();
        }
        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);
        }
示例#5
0
        private CompositionDrawingSurface CreateSurface(Size size)

        {
            Size surfaceSize = size;

            if (surfaceSize.IsEmpty)

            {
                //

                // We start out with a size of 0,0 for the surface, because we don't know

                // the size of the image at this time. We resize the surface later.

                //

                surfaceSize = default(Size);
            }



            var surface = _graphicsDevice.CreateDrawingSurface(surfaceSize, DirectXPixelFormat.B8G8R8A8UIntNormalized, DirectXAlphaMode.Premultiplied);



            return(surface);
        }
        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();
        }
示例#7
0
 void CreateDrawingSurface(global::Windows.Foundation.Size drawSize)
 {
     _drawingSurface = _graphicsDevice.CreateDrawingSurface(
         drawSize,
         DirectXPixelFormat.B8G8R8A8UIntNormalized,
         DirectXAlphaMode.Premultiplied);
 }
示例#8
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);
        }
        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);
                    }
                }
        }
        public ICompositionDrawingSurfaceInterop InitialiseWindowCompositionTree(IntPtr hwnd, out Windows.UI.Composition.Visual surfaceVisual, out IBlurHost blurHost)
        {
            var target = CreateDesktopWindowTarget(hwnd);

            var surface = _graphicsDevice.CreateDrawingSurface(new Windows.Foundation.Size(0, 0),
                                                               Windows.Graphics.DirectX.DirectXPixelFormat.B8G8R8A8UIntNormalized,
                                                               Windows.Graphics.DirectX.DirectXAlphaMode.Premultiplied);

            var surfaceInterop = surface.As <ICompositionDrawingSurfaceInterop>();

            var brush  = _compositor.CreateSurfaceBrush(surface);
            var visual = _compositor.CreateSpriteVisual();

            visual.Brush = brush;
            visual.RelativeSizeAdjustment = new System.Numerics.Vector2(1, 1);

            var container = _compositor.CreateContainerVisual();

            target.Root = container;

            var blur = CreateBlur();

            blurHost = new CompositionBlurHost(blur);

            container.Children.InsertAtTop(blur);

            container.Children.InsertAtTop(visual);

            visual.CompositeMode = CompositionCompositeMode.SourceOver;

            surfaceVisual = container;

            return(surfaceInterop);
        }
示例#11
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);
        }
示例#12
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);
        }
        protected override void OnConnected()
        {
            if (CompositionBrush == null)
            {
                IsConnected    = true;
                canvasDevice   = CanvasDevice.GetSharedDevice();
                graphicsDevice = CanvasComposition.CreateCompositionGraphicsDevice(Compositor, canvasDevice);
                surface1       = graphicsDevice.CreateDrawingSurface(
                    new Windows.Foundation.Size(100, 100),
                    Windows.Graphics.DirectX.DirectXPixelFormat.B8G8R8A8UIntNormalized,
                    Windows.Graphics.DirectX.DirectXAlphaMode.Premultiplied);
                surface2 = graphicsDevice.CreateDrawingSurface(
                    new Windows.Foundation.Size(100, 100),
                    Windows.Graphics.DirectX.DirectXPixelFormat.B8G8R8A8UIntNormalized,
                    Windows.Graphics.DirectX.DirectXAlphaMode.Premultiplied);
                surfaceBrush1         = Compositor.CreateSurfaceBrush(surface1);
                surfaceBrush2         = Compositor.CreateSurfaceBrush(surface2);
                surfaceBrush1.Stretch = CompositionStretch.Fill;
                surfaceBrush2.Stretch = CompositionStretch.Fill;

                colorBrush1 = Compositor.CreateColorBrush();
                colorBrush2 = Compositor.CreateColorBrush();

                Source1Animation = Compositor.CreateScalarKeyFrameAnimation();
                Source1Animation.InsertKeyFrame(0f, 1f);
                Source1Animation.InsertKeyFrame(1f, 0f);
                Source1Animation.Duration = Duration;

                Source2Animation = Compositor.CreateScalarKeyFrameAnimation();
                Source2Animation.InsertKeyFrame(0f, 0f);
                Source2Animation.InsertKeyFrame(1f, 1f);
                Source2Animation.Duration = Duration;

                var effect = new ArithmeticCompositeEffect()
                {
                    Name           = "effect",
                    Source1        = new CompositionEffectSourceParameter("source1"),
                    Source2        = new CompositionEffectSourceParameter("source2"),
                    Source1Amount  = 1f,
                    Source2Amount  = 0f,
                    MultiplyAmount = 0,
                };
                CompositionBrush = Compositor.CreateEffectFactory(effect, new[] { "effect.Source1Amount", "effect.Source2Amount" }).CreateBrush();
            }
        }
示例#14
0
        public DrawingSurfaceRenderer(Compositor compositor, CompositionGraphicsDevice compositionGraphicsDevice)
        {
            drawingSurfaceVisual = compositor.CreateSpriteVisual();
            drawingSurface = compositionGraphicsDevice.CreateDrawingSurface(new Size(256, 256), DirectXPixelFormat.B8G8R8A8UIntNormalized, DirectXAlphaMode.Premultiplied);
            drawingSurfaceVisual.Brush = compositor.CreateSurfaceBrush(drawingSurface);
            DrawDrawingSurface();

            compositionGraphicsDevice.RenderingDeviceReplaced += CompositionGraphicsDevice_RenderingDeviceReplaced;
        }
示例#15
0
        public DrawingSurfaceRenderer(Compositor compositor, CompositionGraphicsDevice compositionGraphicsDevice)
        {
            drawingSurfaceVisual       = compositor.CreateSpriteVisual();
            drawingSurface             = compositionGraphicsDevice.CreateDrawingSurface(new Size(256, 256), DirectXPixelFormat.B8G8R8A8UIntNormalized, DirectXAlphaMode.Premultiplied);
            drawingSurfaceVisual.Brush = compositor.CreateSurfaceBrush(drawingSurface);
            DrawDrawingSurface();

            compositionGraphicsDevice.RenderingDeviceReplaced += CompositionGraphicsDevice_RenderingDeviceReplaced;
        }
示例#16
0
            public TextDrawer(CompositionGraphicsDevice device)
            {
                DrawingSurface = device.CreateDrawingSurface(
                    new Size(1000, 200),
                    Windows.Graphics.DirectX.DirectXPixelFormat.B8G8R8A8UIntNormalized,
                    Windows.Graphics.DirectX.DirectXAlphaMode.Premultiplied);

                //this.text = text;
                //this.fontFamily = fontFamily;
                Draw();
            }
示例#17
0
        public void OnInitialization()
        {
            //LND
            lnd = new LEDandDisplay(50, 30, 16, "COM6", 1650, 1050, false, 50);
            Update();

            //WriteSittings();
            ReadSittings();
            ShowSittings();
            //rec
            _canvasDevice = new CanvasDevice();
            _compositionGraphicsDevice = CanvasComposition.CreateCompositionGraphicsDevice(
                Window.Current.Compositor,
                _canvasDevice);

            //framerate
            dt = DateTime.Now;

            //Arduino
            ArduinoInit();

            //background
            bgndSession        = new ExtendedExecutionSession();
            bgndSession.Reason = ExtendedExecutionReason.Unspecified;

            //drawing
            _compositor = Window.Current.Compositor;

            _surface = _compositionGraphicsDevice.CreateDrawingSurface(
                new Size(100, 100),
                DirectXPixelFormat.B8G8R8A8UIntNormalized,
                DirectXAlphaMode.Premultiplied);
            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);
            if (!GraphicsCaptureSession.IsSupported())
            {
                CaptureButton.Visibility = Visibility.Collapsed;
            }
            //autostart
            if (lnd.autostart == true)
            {
                _item = lnd.item;
                //StartCaptureInternal(lnd.item);
                StartCaptureAsync();
            }
        }
示例#18
0
        private static async Task <CompositionSurfaceBrush> LoadWin2DSurfaceBrushFromImageAsync(
            [NotNull] Compositor compositor, [NotNull] Uri uri, bool reload = false)
        {
            // Lock the semaphore and check the cache first
            await Win2DSemaphore.WaitAsync();

            if (!reload && SurfacesCache.TryGetValue(uri.ToString(), out CompositionSurfaceBrush cached))
            {
                Win2DSemaphore.Release();
                return(cached);
            }

            // Load the image
            CompositionSurfaceBrush brush;

            try
            {
                // This will throw and the canvas will re-initialize the Win2D device if needed
                CanvasDevice sharedDevice = CanvasDevice.GetSharedDevice();
                using (CanvasBitmap bitmap = await CanvasBitmap.LoadAsync(sharedDevice, uri))
                {
                    // Get the device and the target surface
                    CompositionGraphicsDevice device  = CanvasComposition.CreateCompositionGraphicsDevice(compositor, sharedDevice);
                    CompositionDrawingSurface surface = device.CreateDrawingSurface(default(Size),
                                                                                    DirectXPixelFormat.B8G8R8A8UIntNormalized, DirectXAlphaMode.Premultiplied);

                    // Calculate the surface size
                    Size size = bitmap.Size;
                    CanvasComposition.Resize(surface, size);

                    // Draw the image on the surface and get the resulting brush
                    using (CanvasDrawingSession session = CanvasComposition.CreateDrawingSession(surface))
                    {
                        session.Clear(Color.FromArgb(0, 0, 0, 0));
                        session.DrawImage(bitmap, new Rect(0, 0, size.Width, size.Height), new Rect(0, 0, size.Width, size.Height));
                        brush = surface.Compositor.CreateSurfaceBrush(surface);
                    }
                }
            }
            catch
            {
                // Device error
                brush = null;
            }
            String key = uri.ToString();

            if (brush != null && !SurfacesCache.ContainsKey(key))
            {
                SurfacesCache.Add(key, brush);
            }
            Win2DSemaphore.Release();
            return(brush);
        }
示例#19
0
        static public async Task <CompositionDrawingSurface> LoadFromUri(Uri uri)
        {
            CanvasBitmap CBitmap = await CanvasBitmap.LoadAsync(_canvasDevice, uri);

            CompositionDrawingSurface DrawingSurface = _compositionDevice.CreateDrawingSurface(CBitmap.Size, DirectXPixelFormat.B8G8R8A8UIntNormalized, DirectXAlphaMode.Premultiplied);

            using (CanvasDrawingSession DraingSession = CanvasComposition.CreateDrawingSession(DrawingSurface))
            {
                DraingSession.Clear(Color.FromArgb(0, 0, 0, 0));
                DraingSession.DrawImage(CBitmap, new Rect(0, 0, CBitmap.Size.Width, CBitmap.Size.Height));
            }

            return(DrawingSurface);
        }
        static public async Task <CompositionDrawingSurface> LoadFromUri(Uri uri, Size sizeTarget)
        {
            Debug.Assert(_intialized);

            CanvasBitmap bitmap = await CanvasBitmap.LoadAsync(_canvasDevice, uri);

            Size sizeSource = bitmap.Size;

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

            CompositionDrawingSurface 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));
            }

            return(surface);
        }
示例#21
0
        /// <summary>
        /// Initializes the Composition Brush.
        /// </summary>
        protected override void OnConnected()
        {
            base.OnConnected();

            if (_device != null)
            {
                _device.DeviceLost -= CanvasDevice_DeviceLost;
            }

            _device             = CanvasDevice.GetSharedDevice();
            _device.DeviceLost += CanvasDevice_DeviceLost;

            if (_graphics != null)
            {
                _graphics.RenderingDeviceReplaced -= CanvasDevice_RenderingDeviceReplaced;
            }

            _graphics = CanvasComposition.CreateCompositionGraphicsDevice(Window.Current.Compositor, _device);
            _graphics.RenderingDeviceReplaced += CanvasDevice_RenderingDeviceReplaced;

            // 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 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;
            }
        }
        public CompositionBrush CreateShadowMask(object sender, Size size, Compositor compositor, CompositionGraphicsDevice device)
        {
            if (size.Width == 0 && size.Height == 0)
            {
                return(null);
            }

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

            using (var drawingSession = CanvasComposition.CreateDrawingSession(surface))
            {
                drawingSession.Clear(Colors.Transparent);
                var center = size.ToVector2() / 2.0f;
                var radius = center.X > center.Y ? center.Y : center.X;
                drawingSession.FillCircle(center, radius, Color.FromArgb(255, 255, 255, 255));
            }
            return(compositor.CreateSurfaceBrush(surface));
        }
示例#23
0
 private void Draw(bool IsFill, Color color)
 {
     _surface = _graphicsDevice.CreateDrawingSurface(Size.ToSize(), Windows.Graphics.DirectX.DirectXPixelFormat.B8G8R8A8UIntNormalized, Windows.Graphics.DirectX.DirectXAlphaMode.Premultiplied);
     using (var dc = CanvasComposition.CreateDrawingSession(_surface))
     {
         dc.Clear(Colors.Transparent);
         if (IsFill)
         {
             dc.FillCircle(Size / 2, Size.X / 2, color);
         }
         else
         {
             dc.DrawCircle(Size / 2, Size.X / 2 - 2, color, 2f);
         }
         dc.Flush();
     }
     _brush        = _compositor.CreateSurfaceBrush(_surface);
     _visual.Brush = _brush;
 }
 private static async Task <CompositionDrawingSurface> GetCompositionDrawingSurface(Compositor compositor, RenderTargetBitmap renderTargetBitmap)
 {
     using (var canvasDevice = new CanvasDevice())
         using (CompositionGraphicsDevice graphicsDevice = CanvasComposition.CreateCompositionGraphicsDevice(compositor, canvasDevice))
             using (CanvasBitmap canvasBitmap = await GetCanvasBitmap(renderTargetBitmap, canvasDevice))
             {
                 CompositionDrawingSurface surface = graphicsDevice.CreateDrawingSurface(
                     new Size(canvasBitmap.Size.Width, canvasBitmap.Size.Height),
                     DirectXPixelFormat.B8G8R8A8UIntNormalized, DirectXAlphaMode.Ignore);
                 using (CanvasDrawingSession session = CanvasComposition.CreateDrawingSession(surface))
                 {
                     session.Clear(Color.FromArgb(0, 0, 0, 0));
                     session.DrawImage(canvasBitmap,
                                       new Rect(0, 0, surface.Size.Width, surface.Size.Height),
                                       new Rect(0, 0, canvasBitmap.Size.Width, canvasBitmap.Size.Height));
                 }
                 return(surface);
             }
 }
        public TextToBrushWrapper()
        {
            _graphicsDevice   = CanvasComposition.CreateCompositionGraphicsDevice(Compositor, CanvasDevice.GetSharedDevice());
            _spriteTextVisual = Compositor.CreateSpriteVisual();
            DrawingSurface    = _graphicsDevice.CreateDrawingSurface(new Windows.Foundation.Size(10, 10), DirectXPixelFormat.B8G8R8A8UIntNormalized, DirectXAlphaMode.Premultiplied);
            Brush             = Compositor.CreateSurfaceBrush(DrawingSurface);
            RegisterPropertyChangedCallback(FontSizeProperty, new DependencyPropertyChangedCallback((s, e) =>
            {
                DrawSurface();
            }));
            RegisterPropertyChangedCallback(BackgroundProperty, new DependencyPropertyChangedCallback((s, e) =>
            {
                DrawSurface();
            }));
            RegisterPropertyChangedCallback(HeightProperty, new DependencyPropertyChangedCallback((s, e) =>
            {
                if (double.IsNaN(Height) || double.IsNaN(Width) || Width == 0 || Height == 0)
                {
                    return;
                }

                DrawingSurface.Resize(new Windows.Graphics.SizeInt32 {
                    Width = (int)Width, Height = (int)Height
                });
                DrawSurface();
            }));

            RegisterPropertyChangedCallback(WidthProperty, new DependencyPropertyChangedCallback((s, e) =>
            {
                if (double.IsNaN(Height) || double.IsNaN(Width) || Width == 0 || Height == 0)
                {
                    return;
                }

                DrawingSurface.Resize(new Windows.Graphics.SizeInt32 {
                    Width = (int)Width, Height = (int)Height
                });
                DrawSurface();
            }));
        }
示例#26
0
        /// <summary>
        /// Creates a CompositionDrawingSurface of given size
        /// </summary>
        /// <param name="surfaceLock">The object to lock to prevent multiple threads
        /// from accessing the surface at the same time.</param>
        /// <param name="size">Size of the CompositionDrawingSurface</param>
        /// <returns>CompositionDrawingSurface</returns>
        public CompositionDrawingSurface CreateDrawingSurface(object surfaceLock, Size size)
        {
            var surfaceSize = size;

            if (surfaceSize.IsEmpty)
            {
                //
                // We start out with a size of 0,0 for the surface, because we don't know
                // the size of the image at this time. We resize the surface later.
                //
                surfaceSize = new Size(0, 0);
            }

            //
            // Since 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 (surfaceLock)
            {
                return(_graphicsDevice.CreateDrawingSurface(surfaceSize, DirectXPixelFormat.B8G8R8A8UIntNormalized, DirectXAlphaMode.Premultiplied));
            }
        }
示例#27
0
        void OnLoading(object sender, object args)
        {
            // DirectX layer
            _device     = CanvasDevice.GetSharedDevice();
            _compositor = ElementCompositionPreview.GetElementVisual(this).Compositor;

            // create text format
            using CanvasTextFormat textformat = new CanvasTextFormat
                  {
                      FontFamily          = FontFamily.Source,
                      FontSize            = (float)FontSize,
                      FontWeight          = FontWeight,
                      WordWrapping        = CanvasWordWrapping.NoWrap,
                      LineSpacingMode     = CanvasLineSpacingMode.Proportional, // no option to make it properly centered.
                      LineSpacing         = 0.4f,
                      LineSpacingBaseline = 0.6f,
                      HorizontalAlignment = CanvasHorizontalAlignment.Center,
                      VerticalAlignment   = CanvasVerticalAlignment.Center
                  };
            using CanvasTextLayout textLayout = new CanvasTextLayout(_device, Text, textformat, 0, 0);

            if (this.Width < textLayout.LayoutBounds.Width)
            {
                this.Width = textLayout.LayoutBounds.Width + 20;
            }

            _size = new Vector2((float)Width, (float)Height);

            _shape      = _compositor.CreateShapeVisual();
            _shape.Size = _size;

            _graphdevice = CanvasComposition.CreateCompositionGraphicsDevice(_compositor, _device);
            _drawsurface = _graphdevice.CreateDrawingSurface(new Size(Width, Height), DirectXPixelFormat.B8G8R8A8UIntNormalized, DirectXAlphaMode.Premultiplied);

            DrawText(textLayout);
            DrawShape();

            ElementCompositionPreview.SetElementChildVisual(this, _shape);
        }
        /// <summary>
        /// Creates a CompositionDrawingSurface of given size
        /// </summary>
        /// <param name="size">Size of the CompositionDrawingSurface</param>
        /// <returns>CompositionDrawingSurface</returns>
        public CompositionDrawingSurface CreateMaskSurface(Size size)
        {
            var surfaceSize = size;

            if (surfaceSize.IsEmpty)
            {
                //
                // We start out with a size of 0,0 for the surface, because we don't know
                // the size of the image at this time. We resize the surface later.
                //
                surfaceSize = new Size(0, 0);
            }

            CompositionDrawingSurface surface;

            lock (_drawingLock)
            {
                surface = _graphicsDevice.CreateDrawingSurface(surfaceSize, DirectXPixelFormat.B8G8R8A8UIntNormalized, DirectXAlphaMode.Premultiplied);
            }

            return(surface);
        }
        private CompositionDrawingSurface ApplyBlurEffect(CanvasBitmap bitmap, CompositionGraphicsDevice device, Size sizeTarget)
        {
            GaussianBlurEffect blurEffect = new GaussianBlurEffect()
            {
                Source = bitmap,
                BlurAmount = 10.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.DrawImage(blurEffect, destination, new Rect(0, 0, sizeSource.Width, sizeSource.Height));
                ds.FillRectangle(destination, Windows.UI.Color.FromArgb(60, 0, 0, 0));
            }

            return blurSurface;
        }
        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;
        }
示例#31
0
        private static async Task <CompositionSurfaceBrush> LoadWin2DSurfaceBrushFromImageAsync(
            [NotNull] Compositor compositor, [NotNull] CanvasControl canvas, [NotNull] Uri uri, int timeThreshold = 1000, bool reload = false)
        {
            TaskCompletionSource <CompositionSurfaceBrush> tcs = new TaskCompletionSource <CompositionSurfaceBrush>();

            async Task <CompositionSurfaceBrush> LoadImageAsync(bool shouldThrow)
            {
                // Load the image - this will only succeed when there's an available Win2D device
                try
                {
                    using (CanvasBitmap bitmap = await CanvasBitmap.LoadAsync(canvas, uri))
                    {
                        // Get the device and the target surface
                        CompositionGraphicsDevice device  = CanvasComposition.CreateCompositionGraphicsDevice(compositor, canvas.Device);
                        CompositionDrawingSurface surface = device.CreateDrawingSurface(default(Size),
                                                                                        DirectXPixelFormat.B8G8R8A8UIntNormalized, DirectXAlphaMode.Premultiplied);

                        // Calculate the surface size
                        Size size = bitmap.Size;
                        CanvasComposition.Resize(surface, size);

                        // Draw the image on the surface and get the resulting brush
                        using (CanvasDrawingSession session = CanvasComposition.CreateDrawingSession(surface))
                        {
                            session.Clear(Color.FromArgb(0, 0, 0, 0));
                            session.DrawImage(bitmap, new Rect(0, 0, size.Width, size.Height), new Rect(0, 0, size.Width, size.Height));
                            CompositionSurfaceBrush brush = surface.Compositor.CreateSurfaceBrush(surface);
                            return(brush);
                        }
                    }
                }
                catch when(!shouldThrow)
                {
                    // Win2D error, just ignore and continue
                    return(null);
                }
            }

            async void Canvas_CreateResources(CanvasControl sender, CanvasCreateResourcesEventArgs args)
            {
                // Cancel previous actions
                args.GetTrackedAction()?.Cancel();

                // Load the image and notify the canvas
                Task <CompositionSurfaceBrush> task = LoadImageAsync(false);
                IAsyncAction action = task.AsAsyncAction();

                try
                {
                    args.TrackAsyncAction(action);
                    CompositionSurfaceBrush brush = await task;
                    action.Cancel();
                    tcs.TrySetResult(brush);
                }
                catch (COMException)
                {
                    // Somehow another action was still being tracked
                    tcs.TrySetResult(null);
                }
            }

            // Lock the semaphore and check the cache first
            await Win2DSemaphore.WaitAsync();

            if (!reload && SurfacesCache.TryGetValue(uri.ToString(), out CompositionSurfaceBrush cached))
            {
                Win2DSemaphore.Release();
                return(cached);
            }

            // Load the image
            canvas.CreateResources += Canvas_CreateResources;
            try
            {
                // This will throw and the canvas will re-initialize the Win2D device if needed
                await LoadImageAsync(true);
            }
            catch (ArgumentException)
            {
                // Just ignore here
            }
            catch
            {
                // Win2D messed up big time
                tcs.TrySetResult(null);
            }
            await Task.WhenAny(tcs.Task, Task.Delay(timeThreshold).ContinueWith(t => tcs.TrySetResult(null)));

            canvas.CreateResources -= Canvas_CreateResources;
            CompositionSurfaceBrush instance = tcs.Task.Result;
            String key = uri.ToString();

            if (instance != null && !SurfacesCache.ContainsKey(key))
            {
                SurfacesCache.Add(key, instance);
            }
            Win2DSemaphore.Release();
            return(instance);
        }
        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;
        }
示例#33
0
        /// <summary>
        /// Loads a <see cref="CompositionBrush"/> from the input <see cref="System.Uri"/>, and prepares it to be used in a tile effect
        /// </summary>
        /// <param name="canvasDevice">The device to use to process the Win2D image</param>
        /// <param name="compositor">The compositor instance to use to create the final brush</param>
        /// <param name="uri">The path to the image to load</param>
        /// <param name="dpiMode">Indicates the desired DPI mode to use when loading the image</param>
        /// <returns>A <see cref="Task{T}"/> that returns the loaded <see cref="CompositionBrush"/> instance</returns>
        private static async Task <CompositionBrush> LoadSurfaceBrushAsync(
            CanvasDevice canvasDevice,
            Compositor compositor,
            Uri uri,
            DpiMode dpiMode)
        {
            var   displayInformation = DisplayInformation.GetForCurrentView();
            float dpi = displayInformation.LogicalDpi;

            // Load the bitmap with the appropriate settings
            using CanvasBitmap bitmap = dpiMode switch
                  {
                      DpiMode.UseSourceDpi => await CanvasBitmap.LoadAsync(canvasDevice, uri),
                      DpiMode.Default96Dpi => await CanvasBitmap.LoadAsync(canvasDevice, uri, 96),
                      DpiMode.DisplayDpi => await CanvasBitmap.LoadAsync(canvasDevice, uri, dpi),
                      DpiMode.DisplayDpiWith96AsLowerBound => await CanvasBitmap.LoadAsync(canvasDevice, uri, dpi >= 96?dpi : 96),
                      _ => throw new ArgumentOutOfRangeException(nameof(dpiMode), dpiMode, $"Invalid DPI mode: {dpiMode}")
                  };

            // Calculate the surface size
            Size
                size         = bitmap.Size,
                sizeInPixels = new Size(bitmap.SizeInPixels.Width, bitmap.SizeInPixels.Height);

            // Get the device and the target surface
            using CompositionGraphicsDevice graphicsDevice = CanvasComposition.CreateCompositionGraphicsDevice(compositor, canvasDevice);

            // Create the drawing surface
            var drawingSurface = graphicsDevice.CreateDrawingSurface(
                sizeInPixels,
                DirectXPixelFormat.B8G8R8A8UIntNormalized,
                DirectXAlphaMode.Premultiplied);

            // Create a drawing session for the target surface
            using (var drawingSession = CanvasComposition.CreateDrawingSession(drawingSurface, new Rect(0, 0, sizeInPixels.Width, sizeInPixels.Height), dpi))
            {
                // Fill the target surface
                drawingSession.Clear(Color.FromArgb(0, 0, 0, 0));
                drawingSession.DrawImage(bitmap, new Rect(0, 0, size.Width, size.Height), new Rect(0, 0, size.Width, size.Height));
                drawingSession.EffectTileSize = new BitmapSize {
                    Width = (uint)size.Width, Height = (uint)size.Height
                };
            }

            // Setup the effect brush to use
            var surfaceBrush = compositor.CreateSurfaceBrush(drawingSurface);

            surfaceBrush.Stretch = CompositionStretch.None;

            double pixels = displayInformation.RawPixelsPerViewPixel;

            // Adjust the scale if the DPI scaling is greater than 100%
            if (pixels > 1)
            {
                surfaceBrush.Scale = new Vector2((float)(1 / pixels));
                surfaceBrush.BitmapInterpolationMode = CompositionBitmapInterpolationMode.NearestNeighbor;
            }

            return(surfaceBrush);
        }
    }