Exemple #1
0
        private void AnimateMazeRunnerVisualToCell(int col, int row, TravelSpeed travelSpeed, int crumbCount)
        {
            _animationIsRunning = true;

            if (_batch != null)
            {
                _batch.Dispose();
            }
            _batch = _compositor.CreateScopedBatch(CompositionBatchTypes.Animation);

            var animation = _compositor.CreateVector3KeyFrameAnimation();
            var easing    = _compositor.CreateLinearEasingFunction();

            var destination = new Vector3((float)(col * _cellSize), (float)(row * _cellSize), 0.0F);

            animation.InsertKeyFrame(1.0f, destination, easing);

            switch (travelSpeed)
            {
            case TravelSpeed.Walk:
                animation.Duration = TimeSpan.FromMilliseconds(500 * crumbCount);
                break;

            case TravelSpeed.Run:
                animation.Duration = TimeSpan.FromSeconds(0.1);
                break;

            case TravelSpeed.Jump:
                animation.Duration = TimeSpan.FromMilliseconds(1);
                break;
            }
            _mazeRunnerVisual.StartAnimation(nameof(_mazeRunnerVisual.Offset), animation);
            _batch.End();
            _batch.Completed += _batch_Completed;
        }
Exemple #2
0
        public static void StartClipAnimation(this FrameworkElement element, ClipAnimationDirection direction, float to,
                                              double duration = 800, int delay = 0, CompositionEasingFunction easing = null, Action completed = null,
                                              AnimationIterationBehavior iterationBehavior = AnimationIterationBehavior.Count)
        {
            CompositionScopedBatch batch = null;

            var visual = element.Visual();

            // After we get the Visual of the View, we need to SIZE it 'cause by design the
            // Size is (0,0). Without doing this, clipping will not work.
            visual.Size = element.RenderSize.ToVector2();
            var compositor = visual.Compositor;

            if (visual.Clip == null)
            {
                var clip = compositor.CreateInsetClip();
                visual.Clip = clip;
            }

            if (completed != null)
            {
                batch            = compositor.CreateScopedBatch(CompositionBatchTypes.Animation);
                batch.Completed += (s, e) => completed();
            }

            visual.Clip.StartAnimation($"{direction}Inset",
                                       compositor.CreateScalarKeyFrameAnimation(null, to, duration, delay, easing, iterationBehavior));

            batch?.End();
        }
        public static void StartRotationAnimation(this Visual visual, Vector3 rotationAxis, Vector3?centerPoint = null,
                                                  float?from = null, float to = 0, double duration = 800, int delay = 0, CompositionEasingFunction easing = null, Action completed = null,
                                                  AnimationIterationBehavior iterationBehavior = AnimationIterationBehavior.Count)
        {
            CompositionScopedBatch batch = null;
            var compositor = visual.Compositor;

            if (centerPoint == null)
            {
                centerPoint = new Vector3(visual.Size / 2, 0.0f);
            }
            visual.CenterPoint = centerPoint.Value;

            if (completed != null)
            {
                batch            = compositor.CreateScopedBatch(CompositionBatchTypes.Animation);
                batch.Completed += (s, e) => completed();
            }

            visual.RotationAxis = rotationAxis;

            visual.StartAnimation("RotationAngleInDegrees",
                                  compositor.CreateScalarKeyFrameAnimation(from, to, duration, delay, easing, iterationBehavior));

            batch?.End();
        }
Exemple #4
0
        public static void StartClipAnimation(this Visual visual, ClipAnimationDirection direction, float to,
                                              double duration = 800, int delay = 0, CompositionEasingFunction easing = null, Action completed = null,
                                              AnimationIterationBehavior iterationBehavior = AnimationIterationBehavior.Count)
        {
            CompositionScopedBatch batch = null;

            if (visual.Size.X.Equals(0) || visual.Size.Y.Equals(0))
            {
                throw new ArgumentException("The visual is not properly sized.");
            }

            var compositor = visual.Compositor;

            if (visual.Clip == null)
            {
                var clip = compositor.CreateInsetClip();
                visual.Clip = clip;
            }

            if (completed != null)
            {
                batch            = compositor.CreateScopedBatch(CompositionBatchTypes.Animation);
                batch.Completed += (s, e) => completed();
            }

            visual.Clip.StartAnimation($"{direction}Inset",
                                       compositor.CreateScalarKeyFrameAnimation(null, to, duration, delay, easing, iterationBehavior));

            batch?.End();
        }
Exemple #5
0
        private void _switchLight(bool turnOn)
        {
            Action animateSpotLight = () =>
            {
                var animation = _colorsProxy.Compositor.CreateScalarKeyFrameAnimation();
                animation.Duration = TimeSpan.FromMilliseconds(250);
                animation.InsertKeyFrame(1, turnOn ? 1f : 0f);
                _colorsProxy.StartAnimation("LightIntensity", animation);
            };

            if (turnOn)
            {
                //_light.IsEnabled = true;
                animateSpotLight();
            }
            else
            {
                CompositionScopedBatch scopedBatch = Window.Current.Compositor.CreateScopedBatch(CompositionBatchTypes.Animation);
                animateSpotLight();
                scopedBatch.End();
                scopedBatch.Completed += (o, e) =>
                {
                    //_light.IsEnabled = false;
                };
            }
        }
Exemple #6
0
        private void FirstslideBatchAnimation_Completed(object sender, CompositionBatchCompletedEventArgs args)
        {
            string[] parms = (sender as CompositionScopedBatch).Comment.Split(',');

            int  start     = int.Parse(parms[0]);
            int  end       = int.Parse(parms[1]);
            int  delta     = int.Parse(parms[2]);
            int  increment = int.Parse(parms[3]);
            bool change    = bool.Parse(parms[4]);

            var compositor = ElementCompositionPreview.GetElementVisual(Window.Current.Content).Compositor;

            _addAdjacentBatchAnimation            = compositor.CreateScopedBatch(CompositionBatchTypes.Animation);
            _addAdjacentBatchAnimation.Completed += AddAdjacentBatchAnimation_Completed;
            _addAdjacentBatchAnimation.Comment    = start + "," + end + "," + delta + "," + increment;

            for (int i = 0; i < _boardSize; i++)
            {
                change = AddAdjacent(start, end, delta) || change;
                start += increment;
                end   += increment;
            }

            _addAdjacentBatchAnimation.Comment = _addAdjacentBatchAnimation.Comment + "," + change;
            _addAdjacentBatchAnimation.End();

            if (change)
            {
                OnPropertyChanged("Score");
            }
        }
Exemple #7
0
        public static void StartScaleAnimation(this UIElement element, Vector3?from = null, Vector3?to = null,
                                               double duration = 800, int delay = 0, CompositionEasingFunction easing = null, Action completed = null,
                                               AnimationIterationBehavior iterationBehavior = AnimationIterationBehavior.Count)
        {
            CompositionScopedBatch batch = null;

            var visual     = element.Visual();
            var compositor = visual.Compositor;

            if (completed != null)
            {
                batch            = compositor.CreateScopedBatch(CompositionBatchTypes.Animation);
                batch.Completed += (s, e) => completed();
            }

            if (to == null)
            {
                to = Vector3.One;
            }

            visual.StartAnimation("Scale",
                                  compositor.CreateVector3KeyFrameAnimation(from, to.Value, duration, delay, easing, iterationBehavior));

            batch?.End();
        }
        private CompositionScopedBatch RemoveLighting()
        {
            CompositionScopedBatch returnBatch = null;

            if (this._compositor != null)
            {
                returnBatch = this._compositor.CreateScopedBatch(CompositionBatchTypes.Animation);
                var animation2 = this._compositor.CreateColorKeyFrameAnimation();
                animation2.Duration = TimeSpan.FromSeconds(2);
                animation2.InsertKeyFrame(1, Colors.White);
                this._ambientLight.StartAnimation("Color", animation2);

                var animation = this._compositor.CreateScalarKeyFrameAnimation();
                animation.Duration = TimeSpan.FromSeconds(2);
                animation.InsertKeyFrame(1, 40.0f);
                this._pointLight.StartAnimation("LinearAttenuation", animation);

                returnBatch.Completed += (o, e) =>
                {
                    if (this._pointLight != null)
                    {
                        this._pointLight.Dispose();
                        this._pointLight = null;
                    }

                    if (this._ambientLight != null)
                    {
                        this._ambientLight.Dispose();
                        this._ambientLight = null;
                    }
                };
            }

            return(returnBatch);
        }
        public void StopBuffering(bool lightingdisabled)
        {
            if (this.IsBuffering)
            {
                CompositionScopedBatch batch = null;

                if (!lightingdisabled)
                {
                    batch = this.RemoveLighting();
                }
                else
                {
                    batch = this._compositor.CreateScopedBatch(CompositionBatchTypes.Animation);
                }

                this.RemoveText(batch, this._bufferingMessage);
                if (batch != null)
                {
                    batch.Completed += (o, e) =>
                    {
                        this.IsBuffering = false;
                    };

                    batch.End();
                }
            }
        }
Exemple #10
0
        public static void StartRotationAnimation(this UIElement element, Vector3 rotationAxis, float?from = null, float to = 0,
                                                  double duration = 800, int delay = 0, CompositionEasingFunction easing = null, Action completed = null,
                                                  AnimationIterationBehavior iterationBehavior = AnimationIterationBehavior.Count)
        {
            CompositionScopedBatch batch = null;

            var visual     = element.Visual();
            var compositor = visual.Compositor;

            if (completed != null)
            {
                batch            = compositor.CreateScopedBatch(CompositionBatchTypes.Animation);
                batch.Completed += (s, e) => completed();
            }

            visual.RotationAxis = rotationAxis;

            visual.StartAnimation("RotationAngleInDegrees",
                                  compositor.CreateScalarKeyFrameAnimation(from, to, duration, delay, easing, iterationBehavior));

            if (batch != null)
            {
                batch.End();
            }
        }
        public static void StartTranslationAnimation(this UIElement element, Vector2?from = null, Vector2?to = null,
                                                     double duration = 800, int delay = 0, CompositionEasingFunction easing = null, Action completed = null,
                                                     AnimationIterationBehavior iterationBehavior = AnimationIterationBehavior.Count)
        {
            CompositionScopedBatch batch = null;

            ElementCompositionPreview.SetIsTranslationEnabled(element, true);
            var visual     = element.Visual();
            var compositor = visual.Compositor;

            if (completed != null)
            {
                batch            = compositor.CreateScopedBatch(CompositionBatchTypes.Animation);
                batch.Completed += (s, e) => completed();
            }

            if (to == null)
            {
                to = Vector2.Zero;
            }

            visual.StartAnimation("Translation.XY", compositor.CreateVector2KeyFrameAnimation(from, to.Value, duration, delay, easing, iterationBehavior));

            batch?.End();
        }
Exemple #12
0
        private void UpdateContent()
        {
            var width      = (float)ActualWidth;
            var newContent = ViewModel.IsInPomodoro ? (UIElement) new EllipseClipWorkControl() : new EllipseClipPlayControl();

            Root.Children.Add(newContent);
            var visual = ElementCompositionPreview.GetElementVisual(newContent);

            visual.Offset = new Vector3(width, 0, 0);
            var animation = Compositor.CreateVector3KeyFrameAnimation();
            var easing    = Compositor.CreateCubicBezierEasingFunction(new Vector2(0.1f, 0.9f), new Vector2(0.2f, 1f));

            animation.Duration = TimeSpan.FromSeconds(1);
            animation.InsertKeyFrame(1, Vector3.Zero, easing);
            visual.StartAnimation(nameof(Visual.Offset), animation);

            if (_oldVisual != null)
            {
                animation = Compositor.CreateVector3KeyFrameAnimation();
                easing    = Compositor.CreateCubicBezierEasingFunction(new Vector2(0.1f, 0.9f), new Vector2(0.2f, 1f));

                animation.Duration = TimeSpan.FromSeconds(1);
                animation.InsertKeyFrame(1, new Vector3(-width, 0, 0), easing);


                CompositionScopedBatch batch = Compositor.CreateScopedBatch(CompositionBatchTypes.Animation);

                _oldVisual.StartAnimation(nameof(Visual.Offset), animation);

                batch.Completed += (s, e) => Root.Children.RemoveAt(0);
                batch.End();
            }

            _oldVisual = visual;
        }
        // This animation has constant duration, speedy changes depending on the distance
        // between sourceElement and targetElement.
        public async Task StartAnimation2(FrameworkElement sourceElement, FrameworkElement targetElement)
        {
            Point point = sourceElement.TransformToVisual(_rootElement).TransformPoint(new Point(0, 0));

            CompositionDrawingSurface surface = await CompositionDrawingSurfaceFacade1.GetCompositionDrawingSurface(sourceElement, _compositor);

            SpriteVisual spriteVisual = _compositor.CreateSpriteVisual();

            spriteVisual.Brush  = _compositor.CreateSurfaceBrush(surface);
            spriteVisual.Size   = new Vector2((float)surface.Size.Width, (float)surface.Size.Height);
            spriteVisual.Offset = new Vector3((float)point.X, (float)point.Y, 0f);
            _containerVisual.Children.InsertAtBottom(spriteVisual);

            Vector3 targetOffset = GetTargetOffset(targetElement);
            Vector3KeyFrameAnimation offsetAnimation = _compositor.CreateVector3KeyFrameAnimation();

            Vector2 targetSize = GetTargetSize(targetElement);
            Vector2KeyFrameAnimation sizeAnimation = _compositor.CreateVector2KeyFrameAnimation();

            var newWidth  = (float)(sourceElement.ActualWidth * 1.3);
            var newHeight = (float)(sourceElement.ActualHeight * 1.3);
            var newX      = (float)(point.X - (newWidth - sourceElement.ActualWidth) / 2);
            var newY      = (float)(point.Y - (newHeight - sourceElement.ActualHeight) / 2);

            double sizeDurationInMs      = 250;
            double distance              = Math.Sqrt(Math.Pow(targetOffset.X - newX, 2) + Math.Pow(targetOffset.Y - newY, 2));
            double offsetDurationInMs    = distance / 2;
            double animationDurationInMs = sizeDurationInMs + offsetDurationInMs;

            sizeAnimation.Duration   = TimeSpan.FromMilliseconds(animationDurationInMs);
            offsetAnimation.Duration = TimeSpan.FromMilliseconds(animationDurationInMs);

            SetAnimationDefautls(offsetAnimation);
            SetAnimationDefautls(sizeAnimation);

            var normalizedProgressKey0 = (float)(sizeDurationInMs / animationDurationInMs);

            offsetAnimation.InsertKeyFrame(normalizedProgressKey0, new Vector3(newX, newY, 0f));
            sizeAnimation.InsertKeyFrame(normalizedProgressKey0, new Vector2(newWidth, newHeight));

            const float normalizedProgressKey1 = 1f;

            offsetAnimation.InsertKeyFrame(normalizedProgressKey1, targetOffset, _compositor.CreateLinearEasingFunction());
            sizeAnimation.InsertKeyFrame(normalizedProgressKey1, targetSize, _compositor.CreateLinearEasingFunction());

            CompositionScopedBatch myScopedBatch = _compositor.CreateScopedBatch(CompositionBatchTypes.Animation);
            var batchCompletitionAwaiter         = new BatchCompletitionAwaiter(myScopedBatch);

            spriteVisual.StartAnimation("Offset", offsetAnimation);
            spriteVisual.StartAnimation("Size", sizeAnimation);
            myScopedBatch.End();
            await batchCompletitionAwaiter.Completed();

            myScopedBatch.Dispose();
            spriteVisual.Dispose();
            surface.Dispose();
            offsetAnimation.Dispose();
            sizeAnimation.Dispose();
        }
Exemple #14
0
        /// <summary>
        /// Starts all animations and returns an awaitable task.
        /// </summary>
        /// <returns>A <see cref="Task"/> that can be awaited until all animations have completed</returns>
        public async Task StartAsync()
        {
            foreach (var set in _animationSets)
            {
                await set.StartAsync();
            }

            if (_batch != null)
            {
                if (!_batch.IsEnded)
                {
                    _batch.End();
                }

                _batch.Completed -= Batch_Completed;
            }

            foreach (var property in _directPropertyChanges)
            {
                typeof(Visual).GetProperty(property.Key).SetValue(Visual, property.Value);
            }

            foreach (var definition in _directEffectPropertyChanges)
            {
                definition.EffectBrush.Properties.InsertScalar(definition.PropertyName, definition.Value);
            }

            List <Task> tasks = new List <Task>();

            if (_animations.Count > 0 || _effectAnimations.Count > 0)
            {
                _batch            = _compositor.CreateScopedBatch(CompositionBatchTypes.Animation);
                _batch.Completed += Batch_Completed;

                foreach (var anim in _animations)
                {
                    Visual.StartAnimation(anim.Key, anim.Value);
                }

                foreach (var effect in _effectAnimations)
                {
                    effect.EffectBrush.StartAnimation(effect.PropertyName, effect.Animation);
                }

                Task compositionTask = Task.Run(() =>
                {
                    _manualResetEvent.Reset();
                    _manualResetEvent.WaitOne();
                });

                _batch.End();

                tasks.Add(compositionTask);
            }

            tasks.Add(_storyboard.BeginAsync());

            await Task.WhenAll(tasks);
        }
Exemple #15
0
        private void OnFlashTimerTick(object sender, object e)
        {
            _reverseAnimationActive = true;

            //Flip button visual
            var btn1Visual = ElementCompositionPreview.GetElementVisual(_firstButton);
            var btn2Visual = ElementCompositionPreview.GetElementVisual(_secondButton);
            var compositor = btn1Visual.Compositor;

            //Get a visual for the content
            var btn1Content       = VisualTreeHelper.GetChild(VisualTreeHelper.GetChild(_firstButton, 0), 0);
            var btn1ContentVisual = ElementCompositionPreview.GetElementVisual(btn1Content as FrameworkElement);
            var btn2Content       = VisualTreeHelper.GetChild(VisualTreeHelper.GetChild(_secondButton, 0), 0);
            var btn2ContentVisual = ElementCompositionPreview.GetElementVisual(btn2Content as FrameworkElement);

            var easing = compositor.CreateLinearEasingFunction();

            if (_reverseFlipBatchAnimation != null)
            {
                _reverseFlipBatchAnimation.Completed -= ReverseFlipBatchAnimation_Completed;
                _reverseFlipBatchAnimation.Dispose();
            }

            _reverseFlipBatchAnimation            = compositor.CreateScopedBatch(CompositionBatchTypes.Animation);
            _reverseFlipBatchAnimation.Completed += ReverseFlipBatchAnimation_Completed;

            ScalarKeyFrameAnimation flipAnimation = compositor.CreateScalarKeyFrameAnimation();

            flipAnimation.InsertKeyFrame(0.000001f, 0);
            flipAnimation.InsertKeyFrame(0.999999f, -180, easing);
            flipAnimation.InsertKeyFrame(1f, 0);
            flipAnimation.Duration          = TimeSpan.FromMilliseconds(400);
            flipAnimation.IterationBehavior = AnimationIterationBehavior.Count;
            flipAnimation.IterationCount    = 1;
            btn1Visual.CenterPoint          = new Vector3((float)(0.5 * _firstButton.ActualWidth), (float)(0.5f * _firstButton.ActualHeight), 0f);
            btn1Visual.RotationAxis         = new Vector3(0.0f, 1f, 0f);
            btn2Visual.CenterPoint          = new Vector3((float)(0.5 * _secondButton.ActualWidth), (float)(0.5f * _secondButton.ActualHeight), 0f);
            btn2Visual.RotationAxis         = new Vector3(0.0f, 1f, 0f);

            ScalarKeyFrameAnimation appearAnimation = compositor.CreateScalarKeyFrameAnimation();

            appearAnimation.InsertKeyFrame(0.0f, 1);
            appearAnimation.InsertKeyFrame(0.399999f, 1);
            appearAnimation.InsertKeyFrame(0.4f, 0);
            appearAnimation.InsertKeyFrame(1f, 0);
            appearAnimation.Duration          = TimeSpan.FromMilliseconds(400);
            appearAnimation.IterationBehavior = AnimationIterationBehavior.Count;
            appearAnimation.IterationCount    = 1;

            btn1Visual.StartAnimation(nameof(btn1Visual.RotationAngleInDegrees), flipAnimation);
            btn2Visual.StartAnimation(nameof(btn2Visual.RotationAngleInDegrees), flipAnimation);
            btn1ContentVisual.StartAnimation(nameof(btn1ContentVisual.Opacity), appearAnimation);
            btn2ContentVisual.StartAnimation(nameof(btn2ContentVisual.Opacity), appearAnimation);
            _reverseFlipBatchAnimation.End();

            _flashTimer.Stop();
            GazeInput.SetInteraction(buttonMatrix, Interaction.Enabled);
        }
Exemple #16
0
        // Define and setup the Green Square Visual that will be animated
        public void SetupVisual()
        {
            // Intialize the Compositor
            _compositor = new Compositor();
            _root       = ElementCompositionPreview.GetElementVisual(Container);
            _compositor = _root.Compositor;

            _linear = _compositor.CreateLinearEasingFunction();

            // Create Green Square
            var colorVisual = _compositor.CreateSpriteVisual();

            colorVisual.Brush       = _compositor.CreateColorBrush(Colors.Green);
            colorVisual.Size        = new Vector2(150.0f, 150.0f);
            colorVisual.Offset      = new Vector3(250.0f, 50.0f, 0.0f);
            colorVisual.CenterPoint = new Vector3(75.0f, 75.0f, 0.0f);
            _target = colorVisual;

            // Create Blue Square
            var colorVisual2 = _compositor.CreateSpriteVisual();

            colorVisual2.Brush     = _compositor.CreateColorBrush(Colors.Aqua);
            colorVisual2.Size      = new Vector2(200.0f, 150.0f);
            colorVisual2.Offset    = new Vector3(25.0f, 50.0f, 0.0f);
            colorVisual2.IsVisible = false;
            _target2 = colorVisual2;

            // Add the Blue and Green square visuals to the tree
            _mainContainer = _compositor.CreateContainerVisual();
            ElementCompositionPreview.SetElementChildVisual(Container, _mainContainer);
            _mainContainer.Children.InsertAtTop(_target);
            _mainContainer.Children.InsertAtTop(_target2);

            // Create Scoped batch for animations
            _batch = _compositor.CreateScopedBatch(CompositionBatchTypes.Animation);

            // Add Animation1 to the batch
            Animation1(_target);

            // Suspend the batch to exclude an animation
            _batch.Suspend();

            // Exluding Animation2 from batch
            Animation2(_target);

            // Resuming the batch to collect additional animations
            _batch.Resume();

            // Add Animation3 to the batch
            Animation3(_target);

            // Batch is ended an no objects can be added
            _batch.End();

            // Method triggered when batch completion event fires
            _batch.Completed += OnBatchCompleted;
        }
Exemple #17
0
 private void CleanupScopeBatch()
 {
     if (_scopeBatch != null)
     {
         _scopeBatch.Completed -= ScopeBatch_Completed;
         _scopeBatch.Dispose();
         _scopeBatch = null;
     }
 }
Exemple #18
0
        async void ResetBoard()
        {
            PlayAgainText.Visibility = Visibility.Collapsed;
            _gameOver               = false;
            _firstButton            = null;
            _secondButton           = null;
            _numMoves               = 0;
            MoveCountTextBlock.Text = _numMoves.ToString();
            _remaining              = _boardRows * _boardColumns;
            var pairs = (_boardRows * _boardColumns) / 2;

            List <string> listContent;

            if (_usePictures)
            {
                try
                {
                    listContent = await GetPicturesContent(pairs);
                }
                catch
                {
                    listContent  = GetSymbolContent(pairs);
                    _usePictures = false;
                }
            }
            else
            {
                listContent = GetSymbolContent(pairs);
            }

            List <Button> listButtons = ShuffleList(GetButtonList());

            var compositor = ElementCompositionPreview.GetElementVisual(this).Compositor;

            if (_resetBatchAnimation != null)
            {
                _resetBatchAnimation.Completed -= ResetBatchAnimation_Completed;
                _resetBatchAnimation.Dispose();
            }

            _resetBatchAnimation            = compositor.CreateScopedBatch(CompositionBatchTypes.Animation);
            _resetBatchAnimation.Completed += ResetBatchAnimation_Completed;;

            foreach (Button button in listButtons)
            {
                FlipCardFaceDown(button);
                GazeInput.SetInteraction(button, Interaction.Inherited);
            }
            _resetBatchAnimation.End();

            for (int i = 0; i < _boardRows * _boardColumns; i += 2)
            {
                listButtons[i].Tag     = listContent[i / 2];
                listButtons[i + 1].Tag = listContent[i / 2];
            }
        }
Exemple #19
0
        private void DialogDismissedHandler(IUICommand command)
        {
            // Start a scoped batch so we can register to completion event and hide the destination layer
            _scopeBatch = _compositor.CreateScopedBatch(CompositionBatchTypes.Animation);

            // Start the hide animation to fade out the destination effect
            ScalarKeyFrameAnimation hideAnimation = _compositor.CreateScalarKeyFrameAnimation();

            hideAnimation.InsertKeyFrame(0f, 1f);
            hideAnimation.InsertKeyFrame(1.0f, 0f);
            hideAnimation.Duration = TimeSpan.FromMilliseconds(1000);
            _destinationSprite.StartAnimation("Opacity", hideAnimation);

            // Use whichever effect is currently selected
            ComboBoxItem item = EffectSelection.SelectedValue as ComboBoxItem;

            switch ((EffectTypes)item.Tag)
            {
            case EffectTypes.Mask:
            {
                CompositionSurfaceBrush  brush          = ((CompositionEffectBrush)_destinationSprite.Brush).GetSourceParameter("SecondSource") as CompositionSurfaceBrush;
                Vector2KeyFrameAnimation scaleAnimation = _compositor.CreateVector2KeyFrameAnimation();
                scaleAnimation.InsertKeyFrame(1f, new Vector2(2.0f, 2.0f));
                scaleAnimation.Duration = TimeSpan.FromMilliseconds(1000);
                brush.StartAnimation("Scale", scaleAnimation);
                break;
            }

            case EffectTypes.VividLight:
            {
                CompositionEffectBrush brush         = (CompositionEffectBrush)_destinationSprite.Brush;
                ColorKeyFrameAnimation coloAnimation = _compositor.CreateColorKeyFrameAnimation();
                coloAnimation.InsertKeyFrame(1f, Color.FromArgb(255, 100, 100, 100));
                coloAnimation.Duration = TimeSpan.FromMilliseconds(1500);
                brush.StartAnimation("Base.Color", coloAnimation);
                break;
            }

            case EffectTypes.Hue:
            {
                CompositionEffectBrush  brush           = (CompositionEffectBrush)_destinationSprite.Brush;
                ScalarKeyFrameAnimation rotateAnimation = _compositor.CreateScalarKeyFrameAnimation();
                rotateAnimation.InsertKeyFrame(1f, 0f);
                rotateAnimation.Duration = TimeSpan.FromMilliseconds(1500);
                brush.StartAnimation("Hue.Angle", rotateAnimation);
                break;
            }

            default:
                break;
            }

            //Scoped batch completed event
            _scopeBatch.Completed += ScopeBatch_Completed;
            _scopeBatch.End();
        }
        /// <summary>
        /// 停止故事板。
        /// </summary>
        public void Stop()
        {
            _animationBatch?.Dispose();
            _animationBatch = null;

            foreach (var animation in Children)
            {
                animation.TargetVisual.StopAnimation(animation.TargetProperty.ToString());
            }
        }
Exemple #21
0
        private void ScopedBatch_Completed(object sender, CompositionBatchCompletedEventArgs args)
        {
            CompositionScopedBatch batch = sender as CompositionScopedBatch;

            Action action = _dictionary[batch.Comment];

            _dictionary.Remove(batch.Comment);

            action();
        }
        /// <inheritdoc/>
        protected override Task OnStartAsync()
        {
            CompositionScopedBatch batch = TargetVisual.Compositor.CreateScopedBatch(CompositionBatchTypes.Animation);
            TaskCompletionSource   tcs   = new TaskCompletionSource();

            batch.Completed += (s, e) => tcs.SetResult();
            StartAnimations();
            batch.End();
            return(tcs.Task);
        }
Exemple #23
0
        /// <summary>
        /// 停止故事板。
        /// </summary>
        public void Stop()
        {
            _animationBatch?.Dispose();
            _animationBatch = null;

            foreach (var animation in Children)
            {
                animation.TargetVisual.StopAnimation(animation.TargetProperty.ToString());
            }
        }
Exemple #24
0
        private void Batch_CrossFadeCompleted(object sender, CompositionBatchCompletedEventArgs args)
        {
            BackgroundImage.Brush = BackgroundImage.SurfaceBrush;

            // Dispose the image
            ((CompositionDrawingSurface)_previousSurfaceBrush.Surface).Dispose();
            _previousSurfaceBrush.Surface = null;

            // Clear out the batch
            _crossFadeBatch = null;
        }
Exemple #25
0
 private void HideButton_Click(object sender, RoutedEventArgs e)
 {
     if (!_isHidden)
     {
         _batch            = _compositor.CreateScopedBatch(CompositionBatchTypes.Animation);
         _batch.Completed += OnBatchCompleted;
         _visual.StartAnimation("Opacity", _hideAnimation);
         _batch.End();
         _isHidden = true;
     }
 }
        private void ExitAnimBatch_Completed(object sender, CompositionBatchCompletedEventArgs args)
        {
            CompositionScopedBatch sourceBatch = sender as CompositionScopedBatch;
            DeviceContainer        container   = _containers.FirstOrDefault((a) => a.AnimBatch == sourceBatch);

            if (container == null)
            {
                throw new Exception("Exit scoped batch completed for unknown container");
            }

            RemoveContainer(container);
        }
Exemple #27
0
        public void StartEntranceEffect()
        {
            ContainerVisual container  = (ContainerVisual)ElementCompositionPreview.GetElementChildVisual(BasePage);
            Compositor      compositor = container.Compositor;

            // 设置缩放和动画
            const float               ScaleFactor = 20f;
            TimeSpan                  duration    = TimeSpan.FromMilliseconds(1200);
            LinearEasingFunction      linearEase  = compositor.CreateLinearEasingFunction();
            CubicBezierEasingFunction easeInOut   = compositor.CreateCubicBezierEasingFunction(new Vector2(.38f, 0f), new Vector2(.45f, 1f));

            // 创建淡出动画
            ScalarKeyFrameAnimation fadeOutAnimation = compositor.CreateScalarKeyFrameAnimation();

            fadeOutAnimation.InsertKeyFrame(1, 0);
            fadeOutAnimation.Duration = duration;

            // Grid的动画
            Vector2KeyFrameAnimation scaleUpGridAnimation = compositor.CreateVector2KeyFrameAnimation();

            scaleUpGridAnimation.InsertKeyFrame(0.1f, new Vector2(1 / ScaleFactor, 1 / ScaleFactor));
            scaleUpGridAnimation.InsertKeyFrame(1, new Vector2(1, 1));
            scaleUpGridAnimation.Duration = duration;

            // 初始屏动画
            Vector2KeyFrameAnimation scaleUpSplashAnimation = compositor.CreateVector2KeyFrameAnimation();

            scaleUpSplashAnimation.InsertKeyFrame(0, new Vector2(1, 1));
            scaleUpSplashAnimation.InsertKeyFrame(1, new Vector2(ScaleFactor, ScaleFactor));
            scaleUpSplashAnimation.Duration = duration;

            // 设置Grid的中心缩放视觉
            Visual gridVisual = ElementCompositionPreview.GetElementVisual(UIToShow);

            gridVisual.Size        = UIToShow.ActualSize;
            gridVisual.CenterPoint = new Vector3(gridVisual.Size.X, gridVisual.Size.Y, 0) * .5f;

            // 创建一个视觉组,当改组所有视觉执行完后不再显示
            CompositionScopedBatch batch = compositor.CreateScopedBatch(CompositionBatchTypes.Animation);

            container.StartAnimation("Opacity", fadeOutAnimation);
            container.StartAnimation("Scale.XY", scaleUpSplashAnimation);
            gridVisual.StartAnimation("Scale.XY", scaleUpGridAnimation);

            batch.Completed += (s, a) =>
            {
                ElementCompositionPreview.SetElementChildVisual(BasePage, null);
                SurfaceLoader.Uninitialize();
                AnimationCompleted?.Invoke(this, null);
            };
            batch.End();
        }
        /// <summary>
        /// Start animations and re-parent to destination UI Elmenent to finish the operations
        /// </summary>
        /// <param name="destinationElement">Destination UIElement where Visual should show up after page has loaded</param>
        /// <param name="containerVisual">ContainerVisual that contains Visual which needs to show in UIElement</param>
        /// <param name="newContainerVisual">ContainerVisual after visual is parented to UIElement</param>
        public static void InitiateContinuity(FrameworkElement destinationElement, ContainerVisual containerVisual, out ContainerVisual newContainerVisual)
        {
            if (null == containerVisual || null == destinationElement)
            {
                newContainerVisual = null;
                return;
            }
            //Get the frame of Window
            var        rootFrame  = AppShell.Current;
            Visual     rootVisual = ElementCompositionPreview.GetElementVisual(AppShell.Current);
            Compositor compositor = rootVisual.Compositor;
            //Create Temporary Container. this will be added to final UIElement
            ContainerVisual tempContainer = compositor.CreateContainerVisual();
            // Get Sprite Visual from incoming container
            var spriteHeroImage = containerVisual.Children.FirstOrDefault();

            //Create animation scoped batch to track animation completion and to complete re-parenting
            CompositionScopedBatch scopeBatch = compositor.CreateScopedBatch(CompositionBatchTypes.Animation);

            //Get coordinates of UIElement in reference to root so that it can be used for animations final value
            var coordinate = destinationElement.TransformToVisual(rootFrame);
            var position   = coordinate.TransformPoint(new Point(0, 0));

            //Create offset animation to make visual move on screen
            Vector3KeyFrameAnimation offsetAnimation = compositor.CreateVector3KeyFrameAnimation();

            offsetAnimation.InsertKeyFrame(1f, new System.Numerics.Vector3((float)position.X, (float)position.Y, 0));
            offsetAnimation.Duration = TimeSpan.FromMilliseconds(600);

            //Create size animation to change size of the visuals
            Vector2KeyFrameAnimation sizeAnimation = compositor.CreateVector2KeyFrameAnimation();

            sizeAnimation.InsertKeyFrame(1f, new System.Numerics.Vector2((float)destinationElement.ActualWidth, (float)destinationElement.ActualHeight));
            sizeAnimation.Duration = TimeSpan.FromMilliseconds(600);

            //Start Animations
            spriteHeroImage.StartAnimation("size", sizeAnimation);
            containerVisual.StartAnimation("offset", offsetAnimation);
            //Scoped batch completed event.
            scopeBatch.Completed += (o, e) =>
            {
                //Re-parent SpriteVisual to temp container and add temp container to UIElement as animations are finished.
                spriteHeroImage.Offset = new System.Numerics.Vector3(0, 0, 2000);
                containerVisual.Children.Remove(spriteHeroImage);
                tempContainer.Children.InsertAtTop(spriteHeroImage);
                ElementCompositionPreview.SetElementChildVisual(destinationElement, tempContainer);
                containerVisual = null;
            };
            newContainerVisual = tempContainer;

            scopeBatch.End();
        }
Exemple #29
0
        private void HideCustomSplashScreen()
        {
            ContainerVisual container  = (ContainerVisual)ElementCompositionPreview.GetElementChildVisual(this);
            Compositor      compositor = container.Compositor;

            // Setup some constants for scaling and animating
            const float               ScaleFactor = 20f;
            TimeSpan                  duration    = TimeSpan.FromMilliseconds(1200);
            LinearEasingFunction      linearEase  = compositor.CreateLinearEasingFunction();
            CubicBezierEasingFunction easeInOut   = compositor.CreateCubicBezierEasingFunction(new Vector2(.38f, 0f), new Vector2(.45f, 1f));

            // Create the fade animation which will target the opacity of the outgoing splash screen
            ScalarKeyFrameAnimation fadeOutAnimation = compositor.CreateScalarKeyFrameAnimation();

            fadeOutAnimation.InsertKeyFrame(1, 0);
            fadeOutAnimation.Duration = duration;

            // Create the scale up animation for the grid
            Vector2KeyFrameAnimation scaleUpGridAnimation = compositor.CreateVector2KeyFrameAnimation();

            scaleUpGridAnimation.InsertKeyFrame(0.1f, new Vector2(1 / ScaleFactor, 1 / ScaleFactor));
            scaleUpGridAnimation.InsertKeyFrame(1, new Vector2(1, 1));
            scaleUpGridAnimation.Duration = duration;

            // Create the scale up animation for the Splash screen visuals
            Vector2KeyFrameAnimation scaleUpSplashAnimation = compositor.CreateVector2KeyFrameAnimation();

            scaleUpSplashAnimation.InsertKeyFrame(0, new Vector2(1, 1));
            scaleUpSplashAnimation.InsertKeyFrame(1, new Vector2(ScaleFactor, ScaleFactor));
            scaleUpSplashAnimation.Duration = duration;

            // Configure the grid visual to scale from the center
            Visual gridVisual = ElementCompositionPreview.GetElementVisual(MainFrame);

            gridVisual.Size        = new Vector2((float)MainFrame.ActualWidth, (float)MainFrame.ActualHeight);
            gridVisual.CenterPoint = new Vector3(gridVisual.Size.X, gridVisual.Size.Y, 0) * .5f;


            //
            // Create a scoped batch for the animations.  When the batch completes, we can dispose of the
            // splash screen visuals which will no longer be visible.
            //

            CompositionScopedBatch batch = compositor.CreateScopedBatch(CompositionBatchTypes.Animation);

            container.StartAnimation("Opacity", fadeOutAnimation);
            container.StartAnimation("Scale.XY", scaleUpSplashAnimation);
            gridVisual.StartAnimation("Scale.XY", scaleUpGridAnimation);

            batch.Completed += Batch_Completed;
            batch.End();
        }
Exemple #30
0
        public void RefreshCompletedAnimation(UIElement refreshVisualizer, UIElement infoProvider)
        {
            ValidateAndStoreParameters(refreshVisualizer, infoProvider, null);

            if ((refreshVisualizerRefreshCompletedAnimation == null || infoProviderRefreshCompletedAnimation == null || refreshCompletedAnimationNeedsUpdating) && compositor != null)
            {
                refreshVisualizerRefreshCompletedAnimation          = compositor.CreateScalarKeyFrameAnimation();
                refreshVisualizerRefreshCompletedAnimation.Duration = TimeSpan.FromMilliseconds(100);
                infoProviderRefreshCompletedAnimation          = compositor.CreateScalarKeyFrameAnimation();
                infoProviderRefreshCompletedAnimation.Duration = TimeSpan.FromMilliseconds(100);
                infoProviderRefreshCompletedAnimation.InsertKeyFrame(1.0f, 0.0f);

                switch (refreshPullDirection)
                {
                case RefreshPullDirection.TopToBottom:
                    refreshVisualizerRefreshCompletedAnimation.InsertKeyFrame(1.0f, -(refreshVisualizerVisual.Size.Y));
                    break;

                case RefreshPullDirection.BottomToTop:
                    refreshVisualizerRefreshCompletedAnimation.InsertKeyFrame(1.0f, refreshVisualizerVisual.Size.Y);
                    break;

                case RefreshPullDirection.LeftToRight:
                    refreshVisualizerRefreshCompletedAnimation.InsertKeyFrame(1.0f, -(refreshVisualizerVisual.Size.X));
                    break;

                case RefreshPullDirection.RightToLeft:
                    refreshVisualizerRefreshCompletedAnimation.InsertKeyFrame(1.0f, refreshVisualizerVisual.Size.X);
                    break;
                }
                refreshCompletedAnimationNeedsUpdating = false;
            }

            if (compositor != null)
            {
                refreshCompletedScopedBatch            = compositor.CreateScopedBatch(CompositionBatchTypes.Animation);
                refreshCompletedScopedBatch.Completed += RefreshCompletedBatchCompleted;
            }

            if (refreshVisualizerRefreshCompletedAnimation != null && infoProviderRefreshCompletedAnimation != null)
            {
                string animatedProperty = GetAnimatedPropertyName();
                refreshVisualizerVisual.StartAnimation(animatedProperty, refreshVisualizerRefreshCompletedAnimation);
                infoProviderVisual.StartAnimation(animatedProperty, infoProviderRefreshCompletedAnimation);
            }

            if (refreshCompletedScopedBatch != null)
            {
                refreshCompletedScopedBatch.End();
            }
        }
        private void EnterAnimBatch_Completed(object sender, CompositionBatchCompletedEventArgs args)
        {
            CompositionScopedBatch sourceBatch = sender as CompositionScopedBatch;
            DeviceContainer        container   = _containers.FirstOrDefault((a) => a.AnimBatch == sourceBatch);

            if (container == null)
            {
                throw new Exception("Enter scoped batch completed for unknown container");
            }

            container.DeviceElement.SetValue(Canvas.ZIndexProperty, 101);

            container.State = ContainerState.Normal;
        }
        /// <summary>
        /// 开始故事板。
        /// </summary>
        public void Start()
        {
            if (_animationBatch != null)
            {
                _animationBatch.Completed -= _animationBatch_Completed;
                _animationBatch.Dispose();
            }

            _animationBatch = AnimationBatchFactory.Singleton.StartAnimations(Children);

            if (_animationBatch == null)
            {
                return;
            }

            _animationBatch.Completed += _animationBatch_Completed;
        }
Exemple #33
0
        // Define and setup the Green Square Visual that will be animated 
        public void SetupVisual()
        {
            // Intialize the Compositor
            _compositor = new Compositor();
            _root = (ContainerVisual)ElementCompositionPreview.GetElementVisual(Container);
            _compositor = _root.Compositor;

            _linear = _compositor.CreateLinearEasingFunction();

            // Create Green Square
            var colorVisual = _compositor.CreateSpriteVisual();
            colorVisual.Brush = _compositor.CreateColorBrush(Colors.Green);
            colorVisual.Size = new Vector2(150.0f, 150.0f);
            colorVisual.Offset = new Vector3(250.0f, 50.0f, 0.0f);
            colorVisual.CenterPoint = new Vector3(75.0f, 75.0f, 0.0f);
            _target = colorVisual;

            // Create Blue Square
            var colorVisual2 = _compositor.CreateSpriteVisual();
            colorVisual2.Brush = _compositor.CreateColorBrush(Colors.Aqua);
            colorVisual2.Size = new Vector2(200.0f, 150.0f);
            colorVisual2.Offset = new Vector3(25.0f, 50.0f, 0.0f);
            colorVisual2.IsVisible = false; 
            _target2 = colorVisual2;

            // Add the Blue and Green square visuals to the tree
            _mainContainer = _compositor.CreateContainerVisual();
            ElementCompositionPreview.SetElementChildVisual(Container, _mainContainer);
            _mainContainer.Children.InsertAtTop(_target);
            _mainContainer.Children.InsertAtTop(_target2);

            // Create Scoped batch for animations
            _batch = _compositor.CreateScopedBatch(CompositionBatchTypes.Animation);

            // Add Animation1 to the batch
            Animation1(_target);

            // Suspend the batch to exclude an animation
            _batch.Suspend();

            // Exluding Animation2 from batch
            Animation2(_target);

            // Resuming the batch to collect additional animations
            _batch.Resume();

            // Add Animation3 to the batch
            Animation3(_target);

            // Batch is ended an no objects can be added
            _batch.End();

            // Method triggered when batch completion event fires
            _batch.Completed += OnBatchCompleted;
        }
        public void Start(UIElement newParent, CompositionImage targetImage, ScrollViewer scrollViewer, UIElement animationTarget)
        {
            Visual transitionVisual = ElementCompositionPreview.GetElementChildVisual(_parent);
            ElementCompositionPreview.SetElementChildVisual(_parent, null);


            //
            // We need to reparent the transition visual under the new parent.  This is important to ensure
            // it's propertly clipped, etc.
            //

            GeneralTransform coordinate = newParent.TransformToVisual(_parent);
            Point position = coordinate.TransformPoint(new Point(0, 0));

            Vector3 currentOffset = transitionVisual.Offset;
            currentOffset.X -= (float)position.X;
            currentOffset.Y -= (float)position.Y;
            transitionVisual.Offset = currentOffset;

            _parent = newParent;
            _targetImage = targetImage;

            // Move the transition visual to it's new parent
            ElementCompositionPreview.SetElementChildVisual(_parent, transitionVisual);

            // Hide the target Image now since the handoff visual is still transitioning
            targetImage.Opacity = 0f;

            // Load image if necessary
            _imageLoaded = targetImage.IsContentLoaded;
            if (!_imageLoaded)
            {
                targetImage.ImageOpened += CompositionImage_ImageOpened;
            }

            //
            // Create a scoped batch around the animations.  When the batch completes, we know the animations
            // have finished and we can cleanup the transition related objects.
            //

            Compositor compositor = transitionVisual.Compositor;
            _scopeBatch = compositor.CreateScopedBatch(CompositionBatchTypes.Animation);

            //
            // Determine the offset between the parent and the target UIElement.  This will be used to calculate the
            // target position we are animating to.
            //

            coordinate = targetImage.TransformToVisual(_parent);
            position = coordinate.TransformPoint(new Point(0, 0));

            TimeSpan totalDuration = TimeSpan.FromMilliseconds(1000);
            Vector3KeyFrameAnimation offsetAnimation = compositor.CreateVector3KeyFrameAnimation();

            if (scrollViewer != null)
            {
                CompositionPropertySet scrollProperties = ElementCompositionPreview.GetScrollViewerManipulationPropertySet(scrollViewer);

                // Include the scroller offset as that is a factor
                position.X += scrollViewer.HorizontalOffset;
                position.Y += scrollViewer.VerticalOffset;


                //
                // Since the target position is relative to the target UIElement which can move, we need to construct
                // an expression to bind the target's position to the end position of our animation.
                //

                string expression = "Vector3(scrollingProperties.Translation.X, scrollingProperties.Translation.Y, 0) + itemOffset";
                offsetAnimation.InsertExpressionKeyFrame(1f, expression);
                offsetAnimation.SetReferenceParameter("scrollingProperties", scrollProperties);
                offsetAnimation.SetVector3Parameter("itemOffset", new Vector3((float)position.X, (float)position.Y, 0));
                offsetAnimation.Duration = totalDuration;
            }
            else
            {
                offsetAnimation.InsertKeyFrame(1, new Vector3((float)position.X, (float)position.Y, 0));
                offsetAnimation.Duration = totalDuration;
            }

            // Create size animation to change size of the visual
            Vector2KeyFrameAnimation sizeAnimation = compositor.CreateVector2KeyFrameAnimation();
            sizeAnimation.InsertKeyFrame(1f, new Vector2((float)targetImage.ActualWidth, (float)targetImage.ActualHeight));
            sizeAnimation.Duration = totalDuration;

            // Create the fade in animation for the other page content
            if (animationTarget != null)
            {
                Visual fadeVisual = ElementCompositionPreview.GetElementVisual(animationTarget);
                ScalarKeyFrameAnimation fadeIn = compositor.CreateScalarKeyFrameAnimation();
                fadeIn.InsertKeyFrame(0f, 0.0f);
                fadeIn.InsertKeyFrame(1f, 1.0f);
                fadeIn.Duration = totalDuration;
                fadeVisual.StartAnimation("Opacity", fadeIn);
            }

            //Start Animations 
            _sprite.StartAnimation("Size", sizeAnimation);
            _sprite.StartAnimation("Offset", offsetAnimation);

            //Scoped batch completed event
            _scopeBatch.Completed += ScopeBatch_Completed;
            _scopeBatch.End();

            // Clear the flag
            _animationCompleted = false;
        }
        private void Timer_Tick(object sender, object e)
        {
            var now = DateTime.Now;

            _batch = _compositor.CreateScopedBatch(CompositionBatchTypes.Animation);
            var animation = _compositor.CreateScalarKeyFrameAnimation();
            var seconds = (float)(int)now.TimeOfDay.TotalSeconds;
            animation.InsertKeyFrame(0.00f, seconds * 6);
            animation.InsertKeyFrame(1.00f, (seconds + 1) * 6);
            animation.Duration = TimeSpan.FromMilliseconds(900);
            _secondhand.StartAnimation(nameof(_secondhand.RotationAngleInDegrees), animation);
            _batch.End();
            _batch.Completed += Batch_Completed;
        }
        private void BackgroundImage_ImageChanged(object sender, RoutedEventArgs e)
        {
            if (_crossFadeBatch == null)
            {
                TimeSpan duration = TimeSpan.FromMilliseconds(1000);

                // Create the animations for cross-fading
                ScalarKeyFrameAnimation fadeInAnimation = _compositor.CreateScalarKeyFrameAnimation();
                fadeInAnimation.InsertKeyFrame(0, 0);
                fadeInAnimation.InsertKeyFrame(1, 1);
                fadeInAnimation.Duration = duration;

                ScalarKeyFrameAnimation fadeOutAnimation = _compositor.CreateScalarKeyFrameAnimation();
                fadeOutAnimation.InsertKeyFrame(0, 1);
                fadeOutAnimation.InsertKeyFrame(1, 0);
                fadeOutAnimation.Duration = duration;

                // Create a batch object so we can cleanup when the cross-fade completes.
                _crossFadeBatch = _compositor.CreateScopedBatch(CompositionBatchTypes.Animation);

                // Set the sources
                _crossFadeBrush.SetSourceParameter("ImageSource", BackgroundImage.SurfaceBrush);
                _crossFadeBrush.SetSourceParameter("ImageSource2", _previousSurfaceBrush);

                // Animate the source amounts to fade between
                _crossFadeBrush.StartAnimation("CrossFade.Source1Amount", fadeInAnimation);
                _crossFadeBrush.StartAnimation("CrossFade.Source2Amount", fadeOutAnimation);

                // Update the image to use the cross fade brush
                BackgroundImage.Brush = _crossFadeBrush;

                _crossFadeBatch.Completed += Batch_CrossFadeCompleted;
                _crossFadeBatch.End();
            }

            // Unhook the handler
            BackgroundImage.ImageOpened -= BackgroundImage_ImageChanged;
        }
        private void Batch_CrossFadeCompleted(object sender, CompositionBatchCompletedEventArgs args)
        {
            BackgroundImage.Brush = BackgroundImage.SurfaceBrush;

            // Dispose the image
            ((CompositionDrawingSurface)_previousSurfaceBrush.Surface).Dispose();
            _previousSurfaceBrush.Surface = null;

            // Clear out the batch
            _crossFadeBatch = null;
        }
        private void Timer_Tick(object sender, object e)
        {
            var now = DateTime.Now;

            _batch = _compositor.CreateScopedBatch(CompositionBatchTypes.Animation);
            var animation = _compositor.CreateScalarKeyFrameAnimation();
            var seconds = (float)(int)now.TimeOfDay.TotalSeconds;

            // This works:
            //animation.InsertKeyFrame(0.00f, seconds * 6);
            //animation.InsertKeyFrame(1.00f, (seconds + 1) * 6);

            // Just an example of using expressions:
            animation.SetScalarParameter("start", seconds * 6);
            animation.InsertExpressionKeyFrame(0.00f, "start");
            animation.SetScalarParameter("delta", 6.0f);
            animation.InsertExpressionKeyFrame(1.00f, "start + delta");

            animation.Duration = TimeSpan.FromMilliseconds(900);
            _secondhand.StartAnimation(nameof(_secondhand.RotationAngleInDegrees), animation);
            _batch.End();
            _batch.Completed += Batch_Completed;
        }
        private void DialogDismissedHandler(IUICommand command)
        {
            // Start a scoped batch so we can register to completion event and hide the destination layer
            _scopeBatch = _compositor.CreateScopedBatch(CompositionBatchTypes.Animation);

            // Start the hide animation to fade out the destination effect
            ScalarKeyFrameAnimation hideAnimation = _compositor.CreateScalarKeyFrameAnimation();
            hideAnimation.InsertKeyFrame(0f, 1f);
            hideAnimation.InsertKeyFrame(1.0f, 0f);
            hideAnimation.Duration = TimeSpan.FromMilliseconds(1000);
            _destinationSprite.StartAnimation("Opacity", hideAnimation);

            // Use whichever effect is currently selected
            ComboBoxItem item = EffectSelection.SelectedValue as ComboBoxItem;
            switch ((EffectTypes)item.Tag)
            {
                case EffectTypes.Mask:
                    {
                        CompositionSurfaceBrush brush = ((CompositionEffectBrush)_destinationSprite.Brush).GetSourceParameter("SecondSource") as CompositionSurfaceBrush;
                        Vector2KeyFrameAnimation scaleAnimation = _compositor.CreateVector2KeyFrameAnimation();
                        scaleAnimation.InsertKeyFrame(1f, new Vector2(2.0f, 2.0f));
                        scaleAnimation.Duration = TimeSpan.FromMilliseconds(1000);
                        brush.StartAnimation("Scale", scaleAnimation);
                        break;
                    }
                case EffectTypes.VividLight:
                    {
                        CompositionEffectBrush brush = (CompositionEffectBrush)_destinationSprite.Brush;
                        ColorKeyFrameAnimation coloAnimation = _compositor.CreateColorKeyFrameAnimation();
                        coloAnimation.InsertKeyFrame(1f, Color.FromArgb(255, 100, 100, 100));
                        coloAnimation.Duration = TimeSpan.FromMilliseconds(1500);
                        brush.StartAnimation("Base.Color", coloAnimation);
                        break;
                    }
                case EffectTypes.Hue:
                    {
                        CompositionEffectBrush brush = (CompositionEffectBrush)_destinationSprite.Brush;
                        ScalarKeyFrameAnimation rotateAnimation = _compositor.CreateScalarKeyFrameAnimation();
                        rotateAnimation.InsertKeyFrame(1f, 0f);
                        rotateAnimation.Duration = TimeSpan.FromMilliseconds(1500);
                        brush.StartAnimation("Hue.Angle", rotateAnimation);
                        break;
                    }
                default:
                    break;
            }

            //Scoped batch completed event
            _scopeBatch.Completed += ScopeBatch_Completed;
            _scopeBatch.End();
        }
 private void CleanupScopeBatch()
 {
     if (_scopeBatch != null)
     {
         _scopeBatch.Completed -= ScopeBatch_Completed;
         _scopeBatch.Dispose();
         _scopeBatch = null;
     }
 }