Пример #1
0
 /// <summary>
 /// Creates the circle used in the circle brush if not already created.
 /// </summary>
 private void EnsureCircleBrush()
 {
     if (_circleSurface == null)
     {
         _circleSurface = ImageLoader.Instance.LoadCircle(200, Colors.White);
     }
 }
Пример #2
0
 private void Page_Unloaded(object sender, RoutedEventArgs e)
 {
     if (_image != null)
     {
         _image.Dispose();
         _image = null;
     }
 }
Пример #3
0
        public override async Task <CompositionDrawingSurface> LoadResources()
        {
            var graphicsEffect = new ArithmeticCompositeEffect
            {
                Name          = "Arithmetic",
                Source1       = new CompositionEffectSourceParameter("ImageSource"),
                Source1Amount = .25f,
                Source2       = new Transform2DEffect
                {
                    Name   = "LightMapTransform",
                    Source = new CompositionEffectSourceParameter("LightMap")
                },
                Source2Amount  = 0,
                MultiplyAmount = 1
            };

            _effectFactory = _compositor.CreateEffectFactory(graphicsEffect, new[] { "LightMapTransform.TransformMatrix" });

            // Create the image
            _lightMap = await ImageLoader.Instance.LoadFromUriAsync(new Uri("ms-appx:///Assets/NormalMapsAndMasks/conemap.jpg"));

            // Create the animations
            float sweep      = (float)Math.PI / 10f;
            float fullCircle = (float)Math.PI * -2f;

            _enterAnimation = _compositor.CreateScalarKeyFrameAnimation();
            _enterAnimation.InsertKeyFrame(0.1f, fullCircle);
            _enterAnimation.InsertKeyFrame(0.4f, fullCircle + sweep);
            _enterAnimation.InsertKeyFrame(0.8f, fullCircle - sweep);
            _enterAnimation.InsertKeyFrame(1.0f, fullCircle);
            _enterAnimation.Duration          = TimeSpan.FromMilliseconds(4500);
            _enterAnimation.IterationBehavior = AnimationIterationBehavior.Count;
            _enterAnimation.IterationCount    = 1;

            _exitAnimation = _compositor.CreateScalarKeyFrameAnimation();
            _exitAnimation.InsertKeyFrame(1.0f, 0f);
            _exitAnimation.Duration          = TimeSpan.FromMilliseconds(1000);
            _exitAnimation.IterationBehavior = AnimationIterationBehavior.Count;
            _exitAnimation.IterationCount    = 1;

            var propsNode = ExpressionValues.Reference.CreatePropertySetReference("props");
            var propsCenterPointOffset = propsNode.GetVector2Property("CenterPointOffset");
            var propsRotation          = propsNode.GetScalarProperty("Rotation");
            var propsScale             = propsNode.GetScalarProperty("Scale");

            _transformExpressionNode = EF.CreateTranslation(-propsCenterPointOffset) *
                                       EF.Matrix3x2(EF.Cos(propsRotation) * propsScale,
                                                    EF.Sin(propsRotation),
                                                    -EF.Sin(propsRotation),
                                                    EF.Cos(propsRotation) * propsScale,
                                                    0,
                                                    0) *
                                       EF.CreateTranslation(propsCenterPointOffset + propsNode.GetVector2Property("Translate"));

            return(null);
        }
Пример #4
0
        private void Batch_Completed(object sender, CompositionBatchCompletedEventArgs args)
        {
            // Now that the animations are complete, dispose of the custom Splash Screen visuals
            ElementCompositionPreview.SetElementChildVisual(this, null);

            if (_splashSurface != null)
            {
                _splashSurface.Dispose();
                _splashSurface = null;
            }
        }
Пример #5
0
        private void SetImageBrush(string uri)
        {
            // Update the sprite
            _image = ImageLoader.Instance.LoadFromUri(new Uri(uri));
            UpdateImageBrush();

            // Update the preview image
            BitmapImage image = new BitmapImage(new Uri(uri));

            ImagePreview.Source = image;
        }
        async private void LoadImages()
        {
            int loadedImageCount = 0;

            //
            // Populate/load our unique list of image textures.
            //

            _imageBrushes = new ManagedSurface[_thumbnails.Count];

            for (int i = 0; i < _thumbnails.Count; i++)
            {
                Uri uri = new Uri(_thumbnails[i].ImageUrl);
                _imageBrushes[i] = await ImageLoader.Instance.LoadFromUriAsync(uri, new Size(500, 300));

                loadedImageCount++;
            }


            //
            // Populate/load our unique list of "text" image textures.
            //

            _textBrushes = new CompositionSurfaceBrush[_textNodes.Length];

            for (int i = 0; i < _textNodes.Length; i++)
            {
                var textNode = _textNodes[i];

                var textSurface = ImageLoader.Instance.LoadText(textNode.Text, new Size(textNode.TextureSize.X, textNode.TextureSize.Y), textNode.TextFormat, Colors.Black, Colors.Transparent);

                _textBrushes[i] = _compositor.CreateSurfaceBrush(textSurface.Surface);

                //
                // Remember the index of the brush so that we can refer to it later.
                //

                textNode.BrushIndex = i;

                loadedImageCount++;
            }



            //
            // Once we've loaded all of the images, we can continue populating the world.
            //

            if (loadedImageCount == _imageBrushes.Length + _textBrushes.Length)
            {
                PopulateWorld();
            }
        }
Пример #7
0
        public static Grid CreateStar(int duration, Vector2 coord, int radius)
        {
            var x = coord.X;
            var y = coord.Y;

            var height = radius;
            var width  = height;

            var grid = new Grid()
            {
                Height            = height,
                Width             = width,
                Margin            = new Thickness(x, y, 0, 0),
                VerticalAlignment = VerticalAlignment.Top
            };

            var compositor = ElementCompositionPreview.GetElementVisual(grid).Compositor;
            var container  = compositor.CreateContainerVisual();

            container.Size = new Vector2(height, width);

            if (ImageLoader.Instance == null)
            {
                ImageLoader.Initialize(compositor);
            }

            ManagedSurface surface = ImageLoader.Instance.LoadCircle(radius, Colors.White);

            var visual = compositor.CreateSpriteVisual();

            visual.Brush = compositor.CreateSurfaceBrush(surface.Surface);
            visual.Size  = new Vector2(radius, radius);

            container.Children.InsertAtTop(visual);

            ElementCompositionPreview.SetElementChildVisual(grid, container);

            // ------------
            // ANIMATION //
            // ------------
            var animation = compositor.CreateScalarKeyFrameAnimation();

            animation.InsertKeyFrame(0f, 1f);
            animation.InsertKeyFrame(1f, 0f);
            animation.Duration          = TimeSpan.FromSeconds(duration);
            animation.DelayTime         = TimeSpan.FromSeconds(duration / 2);
            animation.IterationBehavior = AnimationIterationBehavior.Forever;
            animation.Direction         = AnimationDirection.Alternate;
            visual.StartAnimation("Opacity", animation);

            return(grid);
        }
Пример #8
0
        public override async Task <CompositionDrawingSurface> LoadResources()
        {
            var graphicsEffect = new ArithmeticCompositeEffect
            {
                Name          = "Arithmetic",
                Source1       = new CompositionEffectSourceParameter("ImageSource"),
                Source1Amount = .1f,
                Source2       = new Transform2DEffect
                {
                    Name   = "LightMapTransform",
                    Source = new CompositionEffectSourceParameter("LightMap")
                },
                Source2Amount  = 0,
                MultiplyAmount = 1
            };

            _effectFactory = _compositor.CreateEffectFactory(graphicsEffect, new[] { "LightMapTransform.TransformMatrix" });

            // Create the image
            _lightMap = await ImageLoader.Instance.LoadFromUriAsync(new Uri("ms-appx:///Assets/NormalMapsAndMasks/pointmap.jpg"));

            // Create the animations
            CubicBezierEasingFunction easeIn = _compositor.CreateCubicBezierEasingFunction(new Vector2(0.0f, 0.51f), new Vector2(1.0f, 0.51f));

            _enterAnimation = _compositor.CreateScalarKeyFrameAnimation();
            _enterAnimation.InsertKeyFrame(0.33f, 1.25f, easeIn);
            _enterAnimation.InsertKeyFrame(0.66f, 0.75f, easeIn);
            _enterAnimation.InsertKeyFrame(1.0f, 1.0f, easeIn);
            _enterAnimation.Duration          = TimeSpan.FromMilliseconds(5000);
            _enterAnimation.IterationBehavior = AnimationIterationBehavior.Forever;

            _exitAnimation = _compositor.CreateVector2KeyFrameAnimation();
            _exitAnimation.InsertKeyFrame(1.0f, new Vector2(0, 0));
            _exitAnimation.Duration          = TimeSpan.FromMilliseconds(750);
            _exitAnimation.IterationBehavior = AnimationIterationBehavior.Count;
            _exitAnimation.IterationCount    = 1;

            var propsNode = ExpressionValues.Reference.CreatePropertySetReference("props");
            var propsCenterPointOffset = propsNode.GetVector2Property("CenterPointOffset");
            var propsTranslate         = propsNode.GetVector2Property("Translate");
            var propsScale             = propsNode.GetScalarProperty("Scale");

            _transformExpressionNode = EF.Matrix3x2(propsScale,
                                                    0,
                                                    0,
                                                    propsScale,
                                                    propsCenterPointOffset.X * (1 - propsScale) + (propsTranslate.X * propsCenterPointOffset.X * 2),
                                                    propsCenterPointOffset.Y * (1 - propsScale) + (propsTranslate.Y * propsCenterPointOffset.Y * 2));

            return(null);
        }
Пример #9
0
        private void Page_Unloaded(object sender, RoutedEventArgs e)
        {
            if (_sphereNormalMap != null)
            {
                _sphereNormalMap.Dispose();
                _sphereNormalMap = null;
            }

            if (_edgeNormalMap != null)
            {
                _edgeNormalMap.Dispose();
                _edgeNormalMap = null;
            }
        }
Пример #10
0
        private void SamplePage_Unloaded(object sender, RoutedEventArgs e)
        {
            foreach (CompositionEffectBrush brush in _brushList)
            {
                brush.Dispose();
            }
            _brushList.Clear();

            if (_normalMap != null)
            {
                _normalMap.Dispose();
                _normalMap = null;
            }
        }
Пример #11
0
        public static Grid CreateCloud(int duration, int endX, int marginTop)
        {
            var height = 70;
            var width  = height;

            var grid = new Grid()
            {
                Height            = height,
                Width             = width,
                Margin            = new Thickness(0, marginTop, 0, 0),
                VerticalAlignment = VerticalAlignment.Top
            };

            var compositor = ElementCompositionPreview.GetElementVisual(grid).Compositor;
            var container  = compositor.CreateContainerVisual();

            container.Size = new Vector2(height, width);

            if (ImageLoader.Instance == null)
            {
                ImageLoader.Initialize(compositor);
            }

            ManagedSurface surface = ImageLoader.Instance.LoadFromUri(new Uri("ms-appx:///Assets/Icons/cloudy.png"));

            var visual = compositor.CreateSpriteVisual();

            visual.Brush = compositor.CreateSurfaceBrush(surface.Surface);
            visual.Size  = new Vector2(70, 70);
            container.Children.InsertAtTop(visual);
            container.Opacity = .5f;

            ElementCompositionPreview.SetElementChildVisual(grid, container);

            // ------------
            // ANIMATION //
            // ------------
            var animation = compositor.CreateScalarKeyFrameAnimation();

            animation.InsertKeyFrame(0f, 0f);
            animation.InsertKeyFrame(1f, endX);
            animation.Duration          = TimeSpan.FromSeconds(duration);
            animation.DelayTime         = TimeSpan.FromSeconds(duration / 2);
            animation.IterationBehavior = AnimationIterationBehavior.Forever;
            animation.Direction         = AnimationDirection.Alternate;
            visual.StartAnimation("Offset.x", animation);

            return(grid);
        }
        /// <summary>
        /// Clean up resources on unload
        /// </summary>
        private void Page_Unloaded(object sender, RoutedEventArgs e)
        {
            _liveCapabilities.Changed -= HandleCapabilitiesChanged;

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

            if (_circleMaskSurface != null)
            {
                _circleMaskSurface.Dispose();
                _circleMaskSurface = null;
            }
        }
Пример #13
0
        /// <summary>
        /// Instantiate brush scenarios to use on the visual; used in combobox BrushSelection changed event.
        /// </summary>
        private static INineGridScenario[] CreateBrushes(Compositor compositor, ManagedSurface ninegridSurface, Vector2 visualSize)
        {
            ninegridSurface.Brush.Stretch = CompositionStretch.Fill;

            // Create INineGridScenario array to return. Surface scenario is special because it's used as input to another scenario
            var surfaceNineGridScenario = new SurfaceNineGridScenario(compositor, ninegridSurface.Brush, "Source: SurfaceBrush");

            return(new INineGridScenario[]
            {
                new ColorNineGridScenario(compositor, "Source: ColorBrush(hollow)"),
                new BorderNineGridScenario(compositor, ninegridSurface.Brush, visualSize, "Source: ColorBrush(w/ content)"),
                surfaceNineGridScenario,
                new EffectNineGridScenario(compositor, (CompositionNineGridBrush)surfaceNineGridScenario.Brush, "Input to: EffectBrush"),
                new MaskNineGridScenario(compositor, ninegridSurface.Brush, "Input to: MaskBrush")
            });
        }
Пример #14
0
        public static SpriteVisual CreateDarkCloudVisual(Compositor compositor, float size)
        {
            if (ImageLoader.Instance == null)
            {
                ImageLoader.Initialize(compositor);
            }

            ManagedSurface surface = ImageLoader.Instance.LoadFromUri(new Uri("ms-appx:///Assets/Icons/dark_cloud_png"));

            var visual = compositor.CreateSpriteVisual();

            visual.Brush = compositor.CreateSurfaceBrush(surface.Surface);
            visual.Size  = new Vector2(size, size);

            return(visual);
        }
Пример #15
0
        public NineGridResizing()
        {
            this.InitializeComponent();

            _compositor = ElementCompositionPreview.GetElementVisual(this).Compositor;

            // Add page loaded event listener
            this.Loaded += NineGridResizing_Loaded;

            // Set data context for data binding
            DataContext = this;

            // Sprite visual to be painted
            _ninegridVisual = _compositor.CreateSpriteVisual();

            // Create ninegridbrush and paint on visual;
            _ninegridBrush        = _compositor.CreateNineGridBrush();
            _ninegridVisual.Brush = _ninegridBrush;
            _ninegridSurface      = ImageLoader.Instance.LoadFromUri(new Uri("ms-appx:///Samples/SDK 14393/NineGridResizing/RoundedRect.png"));

            // Clip compgrid
            var compGrid = ElementCompositionPreview.GetElementVisual(CompGrid);

            compGrid.Clip = _compositor.CreateInsetClip();

            // Scene container to be scaled
            _backgroundContainer = ElementCompositionPreview.GetElementVisual(bkgHost);

            // Insert Composition island
            ElementCompositionPreview.SetElementChildVisual(ngHost, _ninegridVisual);

            // Instatiate brush scenario list and fill with created brush scenarios
            _nineGridBrushScenarios = new ObservableCollection <INineGridScenario>(CreateBrushes(_compositor, _ninegridSurface, _ninegridVisual.Size));

            // Set default combo box selection to first item
            BrushScenarioSelected = _nineGridBrushScenarios.FirstOrDefault();

            // Value timer initialization for sliders
            _valueTimerXSlider = new ValueTimer <float>();
            _valueTimerXSlider.ValueChanged += OnXSliderValueChanged;

            _valueTimerYSlider = new ValueTimer <float>();
            _valueTimerYSlider.ValueChanged += OnYSliderValueChanged;

            _valueTimerScaleSlider = new ValueTimer <float>();
            _valueTimerScaleSlider.ValueChanged += OnScaleSliderValueChanged;
        }
Пример #16
0
        private void Page_Unloaded(object sender, RoutedEventArgs e)
        {
            // Dispose the sprite and unparent it
            ElementCompositionPreview.SetElementChildVisual(ThumbnailList, null);

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

            if (_maskSurface != null)
            {
                _maskSurface.Dispose();
                _maskSurface = null;
            }
        }
Пример #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);

            // Create the circle mask
            _circleMaskSurface = ImageLoader.Instance.LoadCircle(200, Colors.White);
        }
Пример #18
0
 private void ReleaseSurface()
 {
     if (_surface != null)
     {
         // If no one has asked to share, dispose it to free the memory
         if (!_sharedSurface)
         {
             _surface.Dispose();
             _surfaceBrush.Surface = null;
         }
         else
         {
             // No longer being managed
             ImageLoader.Instance.UnregisterSurface(_surface);
         }
         _surface = null;
     }
 }
Пример #19
0
        public override async Task <CompositionDrawingSurface> LoadResources()
        {
            var graphicsEffect = new ArithmeticCompositeEffect
            {
                Name          = "Arithmetic",
                Source1       = new CompositionEffectSourceParameter("ImageSource"),
                Source1Amount = .25f,
                Source2       = new Transform2DEffect
                {
                    Name   = "LightMapTransform",
                    Source = new CompositionEffectSourceParameter("LightMap")
                },
                Source2Amount  = 0,
                MultiplyAmount = 1
            };

            _effectFactory = _compositor.CreateEffectFactory(graphicsEffect, new[] { "LightMapTransform.TransformMatrix" });

            // Create the image
            _lightMap = await ImageLoader.Instance.LoadFromUriAsync(new Uri("ms-appx:///Samples/SDK 10586/PointerEnterEffects/conemap.jpg"));

            // Create the animations
            float sweep      = (float)Math.PI / 10f;
            float fullCircle = (float)Math.PI * -2f;

            _enterAnimation = _compositor.CreateScalarKeyFrameAnimation();
            _enterAnimation.InsertKeyFrame(0.1f, fullCircle);
            _enterAnimation.InsertKeyFrame(0.4f, fullCircle + sweep);
            _enterAnimation.InsertKeyFrame(0.8f, fullCircle - sweep);
            _enterAnimation.InsertKeyFrame(1.0f, fullCircle);
            _enterAnimation.Duration          = TimeSpan.FromMilliseconds(4500);
            _enterAnimation.IterationBehavior = AnimationIterationBehavior.Count;
            _enterAnimation.IterationCount    = 1;

            _exitAnimation = _compositor.CreateScalarKeyFrameAnimation();
            _exitAnimation.InsertKeyFrame(1.0f, 0f);
            _exitAnimation.Duration          = TimeSpan.FromMilliseconds(1000);
            _exitAnimation.IterationBehavior = AnimationIterationBehavior.Count;
            _exitAnimation.IterationCount    = 1;

            _transformExpression = _compositor.CreateExpressionAnimation("Matrix3x2.CreateFromTranslation(-props.CenterPointOffset) * Matrix3x2(cos(props.Rotation) * props.Scale, sin(props.Rotation), -sin(props.Rotation), cos(props.Rotation) * props.Scale, 0, 0) * Matrix3x2.CreateFromTranslation(props.CenterPointOffset + props.Translate)");

            return(null);
        }
Пример #20
0
        /// <summary>
        /// Initialize Composition
        /// </summary>
        private void InitializeComposition()
        {
            // Retrieve an instance of the Compositor from the backing Visual of the Page
            _compositor = ElementCompositionPreview.GetElementVisual(this).Compositor;

            // Create a root visual from the Compositor
            _root = _compositor.CreateContainerVisual();

            // Set the root ContainerVisual as the XAML Page Visual
            ElementCompositionPreview.SetElementChildVisual(this, _root);

            // Assign initial values to variables used to store updated offsets for the visuals
            float posXUpdated = _posX;
            float posYUpdated = _posY;


            //Create a list of image brushes that can be applied to a visual
            string[] imageNames = { "60Banana.png", "60Lemon.png", "60Vanilla.png", "60Mint.png", "60Orange.png", "110Strawberry.png", "60SprinklesRainbow.png" };
            _imageList = new List <ManagedSurface>(10);
            for (int k = 0; k < imageNames.Length; k++)
            {
                ManagedSurface surface = ImageLoader.Instance.LoadFromUri(new Uri("ms-appx:///Samples/SDK 14393/ImplicitAnimationTransformer/" + imageNames[k]));
                _imageList.Add(surface);
            }

            // Create nxn matrix of visuals where n=row/ColumnCount-1 and passes random image brush to the function
            // that creates a visual
            for (int i = 1; i < _rowCount; i++)
            {
                posXUpdated = i * _distance;
                for (int j = 1; j < _columnCount; j++)
                {
                    CompositionSurfaceBrush brush = _imageList[randomBrush.Next(_imageList.Count)].Brush;

                    posYUpdated = j * _distance;
                    _root.Children.InsertAtTop(CreateChildElement(brush, posXUpdated, posYUpdated));
                }
            }

            // Update the default animation state
            UpdateAnimationState(EnableAnimations.IsChecked == true);
        }
Пример #21
0
        private void ShowCustomSplashScreen(Rect imageBounds)
        {
            Compositor compositor = ElementCompositionPreview.GetElementVisual(this).Compositor;
            Vector2    windowSize = new Vector2((float)Window.Current.Bounds.Width, (float)Window.Current.Bounds.Height);


            //
            // Create a container visual to hold the color fill background and image visuals.
            // Configure this visual to scale from the center.
            //

            ContainerVisual container = compositor.CreateContainerVisual();

            container.Size        = windowSize;
            container.CenterPoint = new Vector3(windowSize.X, windowSize.Y, 0) * .5f;
            ElementCompositionPreview.SetElementChildVisual(this, container);


            //
            // Create the colorfill sprite for the background, set the color to the same as app theme
            //

            SpriteVisual backgroundSprite = compositor.CreateSpriteVisual();

            backgroundSprite.Size  = windowSize;
            backgroundSprite.Brush = compositor.CreateColorBrush(Color.FromArgb(255, 0, 188, 242));
            container.Children.InsertAtBottom(backgroundSprite);


            //
            // Create the image sprite containing the splash screen image.  Size and position this to
            // exactly cover the Splash screen image so it will be a seamless transition between the two
            //

            _splashSurface = ImageLoader.Instance.LoadFromUri(new Uri("ms-appx:///Assets/StoreAssets/Wide.png"));
            SpriteVisual imageSprite = compositor.CreateSpriteVisual();

            imageSprite.Brush  = compositor.CreateSurfaceBrush(_splashSurface.Surface);
            imageSprite.Offset = new Vector3((float)imageBounds.X, (float)imageBounds.Y, 0f);
            imageSprite.Size   = new Vector2((float)imageBounds.Width, (float)imageBounds.Height);
            container.Children.InsertAtTop(imageSprite);
        }
Пример #22
0
        private async void Page_Loaded(object sender, RoutedEventArgs e)
        {
            // Populate the light type combobox
            IList <ComboBoxItem> lightList = new List <ComboBoxItem>();

            foreach (LightingTypes type in Enum.GetValues(typeof(LightingTypes)))
            {
                ComboBoxItem item = new ComboBoxItem();
                item.Tag     = type;
                item.Content = type.ToString();
                lightList.Add(item);
            }

            LightingSelection.ItemsSource   = lightList;
            LightingSelection.SelectedIndex = 0;

            ThumbnailList.ItemsSource = Model.AggregateDataSources(new ObservableCollection <Thumbnail>[] { Model.Landscapes, Model.Nature });

            //
            // Create the sperical normal map.  The normals will give the appearance of a sphere, and the alpha channel is used
            // for masking off the rectangular edges.
            //

            _sphereNormalMap = await ImageLoader.Instance.LoadFromUriAsync(new Uri("ms-appx:///Assets/NormalMapsAndMasks/SphericalWithMask.png"));

            _sphereNormalMap.Brush.Stretch = CompositionStretch.Fill;


            //
            // Create the flat normal map with beveled edges.  This should give the appearance of slanting of the surface along
            // the edges, flat in the middle.
            //

            _edgeNormalMap = await ImageLoader.Instance.LoadFromUriAsync(new Uri("ms-appx:///Assets/NormalMapsAndMasks/BeveledEdges.jpg"));

            _edgeNormalMap.Brush.Stretch = CompositionStretch.Fill;

            // Update the effect brushes now that the normal maps are available.
            UpdateEffectBrush();
        }
Пример #23
0
        private async void ApplyEffect(CompositionImage image)
        {
            ManagedSurface effectSurface = null;

            // If we've requested a load time effect input, kick it off now
            if (_currentTechnique.LoadTimeEffectHandler != null)
            {
                effectSurface = await ImageLoader.Instance.LoadFromUriAsync(image.Source, Size.Empty, _currentTechnique.LoadTimeEffectHandler);
            }

            // Create the new brush, set the inputs and set it on the image
            CompositionEffectBrush brush = _currentTechnique.CreateBrush();

            brush.SetSourceParameter("ImageSource", image.SurfaceBrush);
            image.Brush = brush;

            // Set the effect surface as input
            if (effectSurface != null)
            {
                brush.SetSourceParameter("EffectSource", effectSurface.Brush);
            }
        }
        private async void Page_Loaded(object sender, RoutedEventArgs e)
        {
            _backgroundImageVisual     = _compositor.CreateSpriteVisual();
            _imageContainer            = _compositor.CreateContainerVisual();
            _liveCapabilities.Changed += HandleCapabilitiesChanged;

            ElementCompositionPreview.SetElementChildVisual(ImageCanvas, _imageContainer);

            // Load the image
            _surface = await ImageLoader.Instance.LoadFromUriAsync(new Uri("ms-appx:///Assets/Landscapes/Landscape-7.jpg"));

            _surface.Brush.Stretch           = CompositionStretch.Fill;
            _circleMaskSurface               = ImageLoader.Instance.LoadCircle(200, Colors.White);
            _circleMaskSurface.Brush.Stretch = CompositionStretch.Uniform;

            _imageContainer.Size = new Vector2((float)ImageCanvas.ActualWidth, (float)ImageCanvas.ActualHeight);

            _imageContainer.Children.InsertAtTop(_backgroundImageVisual);

            UpdateVisualSizeAndPosition();

            UpdateAlbumArt();
        }
Пример #25
0
        private async void Page_Loaded(object sender, RoutedEventArgs e)
        {
            ThumbnailList.ItemsSource = Model.Items;

            // Populate the Effect combobox
            IList <ComboBoxItem> effectList = new List <ComboBoxItem>();

            foreach (EffectTypes type in Enum.GetValues(typeof(EffectTypes)))
            {
                ComboBoxItem item = new ComboBoxItem();
                item.Tag     = type;
                item.Content = type.ToString();
                effectList.Add(item);
            }

            EffectSelection.ItemsSource   = effectList;
            EffectSelection.SelectedIndex = 0;

            // Get the current compositor
            _compositor = ElementCompositionPreview.GetElementVisual(this).Compositor;

            // Create the destinatio sprite, sized to cover the entire list
            _destinationSprite      = _compositor.CreateSpriteVisual();
            _destinationSprite.Size = new Vector2((float)ThumbnailList.ActualWidth, (float)ThumbnailList.ActualHeight);

            // Start out with the destination layer invisible to avoid any cost until necessary
            _destinationSprite.IsVisible = false;

            // Create the mask surface
            _maskSurface = await ImageLoader.Instance.LoadFromUriAsync(new Uri("ms-appx:///Samples/SDK 14393/ForegroundFocusEffects/mask.png"));

            ElementCompositionPreview.SetElementChildVisual(ThumbnailList, _destinationSprite);

            // Update the effect to set the appropriate brush
            UpdateEffect();
        }
Пример #26
0
        private void Page_Loaded(object sender, RoutedEventArgs e)
        {
            // Get backing visual from shadow container and interop compositor
            _shadowContainer = ElementCompositionPreview.GetElementVisual(ShadowContainer);
            _compositor      = _shadowContainer.Compositor;

            // Get CompositionImage, its sprite visual
            _image       = VisualTreeHelperExtensions.GetFirstDescendantOfType <CompositionImage>(ShadowContainer);
            _imageVisual = _image.SpriteVisual;

            // Load mask asset onto surface using helpers in SamplesCommon
            _imageMaskSurface = ImageLoader.Instance.LoadCircle(200, Colors.White);

            // Get surface brush from composition image
            CompositionSurfaceBrush source = _image.SurfaceBrush as CompositionSurfaceBrush;

            // Create mask brush for toggle mask functionality
            _maskBrush        = _compositor.CreateMaskBrush();
            _maskBrush.Mask   = _imageMaskSurface.Brush;
            _maskBrush.Source = source;

            // Initialize toggle mask
            _isMaskEnabled = false;
        }
Пример #27
0
 public LayerItem(Uri imageUri)
 {
     _surface = ImageLoader.Instance.LoadFromUri(imageUri);
 }
Пример #28
0
        private void CreateTextAndBlendEffect(Vector2 sizeLightBounds)
        {
            //
            // Crete the effect graph, doing a hard light blend of the text over the
            // content already drawn into the backbuffer
            //

            IGraphicsEffect graphicsEffect = new BlendEffect()
            {
                Mode       = BlendEffectMode.HardLight,
                Foreground = new CompositionEffectSourceParameter("Text"),
                Background = new CompositionEffectSourceParameter("Destination"),
            };

            CompositionEffectFactory effectFactory = _compositor.CreateEffectFactory(graphicsEffect, null);
            CompositionEffectBrush   brush         = effectFactory.CreateBrush();

            // Bind the destination brush
            brush.SetSourceParameter("Destination", _compositor.CreateBackdropBrush());


            //
            // Create the text surface which we'll scroll over the image with the lighting effect
            //

            // Pick a nice size font depending on target size
            const float maxFontSize = 72;
            const float scaleFactor = 12;
            float       fontSize    = Math.Min(sizeLightBounds.X / scaleFactor, maxFontSize);

            // Create the text format description, then the surface
            CanvasTextFormat textFormat = new CanvasTextFormat
            {
                FontFamily          = "Segoe UI",
                FontSize            = fontSize,
                FontWeight          = FontWeights.Bold,
                WordWrapping        = CanvasWordWrapping.WholeWord,
                HorizontalAlignment = CanvasHorizontalAlignment.Center,
                VerticalAlignment   = CanvasVerticalAlignment.Center
            };

            string text = "Ein bisschen Frieden, ein bisschen Sonne\n" +
                          "für diese Erde, auf der wir wohnen\n" +
                          "Ein bisschen Frieden, ein bisschen Freude\n" +
                          "ein bisschen Wärme, das wünsch' ich mir\n" +
                          "Ein bisschen Frieden, ein bisschen Träumen\n" +
                          "und dass die Menschen nicht so oft weinen\n" +
                          "Ein bisschen Frieden, ein bisschen Liebe\n" +
                          "dass ich die Hoffnung nie mehr verlier";

            // Make the surface twice the height to give us room to scroll
            Vector2        surfaceSize = new Vector2(sizeLightBounds.X, 2f * sizeLightBounds.Y);
            ManagedSurface textSurface = ImageLoader.Instance.LoadText(text, surfaceSize.ToSize(),
                                                                       textFormat, Colors.White, Colors.Transparent);

            brush.SetSourceParameter("Text", textSurface.Brush);

            // Create the sprite and parent it to the panel with the clip
            _textSprite       = _compositor.CreateSpriteVisual();
            _textSprite.Size  = surfaceSize;
            _textSprite.Brush = brush;

            ElementCompositionPreview.SetElementChildVisual(MyPanel, _textSprite);

            // Lastly, setup the slow scrolling animation of the text
            LinearEasingFunction     linear          = _compositor.CreateLinearEasingFunction();
            Vector3KeyFrameAnimation offsetAnimation = _compositor.CreateVector3KeyFrameAnimation();

            offsetAnimation.InsertKeyFrame(0f, new Vector3(0, 0, 0), linear);
            offsetAnimation.InsertKeyFrame(1f, new Vector3(0, -_textSprite.Size.Y * .5f, 0), linear);
            offsetAnimation.Duration          = TimeSpan.FromMilliseconds(30000);
            offsetAnimation.IterationBehavior = AnimationIterationBehavior.Forever;
            _textSprite.StartAnimation("Offset", offsetAnimation);
        }
Пример #29
0
        private async void LoadSurface()
        {
            // If we're clearing out the content, return
            if (_uri == null)
            {
                ReleaseSurface();
                return;
            }

            try
            {
                // Start a timer to enable the placeholder image if requested
                if (_surface == null && _placeholderDelay >= TimeSpan.Zero)
                {
                    _timer          = new DispatcherTimer();
                    _timer.Interval = _placeholderDelay;
                    _timer.Tick    += Timer_Tick;
                    _timer.Start();
                }

                // Load the image asynchronously
                ManagedSurface surface = await ImageLoader.Instance.LoadFromUriAsync(_uri, Size.Empty, _loadEffectDelegate);

                if (_surface != null)
                {
                    ReleaseSurface();
                }

                _surface = surface;

                // The surface has changed, so we need to re-measure with the new surface dimensions
                InvalidateMeasure();

                // Async operations may take a while.  If we've unloaded, return now.
                if (_unloaded)
                {
                    ReleaseSurface();
                    return;
                }

                // Update the brush
                UpdateBrush();

                // Success, fire the Opened event
                if (ImageOpened != null)
                {
                    ImageOpened(this, null);
                }

                //
                // If we created the loading placeholder, now that the image has loaded
                // cross-fade it out.
                //

                if (_sprite != null && _sprite.Children.Count > 0)
                {
                    Debug.Assert(_timer == null);
                    StartCrossFade();
                }
                else if (_timer != null)
                {
                    // We didn't end up loading the placeholder, so just stop the timer
                    _timer.Stop();
                    _timer = null;
                }
            }
            catch (FileNotFoundException)
            {
                if (ImageFailed != null)
                {
                    ImageFailed(this, null);
                }
            }
        }
Пример #30
0
        public void Highlight()
        {
            var message = DataContext as TLMessage;

            if (message == null)
            {
                return;
            }

            var sticker = message.IsSticker();
            var round   = message.IsRoundVideo();
            var target  = sticker || round ? Media : (FrameworkElement)ContentPanel;

            var overlay = ElementCompositionPreview.GetElementChildVisual(target) as SpriteVisual;

            if (overlay == null)
            {
                overlay = ElementCompositionPreview.GetElementVisual(this).Compositor.CreateSpriteVisual();
                ElementCompositionPreview.SetElementChildVisual(target, overlay);
            }

            var settings = new UISettings();
            var fill     = overlay.Compositor.CreateColorBrush(settings.GetColorValue(UIColorType.Accent));
            var brush    = (CompositionBrush)fill;

            if (sticker || round)
            {
                ImageLoader.Initialize(overlay.Compositor);
                ManagedSurface surface = null;
                if (sticker)
                {
                    var document = message.GetDocument();
                    var fileName = document.GetFileName();
                    if (File.Exists(FileUtils.GetTempFileName(fileName)))
                    {
                        var decoded = WebPImage.Encode(File.ReadAllBytes(FileUtils.GetTempFileName(fileName)));
                        surface = ImageLoader.Instance.LoadFromStream(decoded);
                    }
                }
                else
                {
                    surface = ImageLoader.Instance.LoadCircle(100, Windows.UI.Colors.White);
                }

                if (surface != null)
                {
                    var mask = overlay.Compositor.CreateMaskBrush();
                    mask.Mask   = surface.Brush;
                    mask.Source = fill;
                    brush       = mask;
                }
            }

            overlay.Size    = new System.Numerics.Vector2((float)target.ActualWidth, (float)target.ActualHeight);
            overlay.Opacity = 0f;
            overlay.Brush   = brush;

            var animation = overlay.Compositor.CreateScalarKeyFrameAnimation();

            animation.Duration = TimeSpan.FromSeconds(2);
            animation.InsertKeyFrame(300f / 2000f, 0.4f);
            animation.InsertKeyFrame(1700f / 2000f, 0.4f);
            animation.InsertKeyFrame(1, 0);

            overlay.StartAnimation("Opacity", animation);
        }