Example #1
0
        private (CompositionBrush compositionBrush, CompositionSurfaceBrush compositionSurfaceBrush) CreateBrush(string imageName, Color color)
        {
            var compositor              = Window.Current.Compositor;
            var loadedSurface           = LoadedImageSurface.StartLoadFromUri(new Uri("ms-appx:///Assets/Images/" + imageName));
            var compositionSurfaceBrush = compositor.CreateSurfaceBrush();

            compositionSurfaceBrush.Surface = loadedSurface;
            var compositionBrush = CreateBrush(compositionSurfaceBrush, compositor.CreateColorBrush(color), BlendEffectMode.Lighten);

            return(compositionBrush, compositionSurfaceBrush);
        }
        private static void OnImageUriStringChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var brush = (ImageEffectBrush)d;

            // Unbox and update surface if CompositionBrush exists
            if (brush._surfaceBrush != null)
            {
                var newSurface = LoadedImageSurface.StartLoadFromUri(new Uri((String)e.NewValue));
                brush._surface = newSurface;
                brush._surfaceBrush.Surface = newSurface;
            }
        }
Example #3
0
        public void ValuesChanged(InteractionTracker sender, InteractionTrackerValuesChangedArgs args)
        {
            if (_indicator == null && ApiInfo.CanUseDirectComposition && (_tracker.Position.X > 0.0001f || _tracker.Position.X < -0.0001f) /*&& Math.Abs(e.Cumulative.Translation.X) >= 45*/)
            {
                var sprite = _visual.Compositor.CreateSpriteVisual();
                sprite.Size        = new Vector2(30, 30);
                sprite.CenterPoint = new Vector3(15);

                var surface = LoadedImageSurface.StartLoadFromUri(new Uri("ms-appx:///Assets/Images/Reply.png"));
                surface.LoadCompleted += (s, e) =>
                {
                    sprite.Brush = _visual.Compositor.CreateSurfaceBrush(s);
                };

                var ellipse = _visual.Compositor.CreateEllipseGeometry();
                ellipse.Radius = new Vector2(15);

                var ellipseShape = _visual.Compositor.CreateSpriteShape(ellipse);
                ellipseShape.FillBrush = _visual.Compositor.CreateColorBrush((Windows.UI.Color)App.Current.Resources["MessageServiceBackgroundColor"]);
                ellipseShape.Offset    = new Vector2(15);

                var shape = _visual.Compositor.CreateShapeVisual();
                shape.Shapes.Add(ellipseShape);
                shape.Size = new Vector2(30, 30);

                _indicator = _visual.Compositor.CreateContainerVisual();
                _indicator.Children.InsertAtBottom(shape);
                _indicator.Children.InsertAtTop(sprite);
                _indicator.Size        = new Vector2(30, 30);
                _indicator.CenterPoint = new Vector3(15);
                _indicator.Scale       = new Vector3();

                _container.Children.InsertAtTop(_indicator);

                //ElementCompositionPreview.SetElementChildVisual(this, _indicator);
                //ElementCompositionPreview.SetElementChildVisual(this, _container);
            }

            var offset = (_tracker.Position.X > 0 && !_reply) || (_tracker.Position.X <= 0 && !_forward) ? 0 : Math.Max(0, Math.Min(72, Math.Abs(_tracker.Position.X)));

            var abs     = Math.Abs(offset);
            var percent = abs / 72f;

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

            if (_indicator != null)
            {
                _indicator.Offset  = new Vector3(_tracker.Position.X > 0 ? width - percent * 60 : -30 + percent * 55, (height - 30) / 2, 0);
                _indicator.Scale   = new Vector3(_tracker.Position.X > 0 ? 0.8f + percent * 0.2f : -(0.8f + percent * 0.2f), 0.8f + percent * 0.2f, 1);
                _indicator.Opacity = percent;
            }
        }
Example #4
0
        public static async Task <LoadedImageSurface> GetPatternSurfaceAsync(IProtoService protoService, File file)
        {
            using var locked = await _patternSurfaceLock.WaitAsync();

            if (file.Local.IsFileExisting())
            {
                var bitmap = default(LoadedImageSurface);

                var cache    = $"{file.Remote.UniqueId}.cache.png";
                var relative = System.IO.Path.Combine("wallpapers", cache);

                var item = await ApplicationData.Current.LocalFolder.TryGetItemAsync(relative) as StorageFile;

                if (item == null)
                {
                    item = await ApplicationData.Current.LocalFolder.CreateFileAsync(relative, CreationCollisionOption.ReplaceExisting);

                    using (var stream = await item.OpenAsync(FileAccessMode.ReadWrite))
                    {
                        try
                        {
                            var text = await GetSvgXml(file);

                            await PlaceholderImageHelper.Current.DrawSvgAsync(text, Colors.White, stream);
                        }
                        catch { }
                    }
                }

                if (item != null)
                {
                    using (var stream = await item.OpenReadAsync())
                    {
                        try
                        {
                            var props = await item.Properties.GetImagePropertiesAsync();

                            bitmap = LoadedImageSurface.StartLoadFromStream(stream, new Size(props.Width / 2d, props.Height / 2d));
                        }
                        catch { }
                    }
                }

                return(bitmap);
            }
            else if (file.Local.CanBeDownloaded && !file.Local.IsDownloadingActive && protoService != null)
            {
                protoService.DownloadFile(file.Id, 1);
            }

            return(null);
        }
Example #5
0
 protected override void OnDisconnected()
 {
     if (_surface != null)
     {
         _surface.Dispose();
         _surface = null;
     }
     if (CompositionBrush != null)
     {
         CompositionBrush.Dispose();
         CompositionBrush = null;
     }
 }
Example #6
0
        private void ImgSurface_LoadCompleted(LoadedImageSurface sender, LoadedImageSourceLoadCompletedEventArgs args)
        {
            // TODO : translate ease function to composition
            // var easefunct = new ExponentialEase { Exponent = 7, EasingMode = EasingMode.EaseOut };
            var easefunct = ThumbnailCompositor.CreateCubicBezierEasingFunction(new Vector2(0.19f, 1f), new Vector2(0.22f, 1f));
            var animation = ThumbnailCompositor.CreateScalarKeyFrameAnimation();

            animation.InsertKeyFrame(0f, 0f);
            animation.InsertKeyFrame(1f, 1f, easefunct);
            animation.Duration = TimeSpan.FromMilliseconds(700);

            ThumbnailSpriteVisual.StartAnimation("Opacity", animation);
        }
Example #7
0
        public static LayerTranslator CreateImageLayerTranslator(ImageLayerContext context)
        {
            if (!Transforms.TryCreateContainerVisualTransformChain(context, out var containerVisualRootNode, out var containerVisualContentNode))
            {
                // The layer is never visible.
                return(null);
            }

            var imageAsset = GetImageAsset(context);

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

            var content = context.ObjectFactory.CreateSpriteVisual();

            containerVisualContentNode.Children.Add(content);
            content.Size = new Sn.Vector2((float)imageAsset.Width, (float)imageAsset.Height);

            LoadedImageSurface surface;
            var imageSize = $"{imageAsset.Width}x{imageAsset.Height}";

            switch (imageAsset.ImageType)
            {
            case ImageAsset.ImageAssetType.Embedded:
                var embeddedImageAsset = (EmbeddedImageAsset)imageAsset;
                surface = LoadedImageSurface.StartLoadFromStream(embeddedImageAsset.Bytes);
                surface.SetName(imageAsset.Id);
                surface.SetDescription(context, $"Image: \"{embeddedImageAsset.Id}\" {embeddedImageAsset.Format} {imageSize}.");
                break;

            case ImageAsset.ImageAssetType.External:
                var externalImageAsset = (ExternalImageAsset)imageAsset;
                surface = LoadedImageSurface.StartLoadFromUri(new Uri($"file://localhost/{externalImageAsset.Path}{externalImageAsset.FileName}"));
                surface.SetName(externalImageAsset.FileName);
                var path = externalImageAsset.Path + externalImageAsset.FileName;
                surface.SetDescription(context, $"\"{path}\" {imageSize}.");
                context.Issues.ImageFileRequired(path);
                break;

            default:
                throw new InvalidOperationException();
            }

            var imageBrush = context.ObjectFactory.CreateSurfaceBrush(surface);

            content.Brush = imageBrush;

            return(new LayerTranslator.FromVisual(containerVisualRootNode));
        }
Example #8
0
        private void ApplyComposition()
        {
            var compositor = Window.Current.Compositor;

            var backVisual = ElementCompositionPreview.GetElementVisual(FancyGrid);

            //backVisual.Offset = new Vector3(100, 100, 0);

            ElementCompositionPreview.SetIsTranslationEnabled(FancyGrid, true);
            var fancyGridPropertySet = backVisual.Properties;

            fancyGridPropertySet.InsertVector3("Translation", new Vector3(100, 100, 0));

            backVisual.RotationAngleInDegrees = 45;
            backVisual.CenterPoint            = new Vector3((float)FancyGrid.ActualWidth / 2.0f, (float)FancyGrid.ActualHeight / 2.0f, 0);

            var sprite1 = compositor.CreateSpriteVisual();

            sprite1.Size   = new Vector2(50, 50);
            sprite1.Offset = new Vector3(50, 50, 0);
            sprite1.Brush  = compositor.CreateColorBrush(Colors.Green);

            var sprite2 = compositor.CreateSpriteVisual();

            sprite2.Size   = new Vector2(50, 50);
            sprite2.Offset = new Vector3(25, 25, 0);
            sprite2.Brush  = compositor.CreateColorBrush(Colors.Purple);


            var container = compositor.CreateContainerVisual();

            container.Children.InsertAtTop(sprite1);
            container.Children.InsertAtBottom(sprite2);

            ElementCompositionPreview.SetElementChildVisual(FancyGrid, container);

            _loadedImageSurface = LoadedImageSurface.StartLoadFromUri(new Uri("ms-appx:///Assets/JustEnoughBikes.jpg"));
            _loadedImageSurface.LoadCompleted += (sender, args) =>
            {
                if (args.Status == LoadedImageSourceLoadStatus.Success)
                {
                    var brush = compositor.CreateSurfaceBrush(_loadedImageSurface);
                    brush.Stretch = CompositionStretch.UniformToFill;
                    var imageVisual = compositor.CreateSpriteVisual();
                    imageVisual.Size  = new Vector2(400, 400);
                    imageVisual.Brush = brush;
                    container.Children.InsertAtTop(imageVisual);
                }
            };
        }
Example #9
0
 protected override void OnDisconnected()
 {
     // Dispose Surface and CompositionBrushes if XamlCompBrushBase is removed from tree
     if (_surface != null)
     {
         _surface.Dispose();
         _surface = null;
     }
     if (CompositionBrush != null)
     {
         CompositionBrush.Dispose();
         CompositionBrush = null;
     }
 }
Example #10
0
        private Task <LoadedImageSurface> LoadImage(Uri uri, Size?size, CoreDispatcher dispatcher = null)
        {
            TaskCompletionSource <LoadedImageSurface> completionSource = new TaskCompletionSource <LoadedImageSurface>();
            LoadedImageSurface result = null;

            if (size.HasValue)
            {
                result = LoadedImageSurface.StartLoadFromUri(uri, size.Value);
            }
            else
            {
                result = LoadedImageSurface.StartLoadFromUri(uri);
            }

            TypedEventHandler <LoadedImageSurface, LoadedImageSourceLoadCompletedEventArgs> loadCompleteHandler = null;

            loadCompleteHandler = new TypedEventHandler <LoadedImageSurface, LoadedImageSourceLoadCompletedEventArgs>((sender, args) =>
            {
                sender.LoadCompleted -= loadCompleteHandler;
                if (dispatcher != null)
                {
                    _ = dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                    {
                        if (args.Status == LoadedImageSourceLoadStatus.Success)
                        {
                            completionSource.SetResult(result);
                        }
                        else
                        {
                            completionSource.SetResult(null);
                        }
                    });
                }
                else
                {
                    if (args.Status == LoadedImageSourceLoadStatus.Success)
                    {
                        completionSource.SetResult(result);
                    }
                    else
                    {
                        completionSource.SetResult(null);
                    }
                }
            });

            result.LoadCompleted += loadCompleteHandler;

            return(completionSource.Task);
        }
Example #11
0
        public static LoadedImageSurface GetImageSurface(string assetName, Size imageSize)
        {
            Uri getImageUri()
            {
                if (SharedHelpers.IsInFrameworkPackage())
                {
                    return(new Uri("ms-resource://" + MUXCONTROLS_PACKAGE_NAME + "/Files/Microsoft.UI.Xaml/Assets/" + assetName + ".png"));
                }
                else
                {
                    return(new Uri("ms-resource:///Files/Microsoft.UI.Xaml/Assets/" + assetName + ".png"));
                }
            }

            return(LoadedImageSurface.StartLoadFromUri(getImageUri(), imageSize));
        }
Example #12
0
        /// <summary>
        /// Show Compositon effects on image
        /// </summary>
        /// <param name="imageURL">Image to effect</param>
        private void SetupComposition(Uri imageURL)
        {
            try
            {
                CompositionSurfaceBrush _imageBrush;

                Compositor _compositor = Window.Current.Compositor;

                _imageBrush         = _compositor.CreateSurfaceBrush();
                _imageBrush.Stretch = CompositionStretch.UniformToFill;


                LoadedImageSurface _loadedSurface = LoadedImageSurface.StartLoadFromUri(imageURL);
                _loadedSurface.LoadCompleted += _loadedSurface_LoadCompleted;
                _imageBrush.Surface           = _loadedSurface;

                // Saturate
                var saturationEffect = new SaturationEffect
                {
                    Saturation = 1,
                    Source     = new CompositionEffectSourceParameter("image")
                };
                var effectFactory = _compositor.CreateEffectFactory(saturationEffect);
                var effectBrush   = effectFactory.CreateBrush();
                effectBrush.SetSourceParameter("image", _imageBrush);

                // Blur
                var blurEffect = new GaussianBlurEffect
                {
                    BlurAmount = 8,
                    Source     = new CompositionEffectSourceParameter("image")
                };
                var effectFactory2 = _compositor.CreateEffectFactory(blurEffect);
                var effectBrush2   = effectFactory2.CreateBrush();
                effectBrush2.SetSourceParameter("image", effectBrush);

                _imageVisual       = _compositor.CreateSpriteVisual();
                _imageVisual.Brush = effectBrush2;
                _imageVisual.Size  = new Vector2(Convert.ToSingle(BackgroundContainer.ActualWidth), Convert.ToSingle(BackgroundContainer.ActualHeight));

                ElementCompositionPreview.SetElementChildVisual(BackgroundContainer, _imageVisual);
            }
            catch
            {
                // I guess it'll just look meh
            }
        }
        /// <summary>
        /// </summary>
        protected override void OnConnected()
        {
            var compositor = Window.Current.Compositor;

            // Load milky way image
            _surface = LoadedImageSurface.StartLoadFromUri(new Uri(App.PhotoCollection.ElementAt(4).Path));

            _surface.LoadCompleted += (s, startArgs) =>
            {
                if (startArgs.Status == LoadedImageSourceLoadStatus.Success)
                {
                    // Create blur effect
                    var brush = compositor.CreateSurfaceBrush(_surface);
                    brush.Stretch = CompositionStretch.UniformToFill;

                    IGraphicsEffect graphicsEffect = new GaussianBlurEffect
                    {
                        Name       = "Blur",
                        BlurAmount = 0,
                        Source     = new CompositionEffectSourceParameter("image")
                    };

                    var effectFactory = compositor.CreateEffectFactory(graphicsEffect, new[] { "Blur.BlurAmount" });
                    var effectBrush   = effectFactory.CreateBrush();
                    effectBrush.SetSourceParameter("image", brush);

                    // Composition Brush is what is being applied to the UI Element.
                    CompositionBrush = effectBrush;
                    PropertySet      = effectBrush.Properties;

                    // Animate the blur
                    var blurAnimation = compositor.CreateScalarKeyFrameAnimation();
                    blurAnimation.InsertKeyFrame(0, 0f);
                    blurAnimation.InsertKeyFrame(0.5f, 10.0f);
                    blurAnimation.InsertKeyFrame(1, 0);
                    blurAnimation.Duration          = TimeSpan.FromSeconds(4);
                    blurAnimation.IterationBehavior = AnimationIterationBehavior.Forever;

                    effectBrush.Properties.StartAnimation("Blur.BlurAmount", blurAnimation);
                }
            };
        }
Example #14
0
        // This is only get called by ItemDetailsPage.Episodesitem_ContainerContentChanging
        public async void LoadImage()
        {
            ThumbnailCompositor = ElementCompositionPreview.GetElementVisual(Thumbnail).Compositor;

            using var stream = await GetImage();

            ThumbnailSurface = LoadedImageSurface.StartLoadFromStream(stream);
            ThumbnailSurface.LoadCompleted += ImgSurface_LoadCompleted;

            ThumbnailSurfaceBrush = ThumbnailCompositor.CreateSurfaceBrush(ThumbnailSurface);
            ThumbnailSurfaceBrush.BitmapInterpolationMode = CompositionBitmapInterpolationMode.Linear;
            ThumbnailSurfaceBrush.Stretch = CompositionStretch.UniformToFill;

            ThumbnailSpriteVisual         = ThumbnailCompositor.CreateSpriteVisual();
            ThumbnailSpriteVisual.Brush   = ThumbnailSurfaceBrush;
            ThumbnailSpriteVisual.Opacity = 0;
            ThumbnailSpriteVisual.Size    = new Vector2(180, 80);

            ElementCompositionPreview.SetElementChildVisual(Thumbnail, ThumbnailSpriteVisual);
        }
Example #15
0
        private void LoadMazeRunnerVisual()
        {
            if (_mazeRunnerVisual != null)
            {
                _mazeRunnerVisual.Dispose();
            }

            _mazeRunnerVisual      = _compositor.CreateSpriteVisual();
            _mazeRunnerVisual.Size = new Vector2(_cellSize, _cellSize);

            LoadedImageSurface      loadedSurface = LoadedImageSurface.StartLoadFromUri(new Uri("ms-appx:///Assets/luna.png"), new Size(_cellSize, _cellSize));
            CompositionSurfaceBrush surfaceBrush  = _compositor.CreateSurfaceBrush();

            surfaceBrush.Surface    = loadedSurface;
            _mazeRunnerVisual.Brush = surfaceBrush;

            ElementCompositionPreview.SetElementChildVisual(MazeGrid, _mazeRunnerVisual);
            _mazeRunnerVisual.IsVisible = true;
            _mazeRunnerVisual.Opacity   = 1;
        }
        /// <summary>
        /// Initializes the Composition Brush.
        /// </summary>
        protected override void OnConnected()
        {
            // Delay creating composition resources until they're required.
            if (CompositionBrush == null && Source != null && Source is BitmapImage bitmap)
            {
                // Use LoadedImageSurface API to get ICompositionSurface from image uri provided
                // If UriSource is invalid, StartLoadFromUri will return a blank texture.
                _surface = LoadedImageSurface.StartLoadFromUri(bitmap.UriSource);

                // Load Surface onto SurfaceBrush
                _surfaceBrush         = Window.Current.Compositor.CreateSurfaceBrush(_surface);
                _surfaceBrush.Stretch = CompositionStretchFromStretch(Stretch);

                // Abort if effects aren't supported.
                if (!CompositionCapabilities.GetForCurrentView().AreEffectsSupported())
                {
                    // Just use image straight-up, if we don't support effects.
                    CompositionBrush = _surfaceBrush;
                    return;
                }

                var backdrop = Window.Current.Compositor.CreateBackdropBrush();

                // Use a Win2D invert affect applied to a CompositionBackdropBrush.
                var graphicsEffect = new BlendEffect
                {
                    Name       = "Invert",
                    Mode       = (BlendEffectMode)(int)Mode,
                    Background = new CompositionEffectSourceParameter("backdrop"),
                    Foreground = new CompositionEffectSourceParameter("image")
                };

                var effectFactory = Window.Current.Compositor.CreateEffectFactory(graphicsEffect);
                var effectBrush   = effectFactory.CreateBrush();

                effectBrush.SetSourceParameter("backdrop", backdrop);
                effectBrush.SetSourceParameter("image", _surfaceBrush);

                CompositionBrush = effectBrush;
            }
        }
        private (CompositionBrush, CompositionSurfaceBrush) CreateMaskedBrush(CompositionBrush source)
        {
            var compositor = Window.Current.Compositor;
            var effect     = new AlphaMaskEffect()
            {
                Source    = new CompositionEffectSourceParameter("Source"),
                AlphaMask = new CompositionEffectSourceParameter("Mask"),
            };

            var opacityMaskSurface = LoadedImageSurface.StartLoadFromUri(new Uri("ms-appx:///Assets/Images/mask.Png"));
            var opacityBrush       = Compositor.CreateSurfaceBrush(opacityMaskSurface);

            opacityBrush.Stretch = CompositionStretch.UniformToFill;

            var effectFactory    = compositor.CreateEffectFactory(effect);
            var compositionBrush = effectFactory.CreateBrush();

            compositionBrush.SetSourceParameter("Source", source);
            compositionBrush.SetSourceParameter("Mask", opacityBrush);
            return(compositionBrush, opacityBrush);
        }
        internal override ICompositionSurface?LoadImage(Uri imageUri)
        {
            if (!imageUri.IsAbsoluteUri || imageUri.Authority != "localhost")
            {
                return(null);
            }

            // Load the image from the .lottie file. This is loaded into a MemoryStream
            // because the streams that come from ZipArchive cannot be randomly accessed
            // as required by LoadedImageSurface. This also has the benefit that it is
            // safe to Dispose the DotLottieFile as soon as the last image has started
            // decoding, becuase we already have all the bytes in the MemoryStream.
            var imageStream = _dotLottieFile !.OpenFileAsMemoryStream(imageUri.AbsolutePath);

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

            return(LoadedImageSurface.StartLoadFromStream(imageStream.AsRandomAccessStream()));
        }
        /// <summary>
        /// Deconstructs the Composition Brush.
        /// </summary>
        protected override void OnDisconnected()
        {
            // Dispose of composition resources when no longer in use.
            if (CompositionBrush != null)
            {
                CompositionBrush.Dispose();
                CompositionBrush = null;
            }

            if (_surfaceBrush != null)
            {
                _surfaceBrush.Dispose();
                _surfaceBrush = null;
            }

            if (_surface != null)
            {
                _surface.Dispose();
                _surface = null;
            }
        }
        private static void OnImageSourceChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var brush = (ImageBlendBrush)d;

            // Unbox and update surface if CompositionBrush exists
            if (brush._surfaceBrush != null)
            {
                // If UriSource is invalid, StartLoadFromUri will return a blank texture.
                var uri        = (e.NewValue as BitmapImage)?.UriSource ?? new Uri("ms-appx:///");
                var newSurface = LoadedImageSurface.StartLoadFromUri(uri);

                brush._surface = newSurface;
                brush._surfaceBrush.Surface = newSurface;
            }
            else
            {
                // If we didn't initially have a valid surface, we need to recreate our effect now.
                brush.OnDisconnected();
                brush.OnConnected();
            }
        }
Example #21
0
 private void _surface_LoadCompleted(LoadedImageSurface sender, LoadedImageSourceLoadCompletedEventArgs args)
 {
     lock (_lock)
     {
         if (sender != _surface)
         {
             return;
         }
         _surface.LoadCompleted -= _surface_LoadCompleted;
         if (args.Status == LoadedImageSourceLoadStatus.Success)
         {
             _loaded = true;
         }
         else
         {
             _loaded = false;
             _surface.Dispose();
             _surface = null;
         }
     }
 }
Example #22
0
        protected override void OnConnected()
        {
            if (CompositionBrush == null)
            {
                var surface      = LoadedImageSurface.StartLoadFromUri(Source, new Size(480, 750));
                var surfaceBrush = Window.Current.Compositor.CreateSurfaceBrush(surface);
                surfaceBrush.Stretch = CompositionStretch.None;

                var borderEffect = new BorderEffect()
                {
                    Source  = new CompositionEffectSourceParameter("source"),
                    ExtendX = Microsoft.Graphics.Canvas.CanvasEdgeBehavior.Wrap,
                    ExtendY = Microsoft.Graphics.Canvas.CanvasEdgeBehavior.Wrap
                };

                var borderEffectFactory = Window.Current.Compositor.CreateEffectFactory(borderEffect);
                var borderEffectBrush   = borderEffectFactory.CreateBrush();
                borderEffectBrush.SetSourceParameter("source", surfaceBrush);

                CompositionBrush = borderEffectBrush;
            }
        }
Example #23
0
            public void LoadImage(Uri uri, Size?size = null)
            {
                lock (_lock)
                {
                    if (_surface != null)
                    {
                        _surface.LoadCompleted -= _surface_LoadCompleted;
                        _surface.Dispose();
                        _surface = null;
                    }

                    _loaded = false;
                    if (size.HasValue)
                    {
                        _surface = LoadedImageSurface.StartLoadFromUri(uri, size.Value);
                    }
                    else
                    {
                        _surface = LoadedImageSurface.StartLoadFromUri(uri);
                    }
                    _surface.LoadCompleted += _surface_LoadCompleted;
                }
            }
Example #24
0
        protected override void OnConnected()
        {
            if (DesignMode.DesignModeEnabled)
            {
                return;
            }
            compositor = ElementCompositionPreview.GetElementVisual(Window.Current.Content as UIElement).Compositor;
            var tintOpacity = Convert.ToSingle(TintOpacity);

            if (tintOpacity < 0f)
            {
                tintOpacity = 0f;
            }
            if (tintOpacity > 1f)
            {
                tintOpacity = 1f;
            }
            var arithmeticEffect = new ArithmeticCompositeEffect()
            {
                Name           = "arithmetic",
                MultiplyAmount = 0,
                Source1Amount  = 1f - tintOpacity,
                Source2Amount  = tintOpacity,
                Source1        = new ArithmeticCompositeEffect()
                {
                    MultiplyAmount = 0f,
                    Source1Amount  = 0.95f,
                    Source2Amount  = 0.05f,
                    Source1        = new GaussianBlurEffect()
                    {
                        Name         = "blur",
                        BlurAmount   = Convert.ToSingle(BlurAmount),
                        BorderMode   = EffectBorderMode.Hard,
                        Optimization = EffectOptimization.Balanced,
                        Source       = new CompositionEffectSourceParameter("source"),
                    },
                    Source2 = new BorderEffect()
                    {
                        Source  = new CompositionEffectSourceParameter("image"),
                        ExtendX = CanvasEdgeBehavior.Wrap,
                        ExtendY = CanvasEdgeBehavior.Wrap,
                    }
                },
                Source2 = new ColorSourceEffect()
                {
                    Name  = "tintcolor",
                    Color = TintColor
                }
            };

            Brush = compositor.CreateEffectFactory(arithmeticEffect, new[] { "arithmetic.Source1Amount", "arithmetic.Source2Amount", "tintcolor.Color" }).CreateBrush();

            var imagesurface = LoadedImageSurface.StartLoadFromUri(new Uri("ms-appx:///FluentDesignSystem/Sketch/SketchTexture.jpg"));

            var imagebrush = compositor.CreateSurfaceBrush(imagesurface);

            imagebrush.Stretch = CompositionStretch.None;
            Brush.SetSourceParameter("image", imagebrush);

            switch (BackgroundSource)
            {
            case AcrylicBackgroundSource.Backdrop:
                Brush.SetSourceParameter("source", compositor.CreateBackdropBrush());
                break;

            case AcrylicBackgroundSource.Hostbackdrop:
                Brush.SetSourceParameter("source", compositor.CreateHostBackdropBrush());
                break;
            }

            CompositionBrush = Brush;

            var line = compositor.CreateLinearEasingFunction();

            TintOpacityFillAnimation = compositor.CreateScalarKeyFrameAnimation();
            TintOpacityFillAnimation.InsertExpressionKeyFrame(0f, "TintOpacity", line);
            TintOpacityFillAnimation.InsertKeyFrame(1f, 1f, line);
            TintOpacityFillAnimation.Duration = TimeSpan.FromSeconds(0.1d);
            TintOpacityFillAnimation.Target   = "arithmetic.Source2Amount";

            HostOpacityZeroAnimation = compositor.CreateScalarKeyFrameAnimation();
            HostOpacityZeroAnimation.InsertExpressionKeyFrame(0f, "1f - TintOpacity", line);
            HostOpacityZeroAnimation.InsertKeyFrame(1f, 0f, line);
            HostOpacityZeroAnimation.Duration = TimeSpan.FromSeconds(0.1d);
            HostOpacityZeroAnimation.Target   = "arithmetic.Source1Amount";

            TintToFallBackAnimation = compositor.CreateColorKeyFrameAnimation();
            TintToFallBackAnimation.InsertKeyFrame(0f, TintColor, line);
            TintToFallBackAnimation.InsertKeyFrame(1f, FallbackColor, line);
            TintToFallBackAnimation.Duration = TimeSpan.FromSeconds(0.1d);
            TintToFallBackAnimation.Target   = "tintcolor.Color";

            //Window.Current.Activated += Current_Activated;
            //Window.Current.VisibilityChanged += Current_VisibilityChanged;
            CoreWindow.GetForCurrentThread().Activated         += AcrylicBrush_Activated;
            CoreWindow.GetForCurrentThread().VisibilityChanged += AcrylicBrush_VisibilityChanged;
        }
Example #25
0
        protected override void OnConnected()
        {
            Compositor compositor = Window.Current.Compositor;

            // CompositionCapabilities: Are Effects supported?
            bool usingFallback = !CompositionCapabilities.GetForCurrentView().AreEffectsSupported();

            FallbackColor = Color.FromArgb(100, 60, 60, 60);

            if (usingFallback)
            {
                // If Effects are not supported, use Fallback Solid Color
                CompositionBrush = compositor.CreateColorBrush(FallbackColor);
                return;
            }

            // Load NormalMap onto an ICompositionSurface using LoadedImageSurface
            _surface = LoadedImageSurface.StartLoadFromUri(new Uri("ms-appx:///Assets/Damaged_NormalMap.jpg"), new Size(400, 400));

            // Load Surface onto SurfaceBrush
            CompositionSurfaceBrush normalMap = compositor.CreateSurfaceBrush(_surface);

            normalMap.Stretch = CompositionStretch.Uniform;

            // Define Effect graph
            const float glassLightAmount = 0.5f;
            const float glassBlurAmount  = 0.95f;
            Color       tintColor        = Color.FromArgb(255, 128, 128, 128);

            var graphicsEffect = new ArithmeticCompositeEffect()
            {
                Name           = "LightComposite",
                Source1Amount  = 1,
                Source2Amount  = glassLightAmount,
                MultiplyAmount = 0,
                Source1        = new ArithmeticCompositeEffect()
                {
                    Name           = "BlurComposite",
                    Source1Amount  = 1 - glassBlurAmount,
                    Source2Amount  = glassBlurAmount,
                    MultiplyAmount = 0,
                    Source1        = new ColorSourceEffect()
                    {
                        Name  = "Tint",
                        Color = tintColor,
                    },
                    Source2 = new GaussianBlurEffect()
                    {
                        BlurAmount   = 20,
                        Source       = new CompositionEffectSourceParameter("Backdrop"),
                        Optimization = EffectOptimization.Balanced,
                        BorderMode   = EffectBorderMode.Hard,
                    },
                },
                Source2 = new SceneLightingEffect()
                {
                    AmbientAmount   = 0.15f,
                    DiffuseAmount   = 1,
                    SpecularAmount  = 0.1f,
                    NormalMapSource = new CompositionEffectSourceParameter("NormalMap")
                },
            };

            // Create EffectFactory and EffectBrush
            CompositionEffectFactory effectFactory = compositor.CreateEffectFactory(graphicsEffect);
            CompositionEffectBrush   effectBrush   = effectFactory.CreateBrush();

            // Create BackdropBrush
            CompositionBackdropBrush backdrop = compositor.CreateBackdropBrush();

            // Set Sources to Effect
            effectBrush.SetSourceParameter("NormalMap", normalMap);
            effectBrush.SetSourceParameter("Backdrop", backdrop);

            // Set EffectBrush as the brush that XamlCompBrushBase paints onto Xaml UIElement
            CompositionBrush = effectBrush;
        }
Example #26
0
 TC CanonicalObject <TC>(LoadedImageSurface obj) => (TC)NodeFor(obj).Object;
Example #27
0
 TNode NodeFor(LoadedImageSurface obj) => _graph[obj].Canonical;
        /// <summary>
        /// Load the image and transform it to a composition brush or a XAML brush (depends of the UIStrategy)
        /// </summary>
        /// <param name="uri">the uri of the image to load</param>
        /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns>
        private async Task <bool> LoadImageBrushAsync(Uri uri)
        {
            if (DesignTimeHelpers.IsRunningInLegacyDesignerMode)
            {
                return(false);
            }

            if (_containerVisual == null || uri == null)
            {
                return(false);
            }

            await _flag.WaitAsync();

            try
            {
                bool isAnimated = IsAnimated;

                IsAnimated = false;

                if (_isImageSourceLoaded)
                {
                    for (int i = 0; i < _compositionChildren.Count; i++)
                    {
                        _compositionChildren[i].Brush = null;
                    }

                    _brushVisual?.Dispose();
                    _brushVisual = null;

                    _imageSurface?.Dispose();
                    _imageSurface = null;
                }

                _isImageSourceLoaded = false;

                var compositor = _containerVisual.Compositor;

                _imageSurface = LoadedImageSurface.StartLoadFromUri(uri);
                var loadCompletedSource = new TaskCompletionSource <bool>();
                _brushVisual = compositor.CreateSurfaceBrush(_imageSurface);

                _imageSurface.LoadCompleted += (s, e) =>
                {
                    if (e.Status == LoadedImageSourceLoadStatus.Success)
                    {
                        loadCompletedSource.SetResult(true);
                    }
                    else
                    {
                        loadCompletedSource.SetException(new ArgumentException("Image loading failed."));
                    }
                };

                await loadCompletedSource.Task;
                _imageSize = _imageSurface.DecodedPhysicalSize;

                _isImageSourceLoaded = true;

                RefreshContainerTile();

                RefreshImageSize(_imageSize.Width, _imageSize.Height);

                if (isAnimated)
                {
                    IsAnimated = true;
                }
            }
            finally
            {
                _flag.Release();
            }

            ImageLoaded?.Invoke(this, EventArgs.Empty);

            return(true);
        }
Example #29
0
 /// <summary>
 /// Composition effects completed
 /// </summary>
 private void _loadedSurface_LoadCompleted(LoadedImageSurface sender, LoadedImageSourceLoadCompletedEventArgs args)
 {
     BackgroundContainer.Fade(0.35f, 300, 0, EasingType.Circle).Start();
 }
Example #30
0
        /// <inheritdoc/>
        protected override void WriteLoadedImageSurfaceFactory(CodeBuilder builder, CodeGenInfo info, LoadedImageSurface obj, string fieldName, Uri imageUri)
        {
            switch (obj.Type)
            {
            case LoadedImageSurface.LoadedImageSurfaceType.FromStream:
                builder.WriteLine("auto stream = ref new InMemoryRandomAccessStream();");
                builder.WriteLine("auto dataWriter = ref new DataWriter(stream->GetOutputStreamAt(0));");
                builder.WriteLine($"dataWriter->WriteBytes({fieldName});");
                builder.WriteLine("dataWriter->StoreAsync();");
                builder.WriteLine("dataWriter->FlushAsync();");
                builder.WriteLine("stream->Seek(0);");
                builder.WriteLine($"{_stringifier.Var} result = Windows::UI::Xaml::Media::LoadedImageSurface::StartLoadFromStream(stream);");
                break;

            case LoadedImageSurface.LoadedImageSurfaceType.FromUri:
                builder.WriteLine($"{_stringifier.Var} result = Windows::UI::Xaml::Media::LoadedImageSurface::StartLoadFromUri(ref new Uri(\"{imageUri}\"));");
                break;
            }
        }