Пример #1
0
        public static void Uninitialize()
        {
            if (SlowOffAnimation != null)
            {
                SlowOffAnimation.Dispose();
                SlowOffAnimation = null;
            }

            if (NormalOnAnimation != null)
            {
                NormalOnAnimation.Dispose();
                NormalOnAnimation = null;
            }
        }
Пример #2
0
        public static void Initialize(Compositor compositor)
        {
            // Create keyframes to select and unselect:
            // - Since both Saturation and Opacity use float [0.0 -> 1.0], we can actually use the
            //   same keyframe instances and just bind to different properties.

            NormalOnAnimation = compositor.CreateScalarKeyFrameAnimation();
            NormalOnAnimation.InsertKeyFrame(1.0f, 1.0f /* opaque */);
            NormalOnAnimation.Duration = NormalTime;

            SlowOffAnimation = compositor.CreateScalarKeyFrameAnimation();
            SlowOffAnimation.InsertKeyFrame(1.0f, 0.0f /* transparent */);
            SlowOffAnimation.Duration = SlowTime;
        }
Пример #3
0
        public CompositionImage()
        {
            this.DefaultStyleKey = typeof(CompositionImage);
            this.Background = new SolidColorBrush(Colors.Transparent);
            this._stretchMode = CompositionStretch.Uniform;
            this.Loading += CompImage_Loading;
            this.Unloaded += CompImage_Unloaded;
            this.SizeChanged += CompImage_SizeChanged;

            _compositor = ElementCompositionPreview.GetElementVisual(this).Compositor;

            // Intialize the statics as needed
            if (!_staticsInitialized)
            {
                _defaultPlaceholderBrush = _compositor.CreateColorBrush(Colors.DarkGray);

                TimeSpan duration = TimeSpan.FromMilliseconds(1000);
                _fadeOutAnimation = _compositor.CreateScalarKeyFrameAnimation();
                _fadeOutAnimation.InsertKeyFrame(0, 1);
                _fadeOutAnimation.InsertKeyFrame(1, 0);
                _fadeOutAnimation.Duration = duration;

                _scaleAnimation = _compositor.CreateVector2KeyFrameAnimation();
                _scaleAnimation.InsertKeyFrame(0, new Vector2(1.25f, 1.25f));
                _scaleAnimation.InsertKeyFrame(1, new Vector2(1, 1));
                _scaleAnimation.Duration = duration;

                _staticsInitialized = true;
            }

            // Initialize the surface loader if needed
            if (!SurfaceLoader.IsInitialized)
            {
                SurfaceLoader.Initialize(ElementCompositionPreview.GetElementVisual(this).Compositor);
            }

            _placeholderDelay = TimeSpan.FromMilliseconds(50);
            _surfaceBrush = _compositor.CreateSurfaceBrush(null);
        }
        public override void ReleaseResources()
        {
            if (_effectFactory != null)
            {
                _effectFactory.Dispose();
                _effectFactory = null;
            }

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

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

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

            if (_propertySet != null)
            {
                _propertySet.Dispose();
                _propertySet = null;
            }
        }
        public MainPage()
        {
            this.InitializeComponent();
            ContactsCVS.Source = _list;

            this.Loaded += (s, e) =>
            {
                _scrollViewer = ListView.GetScrollViewer();
                _scrollViewer.DirectManipulationStarted += OnDirectManipulationStarted;
                _scrollViewer.DirectManipulationCompleted += OnDirectManipulationCompleted;

                // Retrieve the ScrollViewer manipulation and the Compositor.
                _scrollerViewerManipulation = ElementCompositionPreview.GetScrollViewerManipulationPropertySet(_scrollViewer);
                _compositor = _scrollerViewerManipulation.Compositor;

                // At the moment there are three things happening when pulling down the list -
                // 1. The Refresh Icon fades in.
                // 2. The Refresh Icon rotates (400°).
                // 3. The Refresh Icon gets pulled down a bit (REFRESH_ICON_MAX_OFFSET_Y)
                // QUESTION 5
                // Can we also have Geometric Path animation so we can also draw the Refresh Icon along the way?
                //

                // Create a rotation expression animation based on the overpan distance of the ScrollViewer.
                _rotationAnimation = _compositor.CreateExpressionAnimation("min(max(0, ScrollManipulation.Translation.Y) * Multiplier, MaxDegree)");
                _rotationAnimation.SetScalarParameter("Multiplier", 10.0f);
                _rotationAnimation.SetScalarParameter("MaxDegree", 400.0f);
                _rotationAnimation.SetReferenceParameter("ScrollManipulation", _scrollerViewerManipulation);

                // Create an opacity expression animation based on the overpan distance of the ScrollViewer.
                _opacityAnimation = _compositor.CreateExpressionAnimation("min(max(0, ScrollManipulation.Translation.Y) / Divider, 1)");
                _opacityAnimation.SetScalarParameter("Divider", 30.0f);
                _opacityAnimation.SetReferenceParameter("ScrollManipulation", _scrollerViewerManipulation);

                // Create an offset expression animation based on the overpan distance of the ScrollViewer.
                _offsetAnimation = _compositor.CreateExpressionAnimation("(min(max(0, ScrollManipulation.Translation.Y) / Divider, 1)) * MaxOffsetY");
                _offsetAnimation.SetScalarParameter("Divider", 30.0f);
                _offsetAnimation.SetScalarParameter("MaxOffsetY", REFRESH_ICON_MAX_OFFSET_Y);
                _offsetAnimation.SetReferenceParameter("ScrollManipulation", _scrollerViewerManipulation);

                // Create a keyframe animation to reset properties like Offset.Y, Opacity, etc.
                _resetAnimation = _compositor.CreateScalarKeyFrameAnimation();
                _resetAnimation.InsertKeyFrame(1.0f, 0.0f);

                // Create a loading keyframe animation (in this case, a rotation animation). 
                _loadingAnimation = _compositor.CreateScalarKeyFrameAnimation();
                _loadingAnimation.InsertKeyFrame(1.0f, 360);
                _loadingAnimation.Duration = TimeSpan.FromMilliseconds(1200);
                _loadingAnimation.IterationBehavior = AnimationIterationBehavior.Forever;

                // Get the RefreshIcon's Visual.
                _refreshIconVisual = ElementCompositionPreview.GetElementVisual(RefreshIcon);
                // Set the center point for the rotation animation.
                _refreshIconVisual.CenterPoint = new Vector3(Convert.ToSingle(RefreshIcon.ActualWidth / 2), Convert.ToSingle(RefreshIcon.ActualHeight / 2), 0);

                // Get the ListView's inner Border's Visual.
                var border = (Border)VisualTreeHelper.GetChild(ListView, 0);
                _borderVisual = ElementCompositionPreview.GetElementVisual(border);

                PrepareExpressionAnimationsOnScroll();
            };

            this.Unloaded += (s, e) =>
            {
                _scrollViewer.DirectManipulationStarted -= OnDirectManipulationStarted;
                _scrollViewer.DirectManipulationCompleted -= OnDirectManipulationCompleted;
            };
        }
#pragma warning disable 1998
        public override async Task<CompositionDrawingSurface> LoadResources()
        {
            // Create the effect template
            var graphicsEffect = new ArithmeticCompositeEffect
            {
                Name = "Arithmetic",
                Source1 = new CompositionEffectSourceParameter("ImageSource"),
                Source1Amount = 1,
                Source2 = new CompositionEffectSourceParameter("EffectSource"),
                Source2Amount = 0,
                MultiplyAmount = 0
            };

            _effectFactory = _compositor.CreateEffectFactory(graphicsEffect, new[] { "Arithmetic.Source1Amount", "Arithmetic.Source2Amount" });


            // Create the animations
            _animationDecreasing = _compositor.CreateScalarKeyFrameAnimation();
            _animationDecreasing.InsertKeyFrame(1f, 0f);
            _animationDecreasing.Duration = TimeSpan.FromMilliseconds(1000);
            _animationDecreasing.IterationBehavior = AnimationIterationBehavior.Count;
            _animationDecreasing.IterationCount = 1;

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

            _loadEffectHandler = ApplyBlurEffect;

            return null;
        }
        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 SurfaceLoader.LoadFromUri(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;
        }
 public static ScalarKeyFrameAnimation SetDuration(this ScalarKeyFrameAnimation animation, TimeSpan duration)
 {
     animation.Duration = duration;
     return(animation);
 }
Пример #9
0
        public override async Task <CompositionDrawingSurface> LoadResources()
        {
            var graphicsEffect = new CompositeEffect
            {
                Sources =
                {
                    new ColorSourceEffect
                    {
                        Color = Windows.UI.Colors.Black
                    },
                    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);
        }
Пример #10
0
        /// <summary>
        /// Updates the CompositionSurfaceBrush's Stretch and Alignment options
        /// </summary>
        /// <param name="surfaceBrush">CompositionSurfaceBrush</param>
        /// <param name="stretch">Stretch mode</param>
        /// <param name="alignX">Horizontal Alignment</param>
        /// <param name="alignY">Vertical Alignment</param>
        /// <param name="alignXAnimation">The animation to use to update the horizontal alignment of the surface brush</param>
        /// <param name="alignYAnimation">The animation to use to update the vertical alignment of the surface brush</param>
        public static void UpdateSurfaceBrushOptions(this CompositionSurfaceBrush surfaceBrush, Stretch stretch,
                                                     AlignmentX alignX, AlignmentY alignY, ScalarKeyFrameAnimation alignXAnimation = null,
                                                     ScalarKeyFrameAnimation alignYAnimation = null)
        {
            // Stretch Mode
            switch (stretch)
            {
            case Stretch.None:
                surfaceBrush.Stretch = CompositionStretch.None;
                break;

            case Stretch.Fill:
                surfaceBrush.Stretch = CompositionStretch.Fill;
                break;

            case Stretch.Uniform:
                surfaceBrush.Stretch = CompositionStretch.Uniform;
                break;

            case Stretch.UniformToFill:
                surfaceBrush.Stretch = CompositionStretch.UniformToFill;
                break;
            }

            // Horizontal Alignment
            var finalAlignX = surfaceBrush.HorizontalAlignmentRatio;

            switch (alignX)
            {
            case AlignmentX.Left:
                finalAlignX = 0;
                break;

            case AlignmentX.Center:
                finalAlignX = 0.5f;
                break;

            case AlignmentX.Right:
                finalAlignX = 1;
                break;
            }

            // If animation is available, animate to the new value
            // otherwise set it explicitly
            if (alignXAnimation == null)
            {
                surfaceBrush.HorizontalAlignmentRatio = finalAlignX;
            }
            else
            {
                alignXAnimation.InsertKeyFrame(1f, finalAlignX);
                surfaceBrush.StartAnimation("HorizontalAlignmentRatio", alignXAnimation);
            }

            // Vertical Alignment
            var finalAlignY = surfaceBrush.VerticalAlignmentRatio;

            switch (alignY)
            {
            case AlignmentY.Top:
                finalAlignY = 0;
                break;

            case AlignmentY.Center:
                finalAlignY = 0.5f;
                break;

            case AlignmentY.Bottom:
                finalAlignY = 1;
                break;
            }

            // If animation is available, animate to the new value
            // otherwise set it explicitly
            if (alignYAnimation == null)
            {
                surfaceBrush.VerticalAlignmentRatio = finalAlignY;
            }
            else
            {
                alignYAnimation.InsertKeyFrame(1f, finalAlignY);
                surfaceBrush.StartAnimation("VerticalAlignmentRatio", alignYAnimation);
            }
        }
Пример #11
0
        void PrepareAnimation()
        {
            if (lowerThan14393)
            {
                _contentGrid.RenderTransformOrigin = new Point(0.5, 0.5);
                _contentGrid.RenderTransform       = new CompositeTransform();
                #region expand
                expand = new Storyboard();
                var duk = new DoubleAnimationUsingKeyFrames();
                Storyboard.SetTarget(duk, _contentGrid);
                Storyboard.SetTargetProperty(duk, "(UIElement.RenderTransform).(CompositeTransform.ScaleX)");
                duk.KeyFrames.Add(new EasingDoubleKeyFrame()
                {
                    KeyTime = KeyTime.FromTimeSpan(TimeSpan.FromSeconds(0)), Value = 0
                });
                duk.KeyFrames.Add(new EasingDoubleKeyFrame()
                {
                    KeyTime = KeyTime.FromTimeSpan(TimeSpan.FromSeconds(0.2)), Value = 1, EasingFunction = new CubicEase()
                    {
                        EasingMode = EasingMode.EaseOut
                    }
                });
                expand.Children.Add(duk);

                duk = new DoubleAnimationUsingKeyFrames();
                Storyboard.SetTarget(duk, _contentGrid);
                Storyboard.SetTargetProperty(duk, "(UIElement.RenderTransform).(CompositeTransform.ScaleY)");
                duk.KeyFrames.Add(new EasingDoubleKeyFrame()
                {
                    KeyTime = KeyTime.FromTimeSpan(TimeSpan.FromSeconds(0)), Value = 0
                });
                duk.KeyFrames.Add(new EasingDoubleKeyFrame()
                {
                    KeyTime = KeyTime.FromTimeSpan(TimeSpan.FromSeconds(0.2)), Value = 1, EasingFunction = new CubicEase()
                    {
                        EasingMode = EasingMode.EaseOut
                    }
                });
                expand.Children.Add(duk);

                duk = new DoubleAnimationUsingKeyFrames();
                Storyboard.SetTarget(duk, _contentGrid);
                Storyboard.SetTargetProperty(duk, "(UIElement.RenderTransform).(CompositeTransform.Rotation)");
                duk.KeyFrames.Add(new EasingDoubleKeyFrame()
                {
                    KeyTime = KeyTime.FromTimeSpan(TimeSpan.FromSeconds(0)), Value = -90
                });
                duk.KeyFrames.Add(new EasingDoubleKeyFrame()
                {
                    KeyTime = KeyTime.FromTimeSpan(TimeSpan.FromSeconds(0.2)), Value = 0, EasingFunction = new CubicEase()
                    {
                        EasingMode = EasingMode.EaseOut
                    }
                });
                expand.Children.Add(duk);
                #endregion

                #region collapse
                collapse = new Storyboard();
                duk      = new DoubleAnimationUsingKeyFrames();
                Storyboard.SetTarget(duk, _contentGrid);
                Storyboard.SetTargetProperty(duk, "(UIElement.RenderTransform).(CompositeTransform.ScaleX)");
                duk.KeyFrames.Add(new EasingDoubleKeyFrame()
                {
                    KeyTime = KeyTime.FromTimeSpan(TimeSpan.FromSeconds(0)), Value = 1
                });
                duk.KeyFrames.Add(new EasingDoubleKeyFrame()
                {
                    KeyTime = KeyTime.FromTimeSpan(TimeSpan.FromSeconds(0.2)), Value = 0, EasingFunction = new CubicEase()
                    {
                        EasingMode = EasingMode.EaseOut
                    }
                });
                collapse.Children.Add(duk);

                duk = new DoubleAnimationUsingKeyFrames();
                Storyboard.SetTarget(duk, _contentGrid);
                Storyboard.SetTargetProperty(duk, "(UIElement.RenderTransform).(CompositeTransform.ScaleY)");
                duk.KeyFrames.Add(new EasingDoubleKeyFrame()
                {
                    KeyTime = KeyTime.FromTimeSpan(TimeSpan.FromSeconds(0)), Value = 1
                });
                duk.KeyFrames.Add(new EasingDoubleKeyFrame()
                {
                    KeyTime = KeyTime.FromTimeSpan(TimeSpan.FromSeconds(0.2)), Value = 0, EasingFunction = new CubicEase()
                    {
                        EasingMode = EasingMode.EaseOut
                    }
                });
                collapse.Children.Add(duk);

                duk = new DoubleAnimationUsingKeyFrames();
                Storyboard.SetTarget(duk, _contentGrid);
                Storyboard.SetTargetProperty(duk, "(UIElement.RenderTransform).(CompositeTransform.Rotation)");
                duk.KeyFrames.Add(new EasingDoubleKeyFrame()
                {
                    KeyTime = KeyTime.FromTimeSpan(TimeSpan.FromSeconds(0)), Value = 0
                });
                duk.KeyFrames.Add(new EasingDoubleKeyFrame()
                {
                    KeyTime = KeyTime.FromTimeSpan(TimeSpan.FromSeconds(0.2)), Value = -90, EasingFunction = new CubicEase()
                    {
                        EasingMode = EasingMode.EaseOut
                    }
                });
                collapse.Children.Add(duk);

                #endregion

                #region Open
                open = new Storyboard();
                duk  = new DoubleAnimationUsingKeyFrames();
                Storyboard.SetTarget(duk, _contentGrid);
                Storyboard.SetTargetProperty(duk, "(UIElement.RenderTransform).(CompositeTransform.ScaleX)");
                duk.KeyFrames.Add(new EasingDoubleKeyFrame()
                {
                    KeyTime = KeyTime.FromTimeSpan(TimeSpan.FromSeconds(0)), Value = 0
                });
                duk.KeyFrames.Add(new EasingDoubleKeyFrame()
                {
                    KeyTime = KeyTime.FromTimeSpan(TimeSpan.FromSeconds(0.1)), Value = 1, EasingFunction = new CubicEase()
                    {
                        EasingMode = EasingMode.EaseOut
                    }
                });
                open.Children.Add(duk);

                duk = new DoubleAnimationUsingKeyFrames();
                Storyboard.SetTarget(duk, _contentGrid);
                Storyboard.SetTargetProperty(duk, "(UIElement.RenderTransform).(CompositeTransform.ScaleY)");
                duk.KeyFrames.Add(new EasingDoubleKeyFrame()
                {
                    KeyTime = KeyTime.FromTimeSpan(TimeSpan.FromSeconds(0)), Value = 0
                });
                duk.KeyFrames.Add(new EasingDoubleKeyFrame()
                {
                    KeyTime = KeyTime.FromTimeSpan(TimeSpan.FromSeconds(0.1)), Value = 1, EasingFunction = new CubicEase()
                    {
                        EasingMode = EasingMode.EaseOut
                    }
                });
                open.Children.Add(duk);
                #endregion

                #region Close
                close = new Storyboard();
                duk   = new DoubleAnimationUsingKeyFrames();
                Storyboard.SetTarget(duk, _contentGrid);
                Storyboard.SetTargetProperty(duk, "(UIElement.RenderTransform).(CompositeTransform.ScaleX)");
                duk.KeyFrames.Add(new EasingDoubleKeyFrame()
                {
                    KeyTime = KeyTime.FromTimeSpan(TimeSpan.FromSeconds(0)), Value = 1
                });
                duk.KeyFrames.Add(new EasingDoubleKeyFrame()
                {
                    KeyTime = KeyTime.FromTimeSpan(TimeSpan.FromSeconds(0.07)), Value = 0, EasingFunction = new CubicEase()
                    {
                        EasingMode = EasingMode.EaseOut
                    }
                });
                close.Children.Add(duk);

                duk = new DoubleAnimationUsingKeyFrames();
                Storyboard.SetTarget(duk, _contentGrid);
                Storyboard.SetTargetProperty(duk, "(UIElement.RenderTransform).(CompositeTransform.ScaleY)");
                duk.KeyFrames.Add(new EasingDoubleKeyFrame()
                {
                    KeyTime = KeyTime.FromTimeSpan(TimeSpan.FromSeconds(0)), Value = 1
                });
                duk.KeyFrames.Add(new EasingDoubleKeyFrame()
                {
                    KeyTime = KeyTime.FromTimeSpan(TimeSpan.FromSeconds(0.07)), Value = 0, EasingFunction = new CubicEase()
                    {
                        EasingMode = EasingMode.EaseOut
                    }
                });
                close.Children.Add(duk);
                #endregion
            }
            else
            {
                //_radialMenuVisual = ElementCompositionPreview.GetElementVisual(this);
                //_radialMenuVisual.Offset = Offset;
                _contentGridVisual = ElementCompositionPreview.GetElementVisual(_contentGrid);
                _compositor        = _contentGridVisual.Compositor;

                rotationAnimation = _compositor.CreateScalarKeyFrameAnimation();
                scaleAnimation    = _compositor.CreateVector3KeyFrameAnimation();

                var easing = _compositor.CreateLinearEasingFunction();

                _contentGrid.SizeChanged += (s, e) =>
                {
                    _contentGridVisual.CenterPoint = new Vector3((float)_contentGrid.ActualWidth / 2.0f, (float)_contentGrid.ActualHeight / 2.0f, 0);
                };

                scaleAnimation.InsertKeyFrame(0.0f, new Vector3()
                {
                    X = 0.0f, Y = 0.0f, Z = 0.0f
                });
                scaleAnimation.InsertKeyFrame(1.0f, new Vector3()
                {
                    X = 1.0f, Y = 1.0f, Z = 0.0f
                }, easing);

                rotationAnimation.InsertKeyFrame(0.0f, -90.0f);
                rotationAnimation.InsertKeyFrame(1.0f, 0.0f, easing);
            }
        }
Пример #12
0
 /// <summary>
 /// Creates an animation template for a "color slide" type effect on a rectangular colored visual.
 /// This is a sub-second animation on the Scale property of the visual.
 /// </summary>
 private void InitializeSlideAnimation()
 {
     _slideAnimation = _compositor.CreateScalarKeyFrameAnimation();
     _slideAnimation.InsertKeyFrame(1.0f, 0f);
     _slideAnimation.Duration = TimeSpan.FromMilliseconds(800); // keeping this under a sec to not be obtrusive
 }
 ScalarKeyFrameAnimation(ScalarKeyFrameAnimation other)
     : base(other)
 {
 }
Пример #14
0
        private void MeasureItemsPosition(int index, int oldindex = -1)
        {
            System.Diagnostics.Debug.WriteLine($"MeasureItemsPosition _selectedIndex is {index} _oldselected is {oldindex}");

            // Set the itemwidth
            // if the container width is larger than ItemWidtn, itemwidth = ItemWidth
            // else itemwidth = container
            double containerWidth = _canvas.ActualWidth;
            double itemWidth      = _itemUIElementList[0].ActualWidth;

            if (containerWidth < this.ItemWidth)
            {
                foreach (var item in _itemUIElementList)
                {
                    item.Width = containerWidth;
                }
            }
            else if (itemWidth < ItemWidth)
            {
                foreach (var item in _itemUIElementList)
                {
                    item.Width = ItemWidth;
                }
            }
            itemWidth = _itemUIElementList[0].Width;
            double LLeft, Cleft, Rleft;

            Cleft = (containerWidth - itemWidth) / 2;
            LLeft = -(itemWidth - Cleft);
            Rleft = containerWidth - Cleft;

            int index_0, index_1, index_2, index_3, index_4;

            index_0 = index - 2;
            if (index_0 < 0)
            {
                index_0 = index_0 + 5;
            }
            index_1 = index - 1;
            if (index_1 < 0)
            {
                index_1 = index_1 + 5;
            }
            index_2 = index;
            index_3 = index + 1;
            if (index_3 > 4)
            {
                index_3 = index_3 - 5;
            }
            index_4 = index + 2;
            if (index_4 > 4)
            {
                index_4 = index_4 - 5;
            }

            // for initialing only, or no need to enable animiations
            if (oldindex == -1)
            {
                _itemVisualList[index_0].Offset = new Vector3((float)(LLeft - itemWidth), 0, 0);
                _itemVisualList[index_1].Offset = new Vector3((float)LLeft, 0, 0);
                _itemVisualList[index_2].Offset = new Vector3((float)Cleft, 0, 0);
                _itemVisualList[index_3].Offset = new Vector3((float)(Rleft), 0, 0);
                _itemVisualList[index_4].Offset = new Vector3((float)(Rleft + itemWidth), 0, 0);
                return;
            }

            int diff = index - oldindex;

            // new selected item equals to current item
            if (diff == 0)
            {
                _indicatorAnimation = _compositor.CreateScalarKeyFrameAnimation();
                _indicatorAnimation.InsertKeyFrame(1.0f, 0.0f);
                _indicatorAnimation.Duration = TimeSpan.FromMilliseconds(300);
            }
            // new selected item is the right item of current item
            if (diff == 1 || diff < -1)
            {
                _indicatorAnimation = _compositor.CreateScalarKeyFrameAnimation();
                _indicatorAnimation.InsertKeyFrame(1.0f, (float)-itemWidth);
                _indicatorAnimation.Duration = TimeSpan.FromMilliseconds(300);
            }
            // new selected item is the left one of current item
            if (diff == -1 || diff > 1)
            {
                _indicatorAnimation = _compositor.CreateScalarKeyFrameAnimation();
                _indicatorAnimation.InsertKeyFrame(1.0f, (float)itemWidth);
                _indicatorAnimation.Duration = TimeSpan.FromMilliseconds(300);
            }

            // Start the indicator animiation
            var backScopedBatch = _compositor.CreateScopedBatch(CompositionBatchTypes.Animation);

            _indicatorVisual.StartAnimation("Offset.X", _indicatorAnimation);
            backScopedBatch.End();
            backScopedBatch.Completed += (ss, ee) =>
            {
                // reset the firt and last item's postion
                _itemVisualList[index_0].Offset = new Vector3((float)(LLeft - itemWidth), 0, 0);
                _itemVisualList[index_1].Offset = new Vector3((float)LLeft, 0, 0);
                _itemVisualList[index_2].Offset = new Vector3((float)Cleft, 0, 0);
                _itemVisualList[index_3].Offset = new Vector3((float)(Rleft), 0, 0);
                _itemVisualList[index_4].Offset = new Vector3((float)(Rleft + itemWidth), 0, 0);

                // Change item's imagesources
                SetItemsImageSource();
                // Set Selected Item's appearance
                SetSelectedAppearance();
                // Start wheel event capturing
                _canvas.PointerWheelChanged += Canvas_PointerWheelChanged;
            };

            // Set the ZIndex of the items
            //Canvas.SetZIndex(_itemUIElementList[index_0], 0);
            //Canvas.SetZIndex(_itemUIElementList[index_1], 1);
            //Canvas.SetZIndex(_itemUIElementList[index_2], 2);
            //Canvas.SetZIndex(_itemUIElementList[index_3], 1);
            //Canvas.SetZIndex(_itemUIElementList[index_4], 0);
        }
        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;
        }
Пример #16
0
        /// <summary>
        /// Initializes the Composition elements
        /// </summary>
        private void InitComposition()
        {
            // Compositor
            _compositor = ElementCompositionPreview.GetElementVisual(this).Compositor;
            // CompositionGenerator
            _generator = CompositionGeneratorFactory.GetCompositionGenerator(_compositor);
            
            // Fade Out Animation
            _fadeOutAnimation = _compositor.CreateScalarKeyFrameAnimation();
            _fadeOutAnimation.InsertKeyFrame(1f, 0);
            _fadeOutAnimation.Duration = TransitionDuration;
            // Fade In Animation
            _fadeInAnimation = _compositor.CreateScalarKeyFrameAnimation();
            _fadeInAnimation.InsertKeyFrame(1f, 1);
            _fadeInAnimation.Duration = TransitionDuration;
            // Color Animation
            _colorAnimation = _compositor.CreateColorKeyFrameAnimation();
            _colorAnimation.Duration = TransitionDuration;
            // Offset Animation
            _offsetAnimation = _compositor.CreateVector3KeyFrameAnimation();
            _offsetAnimation.Target = "Offset";
            _offsetAnimation.Duration = TransitionDuration;
            _offsetAnimation.InsertKeyFrame(1f, Vector3.Zero);
            // Alignment animations
            _alignXAnimation = _compositor.CreateScalarKeyFrameAnimation();
            _alignXAnimation.Duration = AlignmentTransitionDuration;
            _alignYAnimation = _compositor.CreateScalarKeyFrameAnimation();
            _alignYAnimation.Duration = AlignmentTransitionDuration;

            // ZoomIn Animation Group
            _scaleAnimation = _compositor.CreateVector3KeyFrameAnimation();
            _scaleAnimation.Target = "Scale";
            _scaleAnimation.InsertKeyFrame(1f, Vector3.One);
            _scaleAnimation.Duration = TransitionDuration;
            _zoomInAnimationGroup = _compositor.CreateAnimationGroup();
            _zoomInAnimationGroup.Add(_scaleAnimation);
            _zoomInAnimationGroup.Add(_offsetAnimation);

            // Visuals
            _rootContainer = _compositor.CreateContainerVisual();
            _frameLayer = _compositor.CreateLayerVisual();
            _frameBackgroundVisual = _compositor.CreateSpriteVisual();
            _frameContentVisual = _compositor.CreateSpriteVisual();
            _placeholderContentVisual = _compositor.CreateSpriteVisual();
            _placeholderBackgroundVisual = _compositor.CreateSpriteVisual();
            _nextVisualContent = _compositor.CreateSpriteVisual();

            _frameLayer.Children.InsertAtTop(_frameBackgroundVisual);
            _frameLayer.Children.InsertAtTop(_frameContentVisual);
            _frameLayer.Children.InsertAtTop(_placeholderBackgroundVisual);
            _frameLayer.Children.InsertAtTop(_placeholderContentVisual);
            _frameLayer.Children.InsertAtTop(_nextVisualContent);

            // Placeholder content
            _placeholderContentMask = _generator.CreateGeometrySurface(PlaceholderSize, GetPlaceHolderGeometry(),
                PlaceholderColor, PlaceholderBackground);
            _placeholderContentBrush = _compositor.CreateSurfaceBrush(_placeholderContentMask.Surface);
            _placeholderContentVisual.Brush = _placeholderContentBrush;
            // Placeholder background
            _placeholderBackgroundVisual.Brush = _compositor.CreateColorBrush(PlaceholderBackground);

            // By default placeholder visual will not be visible
            HidePlaceholder();

            // Shadow visual
            _shadowVisual = _compositor.CreateSpriteVisual();

            _rootContainer.Children.InsertAtBottom(_shadowVisual);
            _rootContainer.Children.InsertAtTop(_frameLayer);

            _frameBackgroundVisual.Brush = _compositor.CreateColorBrush(FrameBackground);

            // Create the effect to create the opacity mask
            var layerEffect = new CompositeEffect
            {
                // CanvasComposite.DestinationIn - Intersection of source and mask. 
                // Equation: O = MA * S
                // where O - Output pixel, MA - Mask Alpha, S - Source pixel.
                Mode = CanvasComposite.DestinationIn,
                Sources =
                        {
                            new CompositionEffectSourceParameter("source"),
                            new CompositionEffectSourceParameter("mask")
                        }
            };

            var layerEffectFactory = _compositor.CreateEffectFactory(layerEffect);
            _layerEffectBrush = layerEffectFactory.CreateBrush();

            // The mask for the imageFrame
            _frameLayerMask = _generator.CreateMaskSurface(new Size(0, 0), null);
            _layerEffectBrush.SetSourceParameter("mask", _compositor.CreateSurfaceBrush(_frameLayerMask.Surface));
            // Apply the mask effect to the frameLayer
            _frameLayer.Effect = _layerEffectBrush;

            ElementCompositionPreview.SetElementChildVisual(this, _rootContainer);
        }
        /// <summary>
        /// Handles the Arrange layout phase
        /// </summary>
        /// <param name="finalSize">Final Size of the control</param>
        /// <returns>Size</returns>
        protected override Size ArrangeOverride(Size finalSize)
        {
            if ((_compositor == null) || (_generator == null))
                return base.ArrangeOverride(finalSize);

            if (Double.IsInfinity(finalSize.Width) || Double.IsInfinity(finalSize.Height) ||
                Double.IsNaN(finalSize.Width) || Double.IsNaN(finalSize.Height))
                return base.ArrangeOverride(finalSize);

            // Stop the animations and dispose the previous nodes
            // and their animations
            if (_isAnimationStarted)
            {
                for (var i = 0; i < _nodes.Count; i++)
                {
                    _nodes[i].StopAnimation(AnimatedProperty);
                    _animations[i].Dispose();
                    _animations[i] = null;
                    _nodes[i].Dispose();
                    _nodes[i] = null;
                }

                _container.StopAnimation(AnimatedProperty);
                _containerAnimation.Dispose();
                _containerAnimation = null;
                _container.Dispose();
                _container = null;

                _animations.Clear();
                _nodes.Clear();

                _isAnimationStarted = false;
            }

            // Validate MaxNodes and ActiveNodes
            if ((MaxNodes <= 0) || (ActiveNodes <= 0))
                return finalSize;

            // Coerce ActiveNodes to MaxNodes if ActiveNodes > MaxNodes
            if (ActiveNodes > MaxNodes)
                ActiveNodes = MaxNodes;

            // Take the smallest of the width or height
            var sideLength = (float)Math.Min(finalSize.Width, finalSize.Height);
            // Size of the progress ring displayed
            _ringSize = new Vector2(sideLength, sideLength);
            var sideHalf = sideLength / 2f;
            // Radius of each node
            _nodeRadius = (float)NodeSizeFactor * sideHalf;
            // Size of each node
            _nodeSize = new Vector2(_nodeRadius * 2f, _nodeRadius * 2f);
            // Radius of the node
            _ringRadius = sideHalf - _nodeRadius;

            // Each animation will consist of '_maxFrameBlocks' number of
            // FrameBlocks. Each FrameBlock will consist of keyframes which allow
            // the element being animated to move to the next slot and wait
            // at that slot until all other elements have moved to their next slot.
            // Each FrameBlock (except the last one) will have '_maxFramesPerBlock'
            // number of keyframes. The last keyframe in the last FrameBlock
            // will always be (1f, "this.StartingValue + 360")

            // Total number of FrameBlocks in each animation
            _maxFrameBlocks = ActiveNodes;
            // Total keyframes in each FrameBlock
            _maxFramesPerBlock = ActiveNodes + 1;
            // Total keyframes in each animation
            _maxKeyFrames = _maxFrameBlocks * _maxFramesPerBlock;
            // Normalized Progress Key unit value for each keyframe
            _keyFrameSlice = 1f / _maxKeyFrames;

            // ========================================================================
            // NOTE:
            // gamma * maxNodes = 360
            // gamma = alpha + beta
            // beta = 2 * Asin(nodeRadius / ringRadius) * (180 / Math.PI)
            // invisibleNodes = MaxNodes - ActiveNodes
            // phi = (invisibleNodes * gamma)
            // theta = phi - beta
            // ========================================================================

            // gamma is the angle between adjacent nodes when maxNodes number of nodes are arranged in a circle
            _gamma = 360f / MaxNodes;
            // beta is the angle a node must travel after hitting the adjacent node
            _beta = 2f * (float)(Math.Asin(_nodeRadius / _ringRadius) * (180f / Math.PI));
            // alpha is the smallest angle a node must travel before hitting the adjacent node
            _alpha = _gamma - _beta;
            // phi is the angle occupied by (MaxNodes - ActiveNodes) number of nodes
            _phi = (MaxNodes - ActiveNodes + 1) * _gamma;
            // theta is the largest angle a node must travel before hitting the adjacent node
            _theta = _phi - _beta;

            // Create the Animations
            _animations = CreateAnimations();

            // Create the Container
            _container = _compositor.CreateContainerVisual();
            _container.Size = _ringSize;
            _container.Offset = new Vector3(((float)finalSize.Width - sideLength) / 2f,
                                            ((float)finalSize.Height - sideLength) / 2f,
                                            0f);
            _container.CenterPoint = new Vector3(_ringSize.X / 2f, _ringSize.Y / 2f, 0f);

            // Create the Nodes
            var offset = new Vector3(_nodeRadius, _ringSize.Y / 2f, 0);
            var centerPoint = new Vector3(_ringSize.X / 2f - _nodeRadius, 0, 0);
            _nodes = new List<SpriteVisual>();
            var geometry = CanvasGeometry.CreateCircle(_generator.Device, new Vector2(_nodeRadius, _nodeRadius), _nodeRadius);
            // Create/Update the nodeMask
            var color = NodeColor;
            if (_nodeMask == null)
            {
                //Task.Run(async () =>
                //        {
                            _nodeMask = _generator.CreateGeometrySurface(_nodeSize.ToSize(), geometry, color);
                    //    })
                    //.Wait();
            }
            else
            {
                //Task.Run(async () =>
                //        {
                             _nodeMask.Redraw(_nodeSize.ToSize(), geometry, color);
                    //    })
                    //.Wait();
            }

            // Create the SurfaceBrush for the nodes
            var brush = _compositor.CreateSurfaceBrush(_nodeMask.Surface);

            var baseAngle = 0f;

            // Create the visuals for the nodes
            for (var i = 0; i < _maxFramesPerBlock; i++)
            {
                var node = _compositor.CreateSpriteVisual();
                node.Size = _nodeSize;
                node.AnchorPoint = new Vector2(0.5f);
                node.Offset = offset;
                node.CenterPoint = centerPoint;
                node.Brush = brush;
                node.RotationAngleInDegrees = baseAngle;
                if (i == 0)
                {
                    baseAngle += _phi;
                }
                else if (i == _maxFramesPerBlock - 2)
                {
                    baseAngle = -_beta;
                }
                else
                {
                    baseAngle += _gamma;
                }

                _nodes.Add(node);
                // Add the visual to the container
                _container.Children.InsertAtTop(node);
            }

            // Add the container to the Visual Tree
            ElementCompositionPreview.SetElementChildVisual(this, _container);

            // Start Node animations
            for (var i = 0; i < _maxFramesPerBlock; i++)
            {
                _nodes[i].StartAnimation(AnimatedProperty, _animations[i]);
            }

            // Start container animation
            _containerAnimation = _compositor.CreateScalarKeyFrameAnimation();
            _containerAnimation.InsertExpressionKeyFrame(1f, "this.StartingValue + 360f", _compositor.CreateLinearEasingFunction());
            _containerAnimation.Duration = RingDuration;
            _containerAnimation.IterationBehavior = AnimationIterationBehavior.Forever;

            _container.StartAnimation(AnimatedProperty, _containerAnimation);

            _isAnimationStarted = true;

            return finalSize;
        }
Пример #18
0
        /// <summary>
        /// Handles the Arrange layout phase
        /// </summary>
        /// <param name="finalSize">Final Size of the control</param>
        /// <returns>Size</returns>
        protected override Size ArrangeOverride(Size finalSize)
        {
            if ((_compositor == null) || (_generator == null))
            {
                return(base.ArrangeOverride(finalSize));
            }

            if (Double.IsInfinity(finalSize.Width) || Double.IsInfinity(finalSize.Height) ||
                Double.IsNaN(finalSize.Width) || Double.IsNaN(finalSize.Height))
            {
                return(base.ArrangeOverride(finalSize));
            }

            // Stop the animations and dispose the previous nodes
            // and their animations
            if (_isAnimationStarted)
            {
                for (var i = 0; i < _nodes.Count; i++)
                {
                    _nodes[i].StopAnimation(AnimatedProperty);
                    _animations[i].Dispose();
                    _animations[i] = null;
                    _nodes[i].Dispose();
                    _nodes[i] = null;
                }

                _container.StopAnimation(AnimatedProperty);
                _containerAnimation.Dispose();
                _containerAnimation = null;
                _container.Dispose();
                _container = null;

                _animations.Clear();
                _nodes.Clear();

                _isAnimationStarted = false;
            }

            // Validate MaxNodes and ActiveNodes
            if ((MaxNodes <= 0) || (ActiveNodes <= 0))
            {
                return(finalSize);
            }

            // Coerce ActiveNodes to MaxNodes if ActiveNodes > MaxNodes
            if (ActiveNodes > MaxNodes)
            {
                ActiveNodes = MaxNodes;
            }

            // Take the smallest of the width or height
            var sideLength = (float)Math.Min(finalSize.Width, finalSize.Height);

            // Size of the progress ring displayed
            _ringSize = new Vector2(sideLength, sideLength);
            var sideHalf = sideLength / 2f;

            // Radius of each node
            _nodeRadius = (float)NodeSizeFactor * sideHalf;
            // Size of each node
            _nodeSize = new Vector2(_nodeRadius * 2f, _nodeRadius * 2f);
            // Radius of the node
            _ringRadius = sideHalf - _nodeRadius;

            // Each animation will consist of '_maxFrameBlocks' number of
            // FrameBlocks. Each FrameBlock will consist of keyframes which allow
            // the element being animated to move to the next slot and wait
            // at that slot until all other elements have moved to their next slot.
            // Each FrameBlock (except the last one) will have '_maxFramesPerBlock'
            // number of keyframes. The last keyframe in the last FrameBlock
            // will always be (1f, "this.StartingValue + 360")

            // Total number of FrameBlocks in each animation
            _maxFrameBlocks = ActiveNodes;
            // Total keyframes in each FrameBlock
            _maxFramesPerBlock = ActiveNodes + 1;
            // Total keyframes in each animation
            _maxKeyFrames = _maxFrameBlocks * _maxFramesPerBlock;
            // Normalized Progress Key unit value for each keyframe
            _keyFrameSlice = 1f / _maxKeyFrames;

            // ========================================================================
            // NOTE:
            // gamma * maxNodes = 360
            // gamma = alpha + beta
            // beta = 2 * Asin(nodeRadius / ringRadius) * (180 / Math.PI)
            // invisibleNodes = MaxNodes - ActiveNodes
            // phi = (invisibleNodes * gamma)
            // theta = phi - beta
            // ========================================================================

            // gamma is the angle between adjacent nodes when maxNodes number of nodes are arranged in a circle
            _gamma = 360f / MaxNodes;
            // beta is the angle a node must travel after hitting the adjacent node
            _beta = 2f * (float)(Math.Asin(_nodeRadius / _ringRadius) * Scalar.RadiansToDegrees);
            // alpha is the smallest angle a node must travel before hitting the adjacent node
            _alpha = _gamma - _beta;
            // phi is the angle occupied by (MaxNodes - ActiveNodes) number of nodes
            _phi = (MaxNodes - ActiveNodes + 1) * _gamma;
            // theta is the largest angle a node must travel before hitting the adjacent node
            _theta = _phi - _beta;

            // Create the Animations
            _animations = CreateAnimations();

            // Create the Container
            _container        = _compositor.CreateContainerVisual();
            _container.Size   = _ringSize;
            _container.Offset = new Vector3(((float)finalSize.Width - sideLength) / 2f,
                                            ((float)finalSize.Height - sideLength) / 2f,
                                            0f);
            _container.CenterPoint = new Vector3(_ringSize.X / 2f, _ringSize.Y / 2f, 0f);

            // Create the Nodes
            var offset      = new Vector3(_nodeRadius, _ringSize.Y / 2f, 0);
            var centerPoint = new Vector3(_ringSize.X / 2f - _nodeRadius, 0, 0);

            _nodes = new List <SpriteVisual>();
            var geometry = CanvasGeometry.CreateCircle(_generator.Device, new Vector2(_nodeRadius, _nodeRadius), _nodeRadius);
            // Create/Update the nodeMask
            var color = NodeColor;

            if (_nodeMask == null)
            {
                //Task.Run(async () =>
                //        {
                _nodeMask = _generator.CreateGeometrySurface(_nodeSize.ToSize(), geometry, color);
                //    })
                //.Wait();
            }
            else
            {
                //Task.Run(async () =>
                //        {
                _nodeMask.Redraw(_nodeSize.ToSize(), geometry, color);
                //    })
                //.Wait();
            }

            // Create the SurfaceBrush for the nodes
            var brush = _compositor.CreateSurfaceBrush(_nodeMask.Surface);

            var baseAngle = 0f;

            // Create the visuals for the nodes
            for (var i = 0; i < _maxFramesPerBlock; i++)
            {
                var node = _compositor.CreateSpriteVisual();
                node.Size                   = _nodeSize;
                node.AnchorPoint            = new Vector2(0.5f);
                node.Offset                 = offset;
                node.CenterPoint            = centerPoint;
                node.Brush                  = brush;
                node.RotationAngleInDegrees = baseAngle;
                if (i == 0)
                {
                    baseAngle += _phi;
                }
                else if (i == _maxFramesPerBlock - 2)
                {
                    baseAngle = -_beta;
                }
                else
                {
                    baseAngle += _gamma;
                }

                _nodes.Add(node);
                // Add the visual to the container
                _container.Children.InsertAtTop(node);
            }

            // Add the container to the Visual Tree
            ElementCompositionPreview.SetElementChildVisual(this, _container);

            // Start Node animations
            for (var i = 0; i < _maxFramesPerBlock; i++)
            {
                _nodes[i].StartAnimation(AnimatedProperty, _animations[i]);
            }

            // Start container animation
            _containerAnimation = _compositor.CreateScalarKeyFrameAnimation();
            _containerAnimation.InsertExpressionKeyFrame(1f, "this.StartingValue + 360f", _compositor.CreateLinearEasingFunction());
            _containerAnimation.Duration          = RingDuration;
            _containerAnimation.IterationBehavior = AnimationIterationBehavior.Forever;

            _container.StartAnimation(AnimatedProperty, _containerAnimation);

            _isAnimationStarted = true;

            return(finalSize);
        }
Пример #19
0
        /// <summary>
        /// Disposes the resources
        /// </summary>
        public void Dispose()
        {
            // Clean up resources
            _compositor = null;
            Source = null;
            DataContext = null;
            Foreground = null;
            Background = null;
            _scheduledObject = null;
            _currentObject = null;

            // Clean up Composition Objects
            _imageSurface?.Dispose();
            _imageSurface = null;
            _nextImageSurface?.Dispose();
            _nextImageSurface = null;
            _frameLayerMask?.Dispose();
            _frameLayerMask = null;
            _placeholderContentMask?.Dispose();
            _placeholderContentMask = null;
            _placeholderContentBrush?.Dispose();
            _placeholderContentBrush = null;
            _nextSurfaceBrush?.Dispose();
            _nextSurfaceBrush = null;
            _rootContainer?.Dispose();
            _rootContainer = null;
            _shadowVisual?.Dispose();
            _shadowVisual = null;
            _frameLayer?.Dispose();
            _frameLayer = null;
            _frameBackgroundVisual?.Dispose();
            _frameBackgroundVisual = null;
            _placeholderBackgroundVisual?.Dispose();
            _placeholderBackgroundVisual = null;
            _placeholderContentVisual?.Dispose();
            _placeholderContentVisual = null;
            _frameContentVisual?.Dispose();
            _frameContentVisual = null;
            _nextVisualContent?.Dispose();
            _nextVisualContent = null;
            _shadow?.Dispose();
            _shadow = null;
            _layerEffectBrush?.Dispose();
            _layerEffectBrush = null;
            _imageOptions = null;
            _zoomInAnimationGroup?.Dispose();
            _zoomInAnimationGroup = null;
            _fadeOutAnimation?.Dispose();
            _fadeOutAnimation = null;
            _fadeInAnimation?.Dispose();
            _fadeInAnimation = null;
            _colorAnimation?.Dispose();
            _colorAnimation = null;
            _alignXAnimation?.Dispose();
            _alignXAnimation = null;
            _alignYAnimation?.Dispose();
            _alignYAnimation = null;
            _offsetAnimation?.Dispose();
            _offsetAnimation = null;
            _scaleAnimation?.Dispose();
            _scaleAnimation = null;

            // Dispose the generator at the end to allow the 
            // dependant composition objects to unsubscribe from
            // generator events
            _generator?.Dispose();
            _generator = null;
        }
Пример #20
0
        public static CompositionAnimation GetAnimation <TKeyFrame>(
            CompositionObject target,
            string property,
            TimeSpan?delay,
            TimeSpan duration,
            RepeatOption repeat,
            AnimationDelayBehavior delayBehavior,
            ArraySegment <TKeyFrame> keyFrames)
            where TKeyFrame : struct, IKeyFrameInfo
        {
            KeyFrameAnimation animation;

            if (typeof(T) == typeof(bool))
            {
                BooleanKeyFrameAnimation boolAnimation = target.Compositor.CreateBooleanKeyFrameAnimation();

                foreach (var keyFrame in keyFrames)
                {
                    if (keyFrame.TryInsertExpressionKeyFrame(boolAnimation, duration))
                    {
                        continue;
                    }

                    boolAnimation.InsertKeyFrame(keyFrame.GetNormalizedProgress(duration), keyFrame.GetValueAs <bool>());
                }

                animation = boolAnimation;
            }
            else if (typeof(T) == typeof(float))
            {
                ScalarKeyFrameAnimation scalarAnimation = target.Compositor.CreateScalarKeyFrameAnimation();

                foreach (var keyFrame in keyFrames)
                {
                    if (keyFrame.TryInsertExpressionKeyFrame(scalarAnimation, duration))
                    {
                        continue;
                    }

                    CompositionEasingFunction?easingFunction = target.Compositor.TryCreateEasingFunction(keyFrame.EasingType, keyFrame.EasingMode);

                    if (easingFunction is null)
                    {
                        scalarAnimation.InsertKeyFrame(keyFrame.GetNormalizedProgress(duration), keyFrame.GetValueAs <float>());
                    }
                    else
                    {
                        scalarAnimation.InsertKeyFrame(keyFrame.GetNormalizedProgress(duration), keyFrame.GetValueAs <float>(), easingFunction);
                    }
                }

                animation = scalarAnimation;
            }
            else if (typeof(T) == typeof(double))
            {
                ScalarKeyFrameAnimation scalarAnimation = target.Compositor.CreateScalarKeyFrameAnimation();

                foreach (var keyFrame in keyFrames)
                {
                    if (keyFrame.TryInsertExpressionKeyFrame(scalarAnimation, duration))
                    {
                        continue;
                    }

                    CompositionEasingFunction?easingFunction = target.Compositor.TryCreateEasingFunction(keyFrame.EasingType, keyFrame.EasingMode);

                    if (easingFunction is null)
                    {
                        scalarAnimation.InsertKeyFrame(keyFrame.GetNormalizedProgress(duration), (float)keyFrame.GetValueAs <double>());
                    }
                    else
                    {
                        scalarAnimation.InsertKeyFrame(keyFrame.GetNormalizedProgress(duration), (float)keyFrame.GetValueAs <double>(), easingFunction);
                    }
                }

                animation = scalarAnimation;
            }
            else if (typeof(T) == typeof(Vector2))
            {
                Vector2KeyFrameAnimation vector2Animation = target.Compositor.CreateVector2KeyFrameAnimation();

                foreach (var keyFrame in keyFrames)
                {
                    if (keyFrame.TryInsertExpressionKeyFrame(vector2Animation, duration))
                    {
                        continue;
                    }

                    CompositionEasingFunction?easingFunction = target.Compositor.TryCreateEasingFunction(keyFrame.EasingType, keyFrame.EasingMode);

                    if (easingFunction is null)
                    {
                        vector2Animation.InsertKeyFrame(keyFrame.GetNormalizedProgress(duration), keyFrame.GetValueAs <Vector2>());
                    }
                    else
                    {
                        vector2Animation.InsertKeyFrame(keyFrame.GetNormalizedProgress(duration), keyFrame.GetValueAs <Vector2>(), easingFunction);
                    }
                }

                animation = vector2Animation;
            }
            else if (typeof(T) == typeof(Vector3))
            {
                Vector3KeyFrameAnimation vector3Animation = target.Compositor.CreateVector3KeyFrameAnimation();

                foreach (var keyFrame in keyFrames)
                {
                    if (keyFrame.TryInsertExpressionKeyFrame(vector3Animation, duration))
                    {
                        continue;
                    }

                    CompositionEasingFunction?easingFunction = target.Compositor.TryCreateEasingFunction(keyFrame.EasingType, keyFrame.EasingMode);

                    if (easingFunction is null)
                    {
                        vector3Animation.InsertKeyFrame(keyFrame.GetNormalizedProgress(duration), keyFrame.GetValueAs <Vector3>());
                    }
                    else
                    {
                        vector3Animation.InsertKeyFrame(keyFrame.GetNormalizedProgress(duration), keyFrame.GetValueAs <Vector3>(), easingFunction);
                    }
                }

                animation = vector3Animation;
            }
            else if (typeof(T) == typeof(Vector4))
            {
                Vector4KeyFrameAnimation vector4Animation = target.Compositor.CreateVector4KeyFrameAnimation();

                foreach (var keyFrame in keyFrames)
                {
                    if (keyFrame.TryInsertExpressionKeyFrame(vector4Animation, duration))
                    {
                        continue;
                    }

                    CompositionEasingFunction?easingFunction = target.Compositor.TryCreateEasingFunction(keyFrame.EasingType, keyFrame.EasingMode);

                    if (easingFunction is null)
                    {
                        vector4Animation.InsertKeyFrame(keyFrame.GetNormalizedProgress(duration), keyFrame.GetValueAs <Vector4>());
                    }
                    else
                    {
                        vector4Animation.InsertKeyFrame(keyFrame.GetNormalizedProgress(duration), keyFrame.GetValueAs <Vector4>(), easingFunction);
                    }
                }

                animation = vector4Animation;
            }
            else if (typeof(T) == typeof(Color))
            {
                ColorKeyFrameAnimation colorAnimation = target.Compositor.CreateColorKeyFrameAnimation();

                foreach (var keyFrame in keyFrames)
                {
                    if (keyFrame.TryInsertExpressionKeyFrame(colorAnimation, duration))
                    {
                        continue;
                    }

                    CompositionEasingFunction?easingFunction = target.Compositor.TryCreateEasingFunction(keyFrame.EasingType, keyFrame.EasingMode);

                    if (easingFunction is null)
                    {
                        colorAnimation.InsertKeyFrame(keyFrame.GetNormalizedProgress(duration), keyFrame.GetValueAs <Color>());
                    }
                    else
                    {
                        colorAnimation.InsertKeyFrame(keyFrame.GetNormalizedProgress(duration), keyFrame.GetValueAs <Color>(), easingFunction);
                    }
                }

                animation = colorAnimation;
            }
            else if (typeof(T) == typeof(Quaternion))
            {
                QuaternionKeyFrameAnimation quaternionAnimation = target.Compositor.CreateQuaternionKeyFrameAnimation();

                foreach (var keyFrame in keyFrames)
                {
                    if (keyFrame.TryInsertExpressionKeyFrame(quaternionAnimation, duration))
                    {
                        continue;
                    }

                    CompositionEasingFunction?easingFunction = target.Compositor.TryCreateEasingFunction(keyFrame.EasingType, keyFrame.EasingMode);

                    if (easingFunction is null)
                    {
                        quaternionAnimation.InsertKeyFrame(keyFrame.GetNormalizedProgress(duration), keyFrame.GetValueAs <Quaternion>());
                    }
                    else
                    {
                        quaternionAnimation.InsertKeyFrame(keyFrame.GetNormalizedProgress(duration), keyFrame.GetValueAs <Quaternion>(), easingFunction);
                    }
                }

                animation = quaternionAnimation;
            }
            else
            {
                throw new InvalidOperationException("Invalid animation type");
            }

            animation.Duration = duration;

            if (delay.HasValue)
            {
                animation.DelayBehavior = delayBehavior;
                animation.DelayTime     = delay !.Value;
            }

            animation.Target = property;
            (animation.IterationBehavior, animation.IterationCount) = repeat.ToBehaviorAndCount();

            return(animation);
        }
Пример #21
0
 private void CreateAnimation(Compositor compositor)
 {
     blurIncreaseAnimation = Animation.CreateBlurIncreaseAnimation(compositor);
     blurDecreaseAnimation = Animation.CreateBlurDecreaseAnimation(compositor);
 }
        private async void ThumbnailList_ItemClick(object sender, ItemClickEventArgs e)
        {
            Thumbnail    thumbnail = (Thumbnail)e.ClickedItem;
            ListView     listView  = (ListView)sender;
            ListViewItem listItem  = (ListViewItem)listView.ContainerFromItem(e.ClickedItem);


            //
            // Calculate the absolute offset to the item that was clicked.  We will use that for centering
            // the zoom in.
            //

            GeneralTransform coordinate = listItem.TransformToVisual(RootPanel);
            Vector2          clickedItemCenterPosition = coordinate.TransformPoint(new Point(0, 0)).ToVector2() +
                                                         new Vector2((float)listItem.ActualWidth / 2, (float)listItem.ActualHeight / 2);


            //
            // Calculate the offset we want to animate up/down/in for the zoom based on the center point of the target and the
            // size of the panel/viewport.
            //
            Vector2 targetOffset = new Vector2((float)RootPanel.ActualWidth / 2, (float)RootPanel.ActualHeight / 2) - clickedItemCenterPosition;


            //
            // Get the root panel and set it up for the rotation animation.  We're rotating the listview around the Y-axis relative
            // to the center point of the panel.
            //

            Visual root = ElementCompositionPreview.GetElementVisual(ThumbnailList);

            root.Size         = new Vector2((float)ThumbnailList.ActualWidth, (float)ThumbnailList.ActualHeight);
            root.CenterPoint  = new Vector3(root.Size.X / 2, root.Size.Y / 2, 0);
            root.RotationAxis = new Vector3(0, 1, 0);

            // Kick off the rotation animation
            ScalarKeyFrameAnimation rotationAnimation = _compositor.CreateScalarKeyFrameAnimation();

            rotationAnimation.InsertKeyFrame(0, 0);
            rotationAnimation.InsertKeyFrame(1, targetOffset.X > 0 ? -45f : 45f);
            rotationAnimation.Duration = TimeSpan.FromMilliseconds(1000);
            root.StartAnimation("RotationAngleInDegrees", rotationAnimation);

            // Calcuate the offset for the point we are zooming towards
            const float zoomFactor   = .8f;
            Vector3     zoomedOffset = new Vector3(targetOffset.X * zoomFactor, // Adjust the x offset since the rotation will shorten the distance
                                                   targetOffset.Y,
                                                   (float)PerspectivePanel.ActualWidth * zoomFactor);

            Vector3KeyFrameAnimation offsetAnimaton = _compositor.CreateVector3KeyFrameAnimation();

            offsetAnimaton.InsertKeyFrame(0, new Vector3(0, 0, 0));
            offsetAnimaton.InsertKeyFrame(1, zoomedOffset);
            offsetAnimaton.Duration = TimeSpan.FromMilliseconds(1000);
            root.StartAnimation("Offset", offsetAnimaton);

            // Create the dialog
            var messageDialog = new MessageDialog(thumbnail.Name);

            messageDialog.Commands.Add(new UICommand("Close", new UICommandInvokedHandler(DialogDismissedHandler)));

            // Show the message dialog
            await messageDialog.ShowAsync();
        }
 public static ScalarKeyFrameAnimation AddKeyFrame(this ScalarKeyFrameAnimation animation, float normalizedProgressKey, float value, CompositionEasingFunction ease = null)
 {
     animation.InsertKeyFrame(normalizedProgressKey, value, ease);
     return(animation);
 }
Пример #24
0
        void InitConpositionResources()
        {
            easing  = compositor.CreateCubicBezierEasingFunction(new Vector2(0.215f, 0.61f), new Vector2(0.355f, 1f));
            steping = compositor.CreateStepEasingFunction(2);

            ProgressAnimation = compositor.CreateScalarKeyFrameAnimation();
            ProgressAnimation.InsertExpressionKeyFrame(0f, "This.StartingValue", easing);
            ProgressAnimation.InsertExpressionKeyFrame(1f, "propSet.newvalue", easing);
            ProgressAnimation.SetReferenceParameter("propSet", propSet);
            ProgressAnimation.Duration = TimeSpan.FromSeconds(0.3d);
            ProgressAnimation.Target   = "progress";

            //ImplicitAnimations = compositor.CreateImplicitAnimationCollection();
            //ImplicitAnimations["progress"] = ProgressAnimation;

            //propSet.ImplicitAnimations = ImplicitAnimations;

            TopBorderVisual     = ElementCompositionPreview.GetElementVisual(TopBorder);
            BottomBorderVisual  = ElementCompositionPreview.GetElementVisual(BottomBorder);
            CenterBorderVisual  = ElementCompositionPreview.GetElementVisual(CenterBorder);
            ContentBorderVisual = ElementCompositionPreview.GetElementVisual(ContentBorder);

            TopBorderVisual.CenterPoint     = new Vector3(38f, 36f, 0f);
            BottomBorderVisual.CenterPoint  = new Vector3(39f, 36f, 0f);
            CenterBorderVisual.CenterPoint  = new Vector3(36f, 36f, 0f);
            ContentBorderVisual.CenterPoint = new Vector3(36, 36, 0);

            TopRotationAnimation = compositor.CreateExpressionAnimation("0.25 * Pi * propSet.progress");
            TopRotationAnimation.SetReferenceParameter("propSet", propSet);

            BottomRotationAnimation = compositor.CreateExpressionAnimation("-0.25 * Pi * propSet.progress");
            BottomRotationAnimation.SetReferenceParameter("propSet", propSet);

            IconRotationAnimation = compositor.CreateExpressionAnimation("propSet.isopened == 1 ? -Pi * propSet.progress : Pi * propSet.progress");
            IconRotationAnimation.SetReferenceParameter("propSet", propSet);

            ExternalScaleXAnimation = compositor.CreateExpressionAnimation(" 1 - 0.4 * propSet.progress");
            ExternalScaleXAnimation.SetReferenceParameter("propSet", propSet);

            InternalScaleXAnimation = compositor.CreateExpressionAnimation(" 1 - 0.04 * propSet.progress");
            InternalScaleXAnimation.SetReferenceParameter("propSet", propSet);

            IsOpenedAnimation = compositor.CreateScalarKeyFrameAnimation();
            IsOpenedAnimation.InsertExpressionKeyFrame(0f, "This.StartingValue", steping);
            IsOpenedAnimation.InsertKeyFrame(1f, 1f, steping);
            IsOpenedAnimation.Duration  = TimeSpan.FromSeconds(0.001d);
            IsOpenedAnimation.DelayTime = TimeSpan.FromSeconds(0.3d);

            IsNotOpenedAnimation = compositor.CreateScalarKeyFrameAnimation();
            IsNotOpenedAnimation.InsertExpressionKeyFrame(0f, "This.StartingValue", steping);
            IsNotOpenedAnimation.InsertKeyFrame(1f, 0f, steping);
            IsNotOpenedAnimation.Duration  = TimeSpan.FromSeconds(0.001d);
            IsNotOpenedAnimation.DelayTime = TimeSpan.FromSeconds(0.3d);

            TopBorderVisual.StartAnimation("RotationAngle", TopRotationAnimation);
            BottomBorderVisual.StartAnimation("RotationAngle", BottomRotationAnimation);
            ContentBorderVisual.StartAnimation("RotationAngle", IconRotationAnimation);

            TopBorderVisual.StartAnimation("Scale.X", ExternalScaleXAnimation);
            BottomBorderVisual.StartAnimation("Scale.X", ExternalScaleXAnimation);
            CenterBorderVisual.StartAnimation("Scale.X", InternalScaleXAnimation);
        }
        public override void ReleaseResources()
        {
            if (_effectFactory != null)
            {
                _effectFactory.Dispose();
                _effectFactory = null;
            }

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

            if (_exitAnimation != null)
            {
                _exitAnimation.Dispose();
                _exitAnimation = null;
            }
        }
        private void UpdateEffect()
        {
            ComboBoxItem item = EffectSelection.SelectedValue as ComboBoxItem;

            switch ((EffectTypes)item.Tag)
            {
            case EffectTypes.ColorSwap:
            {
                Matrix5x4 mat = new Matrix5x4()
                {
                    M11 = 0, M12 = 0f, M13 = 1f, M14 = 0,
                    M21 = 0f, M22 = 1f, M23 = 0f, M24 = 0,
                    M31 = 1f, M32 = 0f, M33 = 0f, M34 = 0,
                    M41 = 0f, M42 = 0f, M43 = 0f, M44 = 1,
                    M51 = 0, M52 = 0, M53 = 0, M54 = 0
                };

                IGraphicsEffect graphicsEffect = new ColorMatrixEffect()
                {
                    ColorMatrix = mat,
                    Source      = new CompositionEffectSourceParameter("ImageSource")
                };

                // Create the effect factory and instantiate a brush
                CompositionEffectFactory _effectFactory = _compositor.CreateEffectFactory(graphicsEffect, null);
                CompositionEffectBrush   brush          = _effectFactory.CreateBrush();

                // Set the destination brush as the source of the image content
                brush.SetSourceParameter("ImageSource", _compositor.CreateHostBackdropBrush());

                _hostSprite.Brush = brush;
            }
            break;

            case EffectTypes.ColorMask:
            {
                Matrix5x4 mat = new Matrix5x4()
                {
                    M11 = 0.8f, M12 = 0f, M13 = 0f, M14 = 1.0f / 3,
                    M21 = 0f, M22 = 0.8f, M23 = 0f, M24 = 1.0f / 3,
                    M31 = 0f, M32 = 0f, M33 = 0.8f, M34 = 1.0f / 3,
                    M41 = 0f, M42 = 0f, M43 = 0f, M44 = 0,
                    M51 = 0, M52 = 0, M53 = 0, M54 = 0
                };

                IGraphicsEffect graphicsEffect = new ColorMatrixEffect()
                {
                    ColorMatrix = mat,
                    Source      = new CompositionEffectSourceParameter("ImageSource")
                };


                // Create the effect factory and instantiate a brush
                CompositionEffectFactory _effectFactory = _compositor.CreateEffectFactory(graphicsEffect, null);
                CompositionEffectBrush   brush          = _effectFactory.CreateBrush();

                // Set the destination brush as the source of the image content
                brush.SetSourceParameter("ImageSource", _compositor.CreateHostBackdropBrush());

                _hostSprite.Brush = brush;
            }
            break;

            case EffectTypes.RedFilter:
            {
                Matrix5x4 mat = new Matrix5x4()
                {
                    M11 = 1, M12 = 0f, M13 = 0f, M14 = 0,
                    M21 = 0f, M22 = 0f, M23 = 0f, M24 = 0,
                    M31 = 0f, M32 = 0f, M33 = 0f, M34 = 0,
                    M41 = 0f, M42 = 0f, M43 = 0f, M44 = 1,
                    M51 = 0, M52 = 0, M53 = 0, M54 = 0
                };

                IGraphicsEffect graphicsEffect = new ColorMatrixEffect()
                {
                    ColorMatrix = mat,
                    Source      = new CompositionEffectSourceParameter("ImageSource")
                };

                // Create the effect factory and instantiate a brush
                CompositionEffectFactory _effectFactory = _compositor.CreateEffectFactory(graphicsEffect, null);
                CompositionEffectBrush   brush          = _effectFactory.CreateBrush();

                // Set the destination brush as the source of the image content
                brush.SetSourceParameter("ImageSource", _compositor.CreateHostBackdropBrush());

                _hostSprite.Brush = brush;
            }
            break;

            case EffectTypes.ColorHighlight:
            {
                IGraphicsEffect graphicsEffect = new ArithmeticCompositeEffect()
                {
                    MultiplyAmount = 0,
                    Source1Amount  = 1,
                    Source2Amount  = 1,
                    Source1        = new GammaTransferEffect()
                    {
                        RedExponent    = 7,
                        BlueExponent   = 7,
                        GreenExponent  = 7,
                        RedAmplitude   = 3,
                        GreenAmplitude = 3,
                        BlueAmplitude  = 3,
                        Source         = new CompositionEffectSourceParameter("ImageSource")
                    },
                    Source2 = new SaturationEffect()
                    {
                        Saturation = 0,
                        Source     = new CompositionEffectSourceParameter("ImageSource")
                    }
                };

                // Create the effect factory and instantiate a brush
                CompositionEffectFactory _effectFactory = _compositor.CreateEffectFactory(graphicsEffect, null);
                CompositionEffectBrush   brush          = _effectFactory.CreateBrush();

                // Set the destination brush as the source of the image content
                brush.SetSourceParameter("ImageSource", _compositor.CreateHostBackdropBrush());

                _hostSprite.Brush = brush;
            }
            break;

            case EffectTypes.Bloom:
            {
                var bloomEffectDesc = new ArithmeticCompositeEffect
                {
                    Name           = "Bloom",
                    Source1Amount  = 1,
                    Source2Amount  = 2,
                    MultiplyAmount = 0,

                    Source1 = new CompositionEffectSourceParameter("source"),
                    Source2 = new GaussianBlurEffect
                    {
                        Name       = "Blur",
                        BorderMode = EffectBorderMode.Hard,
                        BlurAmount = 40,

                        Source = new BlendEffect
                        {
                            Mode = BlendEffectMode.Multiply,

                            Background = new CompositionEffectSourceParameter("source2"),
                            Foreground = new CompositionEffectSourceParameter("source2"),
                        },
                    },
                };

                var bloomEffectFactory = _compositor.CreateEffectFactory(bloomEffectDesc,
                                                                         new[] { "Bloom.Source2Amount", "Blur.BlurAmount" });
                var brush = bloomEffectFactory.CreateBrush();

                var backdropBrush = _compositor.CreateHostBackdropBrush();
                brush.SetSourceParameter("source", backdropBrush);
                brush.SetSourceParameter("source2", backdropBrush);

                // Setup some animations for the bloom effect
                ScalarKeyFrameAnimation blurAnimation = _compositor.CreateScalarKeyFrameAnimation();
                blurAnimation.InsertKeyFrame(0, 0);
                blurAnimation.InsertKeyFrame(.5f, 2);
                blurAnimation.InsertKeyFrame(1, 0);
                blurAnimation.Duration          = TimeSpan.FromMilliseconds(5000);
                blurAnimation.IterationBehavior = AnimationIterationBehavior.Forever;

                ScalarKeyFrameAnimation bloomAnimation = _compositor.CreateScalarKeyFrameAnimation();
                bloomAnimation.InsertKeyFrame(0, 0);
                bloomAnimation.InsertKeyFrame(.5f, 40);
                bloomAnimation.InsertKeyFrame(1, 0);
                bloomAnimation.Duration          = TimeSpan.FromMilliseconds(5000);
                bloomAnimation.IterationBehavior = AnimationIterationBehavior.Forever;

                brush.StartAnimation("Bloom.Source2Amount", blurAnimation);
                brush.StartAnimation("Blur.BlurAmount", bloomAnimation);

                _hostSprite.Brush = brush;
            }
            break;

            case EffectTypes.None:
            default:
                _hostSprite.Brush = _compositor.CreateHostBackdropBrush();
                break;
            }
        }
        public override void ReleaseResources()
        {
            if (_effectFactory != null)
            {
                _effectFactory.Dispose();
                _effectFactory = null;
            }

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

            if (_animationDecreasing != null)
            {
                _animationDecreasing.Dispose();
                _animationDecreasing = null;
            }
        }
        private async void ThumbnailList_ItemClick(object sender, ItemClickEventArgs e)
        {
            Thumbnail thumbnail = (Thumbnail)e.ClickedItem;

            // If we're in the middle of an animation, cancel it now
            if (_scopeBatch != null)
            {
                CleanupScopeBatch();
            }

            // We're starting our transition, show the destination sprite
            _destinationSprite.IsVisible = true;

            // Animate from transparent to fully opaque
            ScalarKeyFrameAnimation showAnimation = _compositor.CreateScalarKeyFrameAnimation();

            showAnimation.InsertKeyFrame(0f, 0f);
            showAnimation.InsertKeyFrame(1f, 1f);
            showAnimation.Duration = TimeSpan.FromMilliseconds(1500);
            _destinationSprite.StartAnimation("Opacity", showAnimation);

            // 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(0f, new Vector2(1.25f, 1.25f));
                scaleAnimation.InsertKeyFrame(1f, new Vector2(0f, 0f));
                scaleAnimation.Duration = TimeSpan.FromMilliseconds(2000);
                brush.StartAnimation("Scale", scaleAnimation);
                break;
            }

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

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

            case EffectTypes.RainbowBlur:
            {
                CompositionEffectBrush brush          = (CompositionEffectBrush)_destinationSprite.Brush;
                ColorKeyFrameAnimation colorAnimation = _compositor.CreateColorKeyFrameAnimation();
                colorAnimation.InsertKeyFrame(0, Colors.Red);
                colorAnimation.InsertKeyFrame(.16f, Colors.Orange);
                colorAnimation.InsertKeyFrame(.32f, Colors.Yellow);
                colorAnimation.InsertKeyFrame(.48f, Colors.Green);
                colorAnimation.InsertKeyFrame(.64f, Colors.Blue);
                colorAnimation.InsertKeyFrame(.80f, Colors.Purple);
                colorAnimation.InsertKeyFrame(1, Colors.Red);
                colorAnimation.IterationBehavior = AnimationIterationBehavior.Forever;
                colorAnimation.Duration          = TimeSpan.FromMilliseconds(5000);
                brush.StartAnimation("Base.Color", colorAnimation);
                break;
            }

            default:
                break;
            }

            // Create the dialog
            var messageDialog = new MessageDialog(thumbnail.Name);

            messageDialog.Commands.Add(new UICommand("Close", new UICommandInvokedHandler(DialogDismissedHandler)));

            // Show the message dialog
            await messageDialog.ShowAsync();
        }
        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 SurfaceLoader.LoadFromUri(new Uri("ms-appx:///Samples/SDK 10586/PointerEnterEffects/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;

            _transformExpression = _compositor.CreateExpressionAnimation("Matrix3x2(props.Scale, 0, 0, props.Scale, props.CenterPointOffset.X * (1-props.Scale) + (props.Translate.X * props.CenterPointOffset.X * 2), props.CenterPointOffset.Y * (1-props.Scale) + (props.Translate.Y * props.CenterPointOffset.Y * 2))");

            return null;
        }
Пример #30
0
        private void MainPanel_Tapped(object sender, Windows.UI.Xaml.Input.TappedRoutedEventArgs e)

        {
            Visual visual = ElementCompositionPreview.GetElementVisual(CaptionTile);

            Compositor compositor = visual.Compositor;



            visual.Size = new Vector2((float)CaptionTile.Width / 2, (float)CaptionTile.Height / 2);



            // Rotate around the X-axis

            visual.RotationAxis = new Vector3(1, 0, 0);



            // Start the rotation animation

            LinearEasingFunction linear = compositor.CreateLinearEasingFunction();

            ScalarKeyFrameAnimation rotationAnimation = compositor.CreateScalarKeyFrameAnimation();

            if (!IsFlipped) // default

            {
                rotationAnimation.InsertKeyFrame(0, 0, linear);

                rotationAnimation.InsertKeyFrame(1, 250f, linear); // flip over
            }

            else

            {
                rotationAnimation.InsertKeyFrame(0, 250f, linear);

                rotationAnimation.InsertKeyFrame(1, 0f, linear);   // flip back
            }

            rotationAnimation.Duration = TimeSpan.FromMilliseconds(800);



            var transaction = compositor.CreateScopedBatch(CompositionBatchTypes.Animation);

            transaction.Completed += Animation_Completed;



            // we want the CaptionTile visible as it flips back

            if (IsFlipped)
            {
                CaptionTile.Visibility = Windows.UI.Xaml.Visibility.Visible;
            }



            visual.StartAnimation("RotationAngleInDegrees", rotationAnimation);
            transaction.End();
        }
#pragma warning disable 1998
        public override async Task<CompositionDrawingSurface> LoadResources()
        {
            // Create the effect template
            var graphicsEffect = new SaturationEffect
            {
                Name = _effectName,
                Saturation = 1.0f,
                Source = new CompositionEffectSourceParameter("ImageSource")
            };

            _effectFactory = _compositor.CreateEffectFactory(graphicsEffect, new[] { _targetProperty });


            // Create the animations
            _enterAnimation = _compositor.CreateScalarKeyFrameAnimation();
            _enterAnimation.InsertKeyFrame(1f, 0f);
            _enterAnimation.Duration = TimeSpan.FromMilliseconds(1000);
            _enterAnimation.IterationBehavior = AnimationIterationBehavior.Count;
            _enterAnimation.IterationCount = 1;

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

            return null;
        }
Пример #32
0
 private void StartResetAnimations()
 {
     var batch = _Compositor.CreateScopedBatch(CompositionBatchTypes.Animation);
     batch.Completed += (s, e) =>
     {
         _ContentAnimation.SetScalarParameter("offset", 0);
         _LeftContentAnimation.SetScalarParameter("o", 0);
         _RightContentAnimation.SetScalarParameter("o", 0);
         _OffsetX = 0;
     };
     _ResetContentAnimation = _Compositor.CreateScalarKeyFrameAnimation();
     _ResetContentAnimation.Duration = TimeSpan.FromSeconds(0.25);
     _ResetContentAnimation.InsertKeyFrame(1.0f, 0.0f);
     _ContentVisual.StartAnimation("Offset.X", _ResetContentAnimation);
     switch (this.RightAnimationType)
     {
         case SwipeAnimationType.SlideFromInside:
             _ResetRightContentAnimation = _Compositor.CreateScalarKeyFrameAnimation();
             _ResetRightContentAnimation.InsertKeyFrame(1.0f, -75f);
             _ResetRightTextAnimation = _Compositor.CreateScalarKeyFrameAnimation();
             _ResetRightTextAnimation.InsertKeyFrame(1.0f, -100f);
             _RightTextVisual.StartAnimation("Offset.X", _ResetRightTextAnimation);
             _RightContentVisual.StartAnimation("Offset.X", _ResetRightContentAnimation);
             break;
         case SwipeAnimationType.RotateFromInside:
             _ResetRightContentAnimation = _Compositor.CreateScalarKeyFrameAnimation();
             _ResetRightContentAnimation.InsertKeyFrame(1.0f, (float)_BeginRotationAngle2);
             _ResetRightTextAnimation = _Compositor.CreateScalarKeyFrameAnimation();
             _ResetRightTextAnimation.InsertKeyFrame(1.0f, (float)_BeginRotationAngle);
             _RightTextVisual.StartAnimation("RotationAngle", _ResetRightTextAnimation);
             _RightContentVisual.StartAnimation("RotationAngle", _ResetRightContentAnimation);
             break;
         default:
             break;
     }
     switch (this.LeftAnimationType)
     {
         case SwipeAnimationType.SlideFromInside:
             _ResetLeftContentAnimation = _Compositor.CreateScalarKeyFrameAnimation();
             _ResetLeftContentAnimation.InsertKeyFrame(1.0f, 75f);
             _ResetLeftTextAnimation = _Compositor.CreateScalarKeyFrameAnimation();
             _ResetLeftTextAnimation.InsertKeyFrame(1.0f, 100f);
             _LeftTextVisual.StartAnimation("Offset.X", _ResetLeftTextAnimation);
             _LeftContentVisual.StartAnimation("Offset.X", _ResetLeftContentAnimation);
             break;
         case SwipeAnimationType.RotateFromInside:
             _ResetLeftContentAnimation = _Compositor.CreateScalarKeyFrameAnimation();
             _ResetLeftContentAnimation.InsertKeyFrame(1.0f, (float)_BeginRotationAngle);
             _ResetLeftTextAnimation = _Compositor.CreateScalarKeyFrameAnimation();
             _ResetLeftTextAnimation.InsertKeyFrame(1.0f, (float)_BeginRotationAngle);
             _LeftTextVisual.StartAnimation("RotationAngle", _ResetLeftTextAnimation);
             _LeftContentVisual.StartAnimation("RotationAngle", _ResetLeftContentAnimation);
             break;
         default:
             break;
     }
     
     
     batch.End();
 }
Пример #33
0
        private void StartGearMotor(double secondsPerRotation)
        {
            // Start the first gear (the red one)
            if (_gearMotionScalarAnimation == null)
            {
                _gearMotionScalarAnimation = _compositor.CreateScalarKeyFrameAnimation();
                var linear = _compositor.CreateLinearEasingFunction();

                _gearMotionScalarAnimation.InsertExpressionKeyFrame(0.0f, "this.StartingValue");
                _gearMotionScalarAnimation.InsertExpressionKeyFrame(1.0f, "this.StartingValue + 360", linear);

                _gearMotionScalarAnimation.IterationBehavior = AnimationIterationBehavior.Forever;
            }

            _gearMotionScalarAnimation.Duration = TimeSpan.FromSeconds(secondsPerRotation);
            _gearVisuals.First().StartAnimation("RotationAngleInDegrees", _gearMotionScalarAnimation);
        }
        /// <summary>
        /// Creates an animation template for a "color bloom" type effect on a circular colored visual.
        /// This is a sub-second animation on the Scale property of the visual.
        /// 
        /// <param name="initialRadius">the Radius of the circular visual</param>
        /// <param name="finalBounds">the final area to occupy</param>
        /// </summary>
        private void InitializeBloomAnimation(float initialRadius, Rect finalBounds)
        {
            var maxWidth = finalBounds.Width;
            var maxHeight = finalBounds.Height;

            // when fully scaled, the circle must cover the entire viewport
            // so we use the window's diagonal width as our max radius, assuming 0,0 placement
            var maxRadius = (float)Math.Sqrt((maxWidth * maxWidth) + (maxHeight * maxHeight)); // hypotenuse

            // the scale factor is the ratio of the max radius to the original radius
            var scaleFactor = (float)Math.Round(maxRadius / initialRadius, MidpointRounding.AwayFromZero);


            var bloomEase = _compositor.CreateCubicBezierEasingFunction(  //these numbers seem to give a consistent circle even on small sized windows
                    new Vector2(0.1f, 0.4f),
                    new Vector2(0.99f, 0.65f)
                );
            _bloomAnimation = _compositor.CreateScalarKeyFrameAnimation();
            _bloomAnimation.InsertKeyFrame(1.0f, scaleFactor, bloomEase);
            _bloomAnimation.Duration = TimeSpan.FromMilliseconds(800); // keeping this under a sec to not be obtrusive

        }
Пример #35
0
        private void OnActivityListLoaded(object sender, RoutedEventArgs e)
        {
            _scrollViewer = ActivityList.GetVisualDescendents <ScrollViewer>().FirstOrDefault();
            if (_scrollViewer != null)
            {
                _scrollViewer.ViewChanged           += OnScrollViewerViewChanged;
                _scrollViewer.ViewChanging          += OnScrollViewerViewChanging;
                _scrollViewer.IsScrollInertiaEnabled = true;

                _scrollViewer.DirectManipulationStarted   += OnDirectManipStarted;
                _scrollViewer.DirectManipulationCompleted += OnDirectManipCompleted;

                #region PullToRefresh Animation Setup
                // Retrieve the ScrollViewer manipulation and the Compositor.
                _scrollerViewerManipulation = ElementCompositionPreview.GetScrollViewerManipulationPropertySet(_scrollViewer);
                //Compositor = _scrollerViewerManipulation.Compositor;

                // Create a rotation expression animation based on the overpan distance of the ScrollViewer.
                _rotationAnimation = Compositor.CreateExpressionAnimation();
                _rotationAnimation.SetScalarParameter("MyMultiplier", 10.0f);
                _rotationAnimation.SetScalarParameter("MyMaxDegree", 400.0f);
                _rotationAnimation.SetReferenceParameter("MyScrollManipulation", _scrollerViewerManipulation);
                _rotationAnimation.Expression = "min(max(0, MyScrollManipulation.Translation.Y) * MyMultiplier, MyMaxDegree)";

                // Create an opacity expression animation based on the overpan distance of the ScrollViewer.
                _opacityAnimation = Compositor.CreateExpressionAnimation();
                _opacityAnimation.SetScalarParameter("MyDivider", 30.0f);
                _opacityAnimation.SetReferenceParameter("MyScrollManipulation", _scrollerViewerManipulation);
                _opacityAnimation.Expression = "min(max(0, MyScrollManipulation.Translation.Y) / MyDivider, 1)";

                // Create an offset expression animation based on the overpan distance of the ScrollViewer.
                _offsetAnimation = Compositor.CreateExpressionAnimation();
                _offsetAnimation.SetScalarParameter("MyDivider", 30.0f);
                _offsetAnimation.SetScalarParameter("MyMaxOffsetY", REFRESH_ICON_MAX_OFFSET_Y);
                _offsetAnimation.SetReferenceParameter("MyScrollManipulation", _scrollerViewerManipulation);
                _offsetAnimation.Expression = "(min(max(0, MyScrollManipulation.Translation.Y) / MyDivider, 1)) * MyMaxOffsetY";

                // Create a keyframe animation to reset properties like Offset.Y, Opacity, etc.
                _resetAnimation = Compositor.CreateScalarKeyFrameAnimation();
                _resetAnimation.InsertKeyFrame(1.0f, 0.0f);

                // Create a loading keyframe animation (in this case, a rotation animation).
                _loadingAnimation = Compositor.CreateScalarKeyFrameAnimation();
                _loadingAnimation.InsertKeyFrame(1.0f, 360);
                _loadingAnimation.Duration          = TimeSpan.FromMilliseconds(800);
                _loadingAnimation.IterationBehavior = AnimationIterationBehavior.Forever;

                // Get the RefreshIcon's Visual.
                _refreshIconVisual = ElementCompositionPreview.GetElementVisual(RefreshIcon);
                // Set the center point for the rotation animation.
                _refreshIconVisual.CenterPoint = new Vector3(Convert.ToSingle(RefreshIcon.ActualWidth / 2), Convert.ToSingle(RefreshIcon.ActualHeight / 2), 0);

                // Get the ListView's inner Border's Visual.
                var border = (Border)VisualTreeHelper.GetChild(ActivityList, 0);
                _borderVisual = ElementCompositionPreview.GetElementVisual(border);

                _refreshIconVisual.StartAnimation(nameof(_refreshIconVisual.RotationAngleInDegrees), _rotationAnimation);
                _refreshIconVisual.StartAnimation(nameof(_refreshIconVisual.Opacity), _opacityAnimation);
                _refreshIconVisual.StartAnimation($"{nameof(_refreshIconVisual.Offset)}.{nameof(_refreshIconVisual.Offset.Y)}", _offsetAnimation);
                _borderVisual.StartAnimation($"{nameof(_borderVisual.Offset)}.{nameof(_borderVisual.Offset.Y)}", _offsetAnimation);
                #endregion
            }
        }
Пример #36
0
        public static ICompositionAnimationBase CreateAnimationGroup(CompositionAnimation listContentShowAnimations, ScalarKeyFrameAnimation listContentOpacityAnimations)
        {
            var group = Window.Current.Compositor.CreateAnimationGroup();

            group.Add(listContentShowAnimations);
            group.Add(listContentOpacityAnimations);
            return(group);
        }
        /// <summary>
        /// Creates an animation template for a "color slide" type effect on a rectangular colored visual.
        /// This is a sub-second animation on the Scale property of the visual.
        /// </summary>
        private void InitializeSlideAnimation()
        {
            _slideAnimation = _compositor.CreateScalarKeyFrameAnimation();
            _slideAnimation.InsertKeyFrame(1.0f, 0f);
            _slideAnimation.Duration = TimeSpan.FromMilliseconds(800); // keeping this under a sec to not be obtrusive

        }
        public MainPage()
        {
            this.InitializeComponent();
            ContactsCVS.Source = _list;

            this.Loaded += (s, e) =>
            {
                _scrollViewer = ListView.GetScrollViewer();
                _scrollViewer.DirectManipulationStarted   += OnDirectManipulationStarted;
                _scrollViewer.DirectManipulationCompleted += OnDirectManipulationCompleted;

                // Retrieve the ScrollViewer manipulation and the Compositor.
                _scrollerViewerManipulation = ElementCompositionPreview.GetScrollViewerManipulationPropertySet(_scrollViewer);
                _compositor = _scrollerViewerManipulation.Compositor;

                // At the moment there are three things happening when pulling down the list -
                // 1. The Refresh Icon fades in.
                // 2. The Refresh Icon rotates (400°).
                // 3. The Refresh Icon gets pulled down a bit (REFRESH_ICON_MAX_OFFSET_Y)
                // QUESTION 5
                // Can we also have Geometric Path animation so we can also draw the Refresh Icon along the way?
                //

                // Create a rotation expression animation based on the overpan distance of the ScrollViewer.
                _rotationAnimation = _compositor.CreateExpressionAnimation("min(max(0, ScrollManipulation.Translation.Y) * Multiplier, MaxDegree)");
                _rotationAnimation.SetScalarParameter("Multiplier", 10.0f);
                _rotationAnimation.SetScalarParameter("MaxDegree", 400.0f);
                _rotationAnimation.SetReferenceParameter("ScrollManipulation", _scrollerViewerManipulation);

                // Create an opacity expression animation based on the overpan distance of the ScrollViewer.
                _opacityAnimation = _compositor.CreateExpressionAnimation("min(max(0, ScrollManipulation.Translation.Y) / Divider, 1)");
                _opacityAnimation.SetScalarParameter("Divider", 30.0f);
                _opacityAnimation.SetReferenceParameter("ScrollManipulation", _scrollerViewerManipulation);

                // Create an offset expression animation based on the overpan distance of the ScrollViewer.
                _offsetAnimation = _compositor.CreateExpressionAnimation("(min(max(0, ScrollManipulation.Translation.Y) / Divider, 1)) * MaxOffsetY");
                _offsetAnimation.SetScalarParameter("Divider", 30.0f);
                _offsetAnimation.SetScalarParameter("MaxOffsetY", REFRESH_ICON_MAX_OFFSET_Y);
                _offsetAnimation.SetReferenceParameter("ScrollManipulation", _scrollerViewerManipulation);

                // Create a keyframe animation to reset properties like Offset.Y, Opacity, etc.
                _resetAnimation = _compositor.CreateScalarKeyFrameAnimation();
                _resetAnimation.InsertKeyFrame(1.0f, 0.0f);

                // Create a loading keyframe animation (in this case, a rotation animation).
                _loadingAnimation = _compositor.CreateScalarKeyFrameAnimation();
                _loadingAnimation.InsertKeyFrame(1.0f, 360);
                _loadingAnimation.Duration          = TimeSpan.FromMilliseconds(1200);
                _loadingAnimation.IterationBehavior = AnimationIterationBehavior.Forever;

                // Get the RefreshIcon's Visual.
                _refreshIconVisual = ElementCompositionPreview.GetElementVisual(RefreshIcon);
                // Set the center point for the rotation animation.
                _refreshIconVisual.CenterPoint = new Vector3(Convert.ToSingle(RefreshIcon.ActualWidth / 2), Convert.ToSingle(RefreshIcon.ActualHeight / 2), 0);

                // Get the ListView's inner Border's Visual.
                var border = (Border)VisualTreeHelper.GetChild(ListView, 0);
                _borderVisual = ElementCompositionPreview.GetElementVisual(border);

                PrepareExpressionAnimationsOnScroll();
            };

            this.Unloaded += (s, e) =>
            {
                _scrollViewer.DirectManipulationStarted   -= OnDirectManipulationStarted;
                _scrollViewer.DirectManipulationCompleted -= OnDirectManipulationCompleted;
            };
        }
 public static ScalarKeyFrameAnimation SetTarget(this ScalarKeyFrameAnimation animation, string target)
 {
     animation.Target = target;
     return(animation);
 }
 /// <summary>
 ///
 /// </summary>
 /// <param name="animation"></param>
 /// <param name="duration">Duration in seconds</param>
 /// <returns></returns>
 public static ScalarKeyFrameAnimation SetDuration(this ScalarKeyFrameAnimation animation, double duration)
 {
     return(SetDuration(animation, TimeSpan.FromSeconds(duration)));
 }
 void TouchArea_ManipulationStarted(object sender, ManipulationStartedRoutedEventArgs e)
 {
     // reset the animation
     // todo: wonder if there should be a method to remove a certain key frame?
     // so I'd only need to remove the keyframe (_animation.InsertKeyFrame(1.0f, new Vector3());)
     // rather than create a new animation instance
     _x = 0.0f;
     _animation = _compositor.CreateScalarKeyFrameAnimation();
     _animation.InsertExpressionKeyFrame(0.0f, "touch.Offset.X");
     _animation.SetReferenceParameter("touch", _touchAreaVisual);
 }
 internal ScalarKeyFrameTransitionAnimationFluentContext([NotNull] StoryBoardFluentContext parentStoryBoard, [NotNull] ScalarKeyFrameAnimation animation, [NotNull] String targetProperty) : base(parentStoryBoard, animation, targetProperty)
 {
 }