Exemplo n.º 1
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);
        }
Exemplo n.º 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;
        }
Exemplo n.º 3
0
        /// <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
        }
        /// <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

        }
Exemplo n.º 5
0
        private void PlayIndicatorAnimations(UIElement indicator, float from, float to, Vector2 beginSize, Vector2 endSize, bool isOutgoing)
        {
            Visual     visual = ElementCompositionPreview.GetElementVisual(indicator);
            Compositor comp   = visual.Compositor;

            Vector2 size      = indicator.RenderSize.ToVector2();
            float   dimension = Orientation == Orientation.Horizontal ? size.X : size.Y;

            float beginScale = 1.0f;
            float endScale   = 1.0f;

            if (Orientation == Orientation.Horizontal && MathF.Abs(size.X) > 0.001f)
            {
                beginScale = beginSize.X / size.X;
                endScale   = endSize.X / size.X;
            }

            StepEasingFunction singleStep = comp.CreateStepEasingFunction();

            singleStep.IsFinalStepSingleFrame = true;

            if (isOutgoing)
            {
                // fade the outgoing indicator so it looks nice when animating over the scroll area
                ScalarKeyFrameAnimation opacityAnim = comp.CreateScalarKeyFrameAnimation();
                opacityAnim.InsertKeyFrame(0.0f, 1.0f);
                opacityAnim.InsertKeyFrame(0.333f, 1.0f, singleStep);
                opacityAnim.InsertKeyFrame(1.0f, 0.0f, comp.CreateCubicBezierEasingFunction(c_frame2point1, c_frame2point2));
                opacityAnim.Duration = TimeSpan.FromMilliseconds(600);

                visual.StartAnimation("Opacity", opacityAnim);
            }
            else
            {
                visual.Opacity = 1;
            }

            ScalarKeyFrameAnimation posAnim = comp.CreateScalarKeyFrameAnimation();

            posAnim.InsertKeyFrame(0.0f, from < to ? from : (from + (dimension * (beginScale - 1))));
            posAnim.InsertKeyFrame(0.333f, from < to ? (to + (dimension * (endScale - 1))) : to, singleStep);
            posAnim.Duration = TimeSpan.FromMilliseconds(600);

            ScalarKeyFrameAnimation scaleAnim = comp.CreateScalarKeyFrameAnimation();

            scaleAnim.InsertKeyFrame(0.0f, beginScale);
            scaleAnim.InsertKeyFrame(0.333f, MathF.Abs(to - from) / dimension + (from < to ? endScale : beginScale), comp.CreateCubicBezierEasingFunction(c_frame1point1, c_frame1point2));
            scaleAnim.InsertKeyFrame(1.0f, endScale, comp.CreateCubicBezierEasingFunction(c_frame2point1, c_frame2point2));
            scaleAnim.Duration = TimeSpan.FromMilliseconds(600);

            ScalarKeyFrameAnimation centerAnim = comp.CreateScalarKeyFrameAnimation();

            centerAnim.InsertKeyFrame(0.0f, from < to ? 0.0f : dimension);
            centerAnim.InsertKeyFrame(1.0f, from < to ? dimension : 0.0f, singleStep);
            centerAnim.Duration = TimeSpan.FromMilliseconds(200);

            if (Orientation == Orientation.Horizontal)
            {
                visual.StartAnimation("Offset.X", posAnim);
                visual.StartAnimation("Scale.X", scaleAnim);
                visual.StartAnimation("CenterPoint.X", centerAnim);
            }
            else
            {
                visual.StartAnimation("Offset.Y", posAnim);
                visual.StartAnimation("Scale.Y", scaleAnim);
                visual.StartAnimation("CenterPoint.Y", centerAnim);
            }
        }
Exemplo n.º 6
0
 public static ScalarKeyFrameAnimation AddKeyFrame(this ScalarKeyFrameAnimation animation, float normalizedProgressKey, float value, KeySpline ease)
 {
     animation.InsertKeyFrame(normalizedProgressKey, value, animation.Compositor.CreateCubicBezierEasingFunction(ease));
     return animation;
 }
Exemplo n.º 7
0
        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 = 1, M12 = 0f, M13 = 0f, M14 = 2,
                    M21 = 0f, M22 = 1f, M23 = 0f, M24 = -1,
                    M31 = 0f, M32 = 0f, M33 = 1f, M34 = -1,
                    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;
            }
        }
Exemplo n.º 8
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);
        }
Exemplo n.º 9
0
        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(listView);
            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)listView.ActualWidth / 2, (float)listView.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, targetOffset.Y, (float)PerspectivePanel.ActualWidth * zoomFactor) * 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();
        }
        private void OnAssociatedObjectLoaded(object sender, RoutedEventArgs e)
        {
            _scrollViewer = AssociatedObject.GetScrollViewer();
            _scrollViewer.DirectManipulationStarted   += OnScrollViewerDirectManipulationStarted;
            _scrollViewer.DirectManipulationCompleted += OnScrollViewerDirectManipulationCompleted;
            _callbackId = _scrollViewer.RegisterPropertyChangedCallback(ScrollViewer.ScrollableHeightProperty,
                                                                        OnScrollViewerScrollableHeightChanged);

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

            // Set boundaries.
            var listViewBaseVisual = ElementCompositionPreview.GetElementVisual(AssociatedObject);
            var clip = _compositor.CreateInsetClip();

            listViewBaseVisual.Clip = clip;

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

            UpdateScrollableHeightInScrollViewerPropertySet();

            // Create a rotation expression animation based on the overpan distance of the ScrollViewer.
            _rotationAnimation = _compositor.CreateExpressionAnimation($"min({PullDistanceExpression} * DegreeMultiplier, MaxDegree)");
            _rotationAnimation.SetScalarParameter("DegreeMultiplier", 10.0f);
            _rotationAnimation.SetScalarParameter("MaxDegree", (float)IconElementMaxRotationAngle);
            _rotationAnimation.SetReferenceParameter("ScrollManipulation", _scrollerViewerManipulation);

            // Create an opacity expression animation based on the overpan distance of the ScrollViewer.
            _opacityAnimation = _compositor.CreateExpressionAnimation($"min({PullDistanceExpression} / {PullThresholdExpression}, 1)");
            _opacityAnimation.SetScalarParameter("PullThresholdMaxOverpanRatio", (float)PullThresholdMaxOverpanRatio);
            _opacityAnimation.SetReferenceParameter("ScrollManipulation", _scrollerViewerManipulation);

            // Create an offset expression animation based on the overpan distance of the ScrollViewer.
            _offsetAnimation = _compositor.CreateExpressionAnimation($"min({PullDistanceExpression} / {PullThresholdExpression}, 1) * MaxPulledDistance");
            _offsetAnimation.SetScalarParameter("PullThresholdMaxOverpanRatio", (float)PullThresholdMaxOverpanRatio);
            _offsetAnimation.SetScalarParameter("MaxPulledDistance", IconElementMaxPulledOffsetY);
            _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.InsertExpressionKeyFrame(0.0f, "this.StartingValue");
            _loadingAnimation.InsertExpressionKeyFrame(1.0f, "this.StartingValue + 360");
            _loadingAnimation.Duration          = TimeSpan.FromMilliseconds(1200);
            _loadingAnimation.IterationBehavior = AnimationIterationBehavior.Forever;

            // Get the RefreshIcon's Visual.
            _refreshIconVisual = ElementCompositionPreview.GetElementVisual(IconElement);
            // Set the center point for the rotation animation.
            _refreshIconVisual.CenterPoint = new Vector3(IconElement.RenderSize.ToVector2() / 2, 0.0f);

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

            _borderVisual = ElementCompositionPreview.GetElementVisual(border);

            StartExpressionAnimations();
        }
Exemplo n.º 11
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 = .1f,
                        Source2       = new Transform2DEffect
                        {
                            Name   = "LightMapTransform",
                            Source = new CompositionEffectSourceParameter("LightMap")
                        },
                        Source2Amount  = 0,
                        MultiplyAmount = 1
                    }
                }
            };

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

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

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

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

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

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

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

            return(null);
        }
Exemplo n.º 12
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);
        }
Exemplo n.º 13
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();
        }
Exemplo n.º 14
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);
        }
Exemplo n.º 15
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);
        }
Exemplo n.º 16
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(() => surfaceBrush.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(() => surfaceBrush.VerticalAlignmentRatio, alignYAnimation);
            }
        }
Exemplo n.º 17
0
        private async void FlipCardFaceUp(Button btn)
        {
            //Flip button visual
            var btnVisual  = ElementCompositionPreview.GetElementVisual(btn);
            var compositor = btnVisual.Compositor;

            //Get a visual for the content
            var btnContent       = VisualTreeHelper.GetChild(VisualTreeHelper.GetChild(btn, 0), 0);
            var btnContentVisual = ElementCompositionPreview.GetElementVisual(btnContent as FrameworkElement);

            var easing = compositor.CreateLinearEasingFunction();

            if (_flipBatchAnimation != null)
            {
                _flipBatchAnimation.Completed -= FlipBatchAnimation_Completed;
                _flipBatchAnimation.Dispose();
            }

            _flipBatchAnimation            = compositor.CreateScopedBatch(CompositionBatchTypes.Animation);
            _flipBatchAnimation.Completed += FlipBatchAnimation_Completed;

            ScalarKeyFrameAnimation flipAnimation = compositor.CreateScalarKeyFrameAnimation();

            flipAnimation.InsertKeyFrame(0.000001f, 180);
            flipAnimation.InsertKeyFrame(1f, 0, easing);
            flipAnimation.Duration          = TimeSpan.FromMilliseconds(800);
            flipAnimation.IterationBehavior = AnimationIterationBehavior.Count;
            flipAnimation.IterationCount    = 1;
            btnVisual.CenterPoint           = new Vector3((float)(0.5 * btn.ActualWidth), (float)(0.5f * btn.ActualHeight), 0f);
            btnVisual.RotationAxis          = new Vector3(0.0f, 1f, 0f);

            ScalarKeyFrameAnimation appearAnimation = compositor.CreateScalarKeyFrameAnimation();

            appearAnimation.InsertKeyFrame(0.0f, 0);
            appearAnimation.InsertKeyFrame(0.599999f, 0);
            appearAnimation.InsertKeyFrame(0.6f, 0.5f);
            appearAnimation.InsertKeyFrame(1f, 1);
            appearAnimation.Duration          = TimeSpan.FromMilliseconds(800);
            appearAnimation.IterationBehavior = AnimationIterationBehavior.Count;
            appearAnimation.IterationCount    = 1;

            btnVisual.StartAnimation(nameof(btnVisual.RotationAngleInDegrees), flipAnimation);
            btnContentVisual.StartAnimation(nameof(btnContentVisual.Opacity), appearAnimation);
            _flipBatchAnimation.End();

            if (_usePictures)
            {
                var file = await StorageFile.GetFileFromPathAsync(btn.Tag.ToString());

                using (var stream = await file.OpenAsync(FileAccessMode.Read))
                {
                    var image = new Image();
                    var bmp   = new BitmapImage();
                    await bmp.SetSourceAsync(stream);

                    image.Source = bmp;
                    btn.Content  = image;
                }
            }
            else
            {
                btn.Content = btn.Tag.ToString();
            }
        }
Exemplo n.º 18
0
#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;
        }
Exemplo n.º 19
0
        private void Page_Loaded(object sender, RoutedEventArgs e)
        {
            // create the compositor
            _compositor = ElementCompositionPreview.GetElementVisual(this).Compositor;

            // create what captures the pointer position
            _hoverPositionPropertySet = ElementCompositionPreview.GetPointerPositionPropertySet(r2);

            // create the two visuals
            _vis      = _compositor.CreateSpriteVisual();
            _pulseVis = _compositor.CreateSpriteVisual();

            // create the main brush with warm colors
            _mainBrush = _compositor.CreateRadialGradientBrush();
            _mainBrush.EllipseCenter = new Vector2(.5f, .5f);
            _mainBrush.EllipseRadius = new Vector2(.5f, .5f);

            _MBGradientStop1        = _compositor.CreateColorGradientStop();
            _MBGradientStop1.Offset = 0;
            _MBGradientStop1.Color  = _warmColor1;

            _MBGradientStop2        = _compositor.CreateColorGradientStop();
            _MBGradientStop2.Offset = .1f;
            _MBGradientStop2.Color  = _warmColor2;

            _MBGradientStop3        = _compositor.CreateColorGradientStop();
            _MBGradientStop3.Offset = 1;
            _MBGradientStop3.Color  = _warmColor3;

            _mainBrush.ColorStops.Add(_MBGradientStop1);
            _mainBrush.ColorStops.Add(_MBGradientStop2);
            _mainBrush.ColorStops.Add(_MBGradientStop3);

            // create the brush for the pulse visual
            _pulseBrush = _compositor.CreateRadialGradientBrush();
            _pulseBrush.EllipseCenter = new Vector2(.5f, .5f);
            _pulseBrush.EllipseRadius = new Vector2(.5f, .5f);

            _PBGradientStop1        = _compositor.CreateColorGradientStop();
            _PBGradientStop1.Offset = 0;
            _PBGradientStop1.Color  = _innerPulseColor;

            _PBGradientStop2        = _compositor.CreateColorGradientStop();
            _PBGradientStop2.Offset = 1;
            _PBGradientStop2.Color  = _innerPulseColor;

            _pulseBrush.ColorStops.Add(_PBGradientStop1);
            _pulseBrush.ColorStops.Add(_PBGradientStop2);

            // finish setting properties of the first visual
            _vis.Size        = new Vector2(300, 300);
            _vis.Offset      = new Vector3(((float)r2.ActualWidth / 2), ((float)r2.ActualHeight / 2), 0);
            _vis.AnchorPoint = new Vector2(.5f, .5f);
            _vis.Brush       = _mainBrush;

            // finish setting properties of the pulsing visual
            _pulseVis.Size        = new Vector2(500, 500);
            _pulseVis.Offset      = new Vector3(((float)r1.ActualWidth / 2), ((float)r1.ActualHeight / 2), 0);
            _pulseVis.AnchorPoint = new Vector2(.5f, .5f);
            _pulseVis.Brush       = _pulseBrush;

            // create the clip that makes the visuals circular
            CompositionGeometricClip   gClip  = _compositor.CreateGeometricClip();
            CompositionEllipseGeometry circle = _compositor.CreateEllipseGeometry();

            circle.Radius  = new Vector2(_vis.Size.X / 2, _vis.Size.Y / 2);
            circle.Center  = new Vector2(_vis.Size.X / 2, _vis.Size.Y / 2);
            gClip.Geometry = circle;

            _vis.Clip = gClip;

            CompositionGeometricClip   gClip2  = _compositor.CreateGeometricClip();
            CompositionEllipseGeometry circle2 = _compositor.CreateEllipseGeometry();

            circle2.Radius  = new Vector2(_pulseVis.Size.X / 2, _pulseVis.Size.Y / 2);
            circle2.Center  = new Vector2(_pulseVis.Size.X / 2, _pulseVis.Size.Y / 2);
            gClip2.Geometry = circle2;

            _pulseVis.Clip = gClip2;

            // set the pointer
            my_pointer = new Vector3(((float)r1.ActualWidth / 2), ((float)r1.ActualHeight / 2), 0);

            // set the visuals in the tree
            ElementCompositionPreview.SetElementChildVisual(r2, _vis);
            ElementCompositionPreview.SetElementChildVisual(r1, _pulseVis);

            // ellipse center follows mouse
            _ellipseCenterAnim = _compositor.CreateExpressionAnimation("Vector2(p.Position.X / 500.0f, p.Position.Y / 500.0f)");
            _ellipseCenterAnim.SetReferenceParameter("p", _hoverPositionPropertySet);
            _mainBrush.StartAnimation("EllipseCenter", _ellipseCenterAnim);

            // second stop is animated for "pulsing" effect within the first visual that runs constantly
            _offsetAnim = _compositor.CreateScalarKeyFrameAnimation();
            _offsetAnim.InsertKeyFrame(0, 0);
            _offsetAnim.InsertKeyFrame(1f, 1f);
            _offsetAnim.Duration       = TimeSpan.FromSeconds(2);
            _offsetAnim.IterationCount = 50;

            _MBGradientStop2.StartAnimation("Offset", _offsetAnim);

            // set up the animation for the backing pulse visual
            // animate the color
            _pulseColorAnim = _compositor.CreateColorKeyFrameAnimation();
            _pulseColorAnim.InsertKeyFrame(0, _innerPulseColor);
            _pulseColorAnim.InsertKeyFrame(.99f, _outerPulseColor);
            _pulseColorAnim.InsertKeyFrame(1, _innerPulseColor);
            _pulseColorAnim.Duration          = TimeSpan.FromSeconds(1);
            _pulseColorAnim.IterationBehavior = AnimationIterationBehavior.Forever;

            _PBGradientStop1.StartAnimation("Color", _pulseColorAnim);

            // animate offset of first stop
            _pulseStop1OffsetAnim = _compositor.CreateScalarKeyFrameAnimation();
            _pulseStop1OffsetAnim.InsertKeyFrame(0, 0);
            _pulseStop1OffsetAnim.InsertKeyFrame(1f, 1f);
            _pulseStop1OffsetAnim.Duration          = TimeSpan.FromSeconds(1);
            _pulseStop1OffsetAnim.IterationBehavior = AnimationIterationBehavior.Forever;

            _PBGradientStop1.StartAnimation("Offset", _pulseStop1OffsetAnim);

            // animate offset of second stop
            _pulseStop2OffsetAnim = _compositor.CreateScalarKeyFrameAnimation();
            _pulseStop2OffsetAnim.InsertKeyFrame(0, 0);
            _pulseStop2OffsetAnim.InsertKeyFrame(1f, 1f);
            _pulseStop2OffsetAnim.Duration          = TimeSpan.FromSeconds(1);
            _pulseStop2OffsetAnim.IterationBehavior = AnimationIterationBehavior.Forever;
            _pulseStop2OffsetAnim.DelayTime         = TimeSpan.FromSeconds(.25f);

            _PBGradientStop2.StartAnimation("Offset", _pulseStop2OffsetAnim);

            _pulseScaleAnim = _compositor.CreateVector3KeyFrameAnimation();
            _pulseScaleAnim.InsertKeyFrame(0, Vector3.Zero);
            _pulseScaleAnim.InsertKeyFrame(1, Vector3.One);
            _pulseScaleAnim.Duration          = TimeSpan.FromSeconds(1);
            _pulseScaleAnim.IterationBehavior = AnimationIterationBehavior.Forever;

            _pulseVis.StartAnimation("Scale", _pulseScaleAnim);
        }
Exemplo n.º 20
0
        public override async Task<CompositionDrawingSurface> LoadResources()
        {
            var graphicsEffect = new ArithmeticCompositeEffect
            {
                Name = "Arithmetic",
                Source1 = new CompositionEffectSourceParameter("ImageSource"),
                Source1Amount = .25f,
                Source2 = new Transform2DEffect
                {
                    Name = "LightMapTransform",
                    Source = new CompositionEffectSourceParameter("LightMap")
                },
                Source2Amount = 0,
                MultiplyAmount = 1
            };

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

            // Create the image
            _lightMap = await 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 CompositionAnimation GetAnimation <TKeyFrame>(
            CompositionObject target,
            string property,
            TimeSpan?delay,
            TimeSpan duration,
            RepeatOption repeat,
            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.DelayTime = delay !.Value;
            }

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

            return(animation);
        }
Exemplo n.º 22
0
        public override async Task<CompositionDrawingSurface> LoadResources()
        {
            var graphicsEffect = new ArithmeticCompositeEffect
            {
                Name = "Arithmetic",
                Source1 = new CompositionEffectSourceParameter("ImageSource"),
                Source1Amount = .1f,
                Source2 = new Transform2DEffect
                {
                    Name = "LightMapTransform",
                    Source = new CompositionEffectSourceParameter("LightMap")
                },
                Source2Amount = 0,
                MultiplyAmount = 1
            };

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

            // Create the image
            _lightMap = await 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;
        }
Exemplo n.º 23
0
 public static ScalarKeyFrameAnimation AddKeyFrame(this ScalarKeyFrameAnimation animation, float normalizedProgressKey, float value, CompositionEasingFunction ease = null)
 {
     animation.InsertKeyFrame(normalizedProgressKey, value, ease);
     return animation;
 }
Exemplo n.º 24
0
#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;
        }
Exemplo n.º 25
0
        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();
        }
Exemplo n.º 26
0
        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;
            };
        }
Exemplo n.º 27
0
        protected override void OnConnected()
        {
            if (DesignMode.DesignModeEnabled)
            {
                return;
            }
            compositor = ElementCompositionPreview.GetElementVisual(Window.Current.Content as UIElement).Compositor;
            var tintOpacity = Convert.ToSingle(TintOpacity);

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

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

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

            var imagebrush = compositor.CreateSurfaceBrush(imagesurface);

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

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

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

            CompositionBrush = Brush;

            var line = compositor.CreateLinearEasingFunction();

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

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

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

            //Window.Current.Activated += Current_Activated;
            //Window.Current.VisibilityChanged += Current_VisibilityChanged;
            CoreWindow.GetForCurrentThread().Activated         += AcrylicBrush_Activated;
            CoreWindow.GetForCurrentThread().VisibilityChanged += AcrylicBrush_VisibilityChanged;
        }
Exemplo n.º 28
0
        private void PlayingView_Loaded(object sender, RoutedEventArgs e)
        {
            if (Windows.ApplicationModel.DesignMode.DesignModeEnabled)
            {
                return;
            }
            // get the private fields
            _rootGrid           = this.RootGrid;
            _rootGridVisual     = ElementCompositionPreview.GetElementVisual(this.RootGrid);
            _compositor         = _rootGridVisual.Compositor;
            _playerDiskVisual   = ElementCompositionPreview.GetElementVisual(this.playerDiskGrid);
            _playerNeedleVisual = ElementCompositionPreview.GetElementVisual(this.playerNeedle);
            //_coverBackImageVisual = ElementCompositionPreview.GetElementVisual(this.coverBGImage);
            this.backCanvasControl.CreateResources += BackCanvasControl_CreateResources;
            this.backCanvasControl.Draw            += BackCanvasControl_Draw;

            // prepare animations
            var liner = _compositor.CreateLinearEasingFunction();

            _openPlayingViewScaleAnimation = _compositor.CreateVector3KeyFrameAnimation();
            _openPlayingViewScaleAnimation.InsertKeyFrame(0.0f, new System.Numerics.Vector3(0.0f, 0f, 1f));
            _openPlayingViewScaleAnimation.InsertKeyFrame(1.0f, new System.Numerics.Vector3(1f, 1f, 1f), liner);
            _openPlayingViewScaleAnimation.Duration = TimeSpan.FromMilliseconds(300);

            _closePlayingViewScaleAnimation = _compositor.CreateVector3KeyFrameAnimation();
            _closePlayingViewScaleAnimation.InsertKeyFrame(0.0f, new System.Numerics.Vector3(1f, 1f, 1f));
            _closePlayingViewScaleAnimation.InsertKeyFrame(1.0f, new System.Numerics.Vector3(0f, 0f, 1f), liner);
            _closePlayingViewScaleAnimation.Duration = TimeSpan.FromMilliseconds(300);

            _closePlayingViewOpacityAnimation = _compositor.CreateScalarKeyFrameAnimation();
            _closePlayingViewOpacityAnimation.InsertKeyFrame(0.0f, 1.0f);
            _closePlayingViewOpacityAnimation.InsertKeyFrame(1.0f, 0.3f, liner);
            _closePlayingViewOpacityAnimation.Duration = TimeSpan.FromMilliseconds(300);

            _openPlayingViewOpacityAnimation = _compositor.CreateScalarKeyFrameAnimation();
            _openPlayingViewOpacityAnimation.InsertKeyFrame(0.0f, 0.3f);
            _openPlayingViewOpacityAnimation.InsertKeyFrame(1.0f, 1.0f, liner);
            _openPlayingViewOpacityAnimation.Duration = TimeSpan.FromMilliseconds(300);
            // Playing rotation animation
            _diskRotationAnimation = _compositor.CreateScalarKeyFrameAnimation();
            _diskRotationAnimation.InsertKeyFrame(0.0f, 0f);
            _diskRotationAnimation.InsertKeyFrame(1f, 360.0f, liner);
            _diskRotationAnimation.Duration          = TimeSpan.FromSeconds(30);
            _diskRotationAnimation.IterationBehavior = AnimationIterationBehavior.Forever;

            _needleStartAnimation = _compositor.CreateScalarKeyFrameAnimation();
            _needleStartAnimation.InsertKeyFrame(0f, -30f);
            _needleStartAnimation.InsertKeyFrame(1f, 0f, liner);
            _needleStartAnimation.Duration = TimeSpan.FromMilliseconds(500);

            _needleStopAnimation = _compositor.CreateScalarKeyFrameAnimation();
            _needleStopAnimation.InsertKeyFrame(0f, 0f);
            _needleStopAnimation.InsertKeyFrame(1f, -30f, liner);
            _needleStopAnimation.Duration = TimeSpan.FromMilliseconds(500);

            // set centerpoint
            _rootGridVisual.CenterPoint     = new System.Numerics.Vector3(0.0f, (float)RootGrid.ActualHeight, 0.0f);
            _playerDiskVisual.CenterPoint   = new System.Numerics.Vector3((float)(this.playerDiskGrid.ActualWidth / 2), (float)(this.playerDiskGrid.ActualHeight / 2), 0f);
            _playerNeedleVisual.CenterPoint = new System.Numerics.Vector3((float)(this.playerNeedle.ActualWidth / 2), 0f, 0f);


            // Set initial state of the visuals
            //_rootGridVisual.Scale = new System.Numerics.Vector3(0.0f, 0f, 1f);
            _playerNeedleVisual.RotationAngleInDegrees = -30f;

            // Note: Using storyboard instead of Composition API
            // Because blur appeares after compostion animation
            // It confused me!!
            _rootGrid.RenderTransform = new CompositeTransform()
            {
                ScaleX = 0, ScaleY = 0
            };

            // Set CoverBackground Effect; Don't support GaussionEffect!!
            //PrepareBlurCover();
        }
Exemplo n.º 29
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();
 }
 /// <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
 }
Exemplo n.º 31
0
        private void InitializeComposition()
        {
            _compositor    = ElementCompositionPreview.GetElementVisual(this).Compositor;
            menuGridVisual = ElementCompositionPreview.GetElementVisual(MenuGrid);

            var scaleFactor = 5f;

            _scaleUpMenuAnimation = _compositor.CreateVector2KeyFrameAnimation();
            _scaleUpMenuAnimation.InsertKeyFrame(1, new Vector2(scaleFactor, scaleFactor));
            _scaleUpMenuAnimation.Duration = TimeSpan.FromSeconds(MenuGridScaleUpDuration);

            _scaleDownMenuAnimation = _compositor.CreateVector2KeyFrameAnimation();
            _scaleDownMenuAnimation.InsertKeyFrame(1, Vector2.One);
            _scaleDownMenuAnimation.Duration = TimeSpan.FromSeconds(MenuGridScaleDownDuration);

            _scaleX           = (float)(400.00 / (ItemSize / 1f));
            _scaleY           = (float)(700.0 / (ItemSize / 1f));
            _scaleUpAnimation = _compositor.CreateVector2KeyFrameAnimation();
            _scaleUpAnimation.InsertKeyFrame(1, new Vector2(_scaleX, _scaleY));
            _scaleUpAnimation.Duration = TimeSpan.FromSeconds(MenuGridScaleUpDuration);

            _scaleDownAnimation = _compositor.CreateVector2KeyFrameAnimation();
            _scaleDownAnimation.InsertKeyFrame(1, Vector2.One);
            _scaleDownAnimation.Duration = TimeSpan.FromSeconds(MenuGridScaleDownDuration);

            _scaleUpContentAnimation = _compositor.CreateVector2KeyFrameAnimation();
            _scaleUpContentAnimation.InsertKeyFrame(1, Vector2.One);
            _scaleUpContentAnimation.Duration = TimeSpan.FromSeconds(MenuGridScaleUpDuration);

            _scaleDownContentAnimation = _compositor.CreateVector2KeyFrameAnimation();
            _scaleDownContentAnimation.InsertKeyFrame(1, new Vector2(1 / _scaleX, 1 / _scaleY));
            _scaleDownContentAnimation.Duration = TimeSpan.FromSeconds(MenuGridScaleDownDuration);

            _offsetUpAnimation = _compositor.CreateVector3KeyFrameAnimation();
            _offsetUpAnimation.InsertKeyFrame(1, Vector3.Zero);
            _offsetUpAnimation.Duration = TimeSpan.FromSeconds(MenuGridScaleUpDuration);

            _offsetDownAnimation          = _compositor.CreateVector3KeyFrameAnimation();
            _offsetDownAnimation.Duration = TimeSpan.FromSeconds(MenuGridScaleDownDuration);

            _fadeInMenuAnimation = _compositor.CreateScalarKeyFrameAnimation();
            _fadeInMenuAnimation.InsertKeyFrame(1f, 1);
            _fadeInMenuAnimation.Duration = TimeSpan.FromSeconds(FadeInMenuDuration);

            _fadeOutMenuAnimation = _compositor.CreateScalarKeyFrameAnimation();
            _fadeOutMenuAnimation.InsertKeyFrame(0.5f, 0f);
            _fadeOutMenuAnimation.Duration = TimeSpan.FromSeconds(FadeOutMenuDuration);

            _fadeInAnimation = _compositor.CreateScalarKeyFrameAnimation();
            _fadeInAnimation.InsertKeyFrame(0.5f, 1f, _compositor.CreateLinearEasingFunction());
            _fadeInAnimation.Duration = TimeSpan.FromSeconds(FadeInDuration);

            _fadeOutAnimation = _compositor.CreateScalarKeyFrameAnimation();
            _fadeOutAnimation.InsertKeyFrame(0.65f, 0);
            _fadeOutAnimation.Duration = TimeSpan.FromSeconds(FadeOutDuration);

            _fadeInContentAnimation = _compositor.CreateScalarKeyFrameAnimation();
            _fadeInContentAnimation.InsertKeyFrame(0.5f, 1f, _compositor.CreateLinearEasingFunction());
            _fadeInContentAnimation.Duration = TimeSpan.FromSeconds(FadeInDuration);

            _fadeOutContentAnimation = _compositor.CreateScalarKeyFrameAnimation();
            _fadeOutContentAnimation.InsertKeyFrame(0.5f, 0);
            _fadeOutContentAnimation.Duration = TimeSpan.FromSeconds(FadeOutDuration);
        }
Exemplo n.º 32
0
        private void UpdateAnimations()
        {
            Vector2 sizeLightBounds = new Vector2((float)RootPanel.ActualWidth, (float)RootPanel.ActualHeight + 200f);

            ComboBoxItem item = LightingSelection.SelectedValue as ComboBoxItem;

            switch ((LightingTypes)item.Tag)
            {
            case LightingTypes.PointDiffuse:
            case LightingTypes.PointSpecular:
            {
                // Create the light position animation
                _lightPositionAnimation = _compositor.CreateVector3KeyFrameAnimation();
                _lightPositionAnimation.InsertKeyFrame(0f, new Vector3(0f, 0f, 100f));
                _lightPositionAnimation.InsertKeyFrame(.25f, new Vector3(sizeLightBounds.X * .7f, sizeLightBounds.Y * .5f, 100f));
                _lightPositionAnimation.InsertKeyFrame(.50f, new Vector3(sizeLightBounds.X, sizeLightBounds.Y, 100f));
                _lightPositionAnimation.InsertKeyFrame(.75f, new Vector3(sizeLightBounds.X * .2f, sizeLightBounds.Y, 100f));
                _lightPositionAnimation.InsertKeyFrame(1f, new Vector3(0f, 0f, 100f));
                _lightPositionAnimation.Duration          = TimeSpan.FromMilliseconds(7500);
                _lightPositionAnimation.IterationBehavior = AnimationIterationBehavior.Forever;

                _lightColorAnimation = _compositor.CreateColorKeyFrameAnimation();
                _lightColorAnimation.InsertKeyFrame(0f, Colors.White);
                _lightColorAnimation.InsertKeyFrame(.33f, Colors.White);
                _lightColorAnimation.InsertKeyFrame(.66f, Colors.Yellow);
                _lightColorAnimation.InsertKeyFrame(1f, Colors.White);
                _lightColorAnimation.Duration          = TimeSpan.FromMilliseconds(20000);
                _lightColorAnimation.IterationBehavior = AnimationIterationBehavior.Forever;
            }
            break;

            case LightingTypes.SpotLightDiffuse:
            case LightingTypes.SpotLightSpecular:
            {
                // Create the light position animation
                _lightPositionAnimation = _compositor.CreateVector3KeyFrameAnimation();
                _lightPositionAnimation.InsertKeyFrame(0f, new Vector3(0f, 0f, 100f));
                _lightPositionAnimation.InsertKeyFrame(.33f, new Vector3(sizeLightBounds.X * .5f, sizeLightBounds.Y * .5f, 400f));
                _lightPositionAnimation.InsertKeyFrame(.66f, new Vector3(sizeLightBounds.X, sizeLightBounds.Y * .5f, 1400f));
                _lightPositionAnimation.InsertKeyFrame(1f, new Vector3(0f, 0f, 100f));
                _lightPositionAnimation.Duration          = TimeSpan.FromMilliseconds(7500);
                _lightPositionAnimation.IterationBehavior = AnimationIterationBehavior.Forever;

                _lightColorAnimation = _compositor.CreateColorKeyFrameAnimation();
                _lightColorAnimation.InsertKeyFrame(0f, Colors.White);
                _lightColorAnimation.InsertKeyFrame(.33f, Colors.White);
                _lightColorAnimation.InsertKeyFrame(.66f, Colors.Yellow);
                _lightColorAnimation.InsertKeyFrame(1f, Colors.White);
                _lightColorAnimation.Duration          = TimeSpan.FromMilliseconds(20000);
                _lightColorAnimation.IterationBehavior = AnimationIterationBehavior.Forever;
            }
            break;

            case LightingTypes.DistantDiffuse:
            case LightingTypes.DistantSpecular:
            {
                _lightAzimuthAnimation = _compositor.CreateScalarKeyFrameAnimation();
                _lightAzimuthAnimation.InsertKeyFrame(0f, 0f);
                _lightAzimuthAnimation.InsertKeyFrame(1f, (float)Math.PI * 2f);
                _lightAzimuthAnimation.Duration          = TimeSpan.FromMilliseconds(10000);
                _lightAzimuthAnimation.IterationBehavior = AnimationIterationBehavior.Forever;

                _lightElevationAnimation = _compositor.CreateScalarKeyFrameAnimation();
                _lightElevationAnimation.InsertKeyFrame(0f, (float)Math.PI * .5f);
                _lightElevationAnimation.InsertKeyFrame(.33f, (float)Math.PI * .25f);
                _lightElevationAnimation.InsertKeyFrame(.66f, (float)Math.PI * .75f);
                _lightElevationAnimation.InsertKeyFrame(1f, (float)Math.PI * .5f);
                _lightElevationAnimation.Duration          = TimeSpan.FromMilliseconds(5000);
                _lightElevationAnimation.IterationBehavior = AnimationIterationBehavior.Forever;
            }
            break;

            default:
                break;
            }
        }
        /// <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

        }
        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;
        }
Exemplo n.º 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
            }
        }
Exemplo n.º 36
0
        private void Scroller4_ZoomAnimationStarting(muxc.ScrollViewer sender, muxc.ZoomAnimationStartingEventArgs args)
        {
            try
            {
                ScalarKeyFrameAnimation stockKeyFrameAnimation = args.Animation as ScalarKeyFrameAnimation;

                if (stockKeyFrameAnimation != null)
                {
                    ScalarKeyFrameAnimation customKeyFrameAnimation = stockKeyFrameAnimation;

                    if (nameof(ZoomAnimationOptions.Default) != (string)cbZoomAnimation.SelectedItem)
                    {
                        float targetZoomFactor = (float)zoomFactorSlider.Value;

                        customKeyFrameAnimation = stockKeyFrameAnimation.Compositor.CreateScalarKeyFrameAnimation();
                        float deltaZoomFactor = (float)(targetZoomFactor - sender.ZoomFactor);

                        switch ((string)cbZoomAnimation.SelectedItem)
                        {
                        case nameof(ZoomAnimationOptions.Custom1):
                            // "Accordion" case
                            for (int step = 0; step < 3; step++)
                            {
                                customKeyFrameAnimation.InsertKeyFrame(
                                    1.0f - (0.4f / (float)Math.Pow(2, step)),
                                    targetZoomFactor + 0.1f * deltaZoomFactor);
                                deltaZoomFactor /= -2.0f;
                            }

                            customKeyFrameAnimation.InsertKeyFrame(1.0f, targetZoomFactor);
                            break;

                        case nameof(ZoomAnimationOptions.Custom2):
                            // "Teleportation" case

                            CubicBezierEasingFunction cubicBezierStart = stockKeyFrameAnimation.Compositor.CreateCubicBezierEasingFunction(
                                new Vector2(1.0f, 0.0f),
                                new Vector2(1.0f, 0.0f));

                            StepEasingFunction stepEasingFunc = stockKeyFrameAnimation.Compositor.CreateStepEasingFunction(1);

                            CubicBezierEasingFunction cubicBezierEnd = stockKeyFrameAnimation.Compositor.CreateCubicBezierEasingFunction(
                                new Vector2(0.0f, 1.0f),
                                new Vector2(0.0f, 1.0f));

                            customKeyFrameAnimation.InsertKeyFrame(
                                0.499999f,
                                targetZoomFactor - 0.75f * deltaZoomFactor,
                                cubicBezierStart);
                            customKeyFrameAnimation.InsertKeyFrame(
                                0.5f,
                                targetZoomFactor - 0.25f * deltaZoomFactor,
                                stepEasingFunc);
                            customKeyFrameAnimation.InsertKeyFrame(
                                1.0f,
                                targetZoomFactor,
                                cubicBezierEnd);
                            break;

                        default:
                            break;
                        }

                        customKeyFrameAnimation.Duration = stockKeyFrameAnimation.Duration;
                        args.Animation = customKeyFrameAnimation;
                    }

                    if (!string.IsNullOrWhiteSpace(tbZoomDuration.Text))
                    {
                        double durationOverride = Convert.ToDouble(tbZoomDuration.Text);
                        customKeyFrameAnimation.Duration = TimeSpan.FromMilliseconds(durationOverride);
                    }
                }
            }
            catch (Exception ex)
            {
            }
        }
        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;
            };
        }
Exemplo n.º 38
0
        private async void OnButtonClick(object sender, RoutedEventArgs e)
        {
            var btn = sender as Button;

            if (btn.Content != null)
            {
                return;
            }
            if (_flashTimer.IsEnabled)
            {
                OnFlashTimerTick(null, null);
            }

            _numMoves++;

            if (_firstButton == null)
            {
                _firstButton = btn;
            }
            else
            {
                _secondButton = btn;
            }

            //Flip button visual
            var btnVisual  = ElementCompositionPreview.GetElementVisual(btn);
            var compositor = btnVisual.Compositor;

            //Get a visual for the content
            var btnContent       = VisualTreeHelper.GetChild(VisualTreeHelper.GetChild(btn, 0), 0);
            var btnContentVisual = ElementCompositionPreview.GetElementVisual(btnContent as FrameworkElement);

            var easing = compositor.CreateLinearEasingFunction();

            ScalarKeyFrameAnimation flipAnimation = compositor.CreateScalarKeyFrameAnimation();

            flipAnimation.InsertKeyFrame(0.000001f, 180);
            flipAnimation.InsertKeyFrame(1f, 0, easing);
            flipAnimation.Duration          = TimeSpan.FromMilliseconds(800);
            flipAnimation.IterationBehavior = AnimationIterationBehavior.Count;
            flipAnimation.IterationCount    = 1;
            btnVisual.CenterPoint           = new Vector3((float)(0.5 * btn.ActualWidth), (float)(0.5f * btn.ActualHeight), (float)(btn.ActualWidth / 4));
            btnVisual.RotationAxis          = new Vector3(0.0f, 1f, 0f);

            ScalarKeyFrameAnimation appearAnimation = compositor.CreateScalarKeyFrameAnimation();

            appearAnimation.InsertKeyFrame(0.0f, 0);
            appearAnimation.InsertKeyFrame(0.499999f, 0);
            appearAnimation.InsertKeyFrame(0.5f, 1);
            appearAnimation.InsertKeyFrame(1f, 1);
            appearAnimation.Duration          = TimeSpan.FromMilliseconds(800);
            appearAnimation.IterationBehavior = AnimationIterationBehavior.Count;
            appearAnimation.IterationCount    = 1;

            btnVisual.StartAnimation(nameof(btnVisual.RotationAngleInDegrees), flipAnimation);
            btnContentVisual.StartAnimation(nameof(btnContentVisual.Opacity), appearAnimation);

            if (_usePictures)
            {
                var file = await StorageFile.GetFileFromPathAsync(btn.Tag.ToString());

                using (var stream = await file.OpenAsync(FileAccessMode.Read))
                {
                    var image = new Image();
                    var bmp   = new BitmapImage();
                    await bmp.SetSourceAsync(stream);

                    image.Source = bmp;
                    btn.Content  = image;
                }
            }
            else
            {
                btn.Content = btn.Tag.ToString();
            }

            if (_secondButton == null)
            {
                return;
            }

            if (_secondButton.Tag.ToString() != _firstButton.Tag.ToString())
            {
                _flashTimer.Start();
            }
            else
            {
                _firstButton  = null;
                _secondButton = null;
                _remaining   -= 2;

                CheckGameCompletion();
            }
        }
        public static void EnableFluidVisibilityAnimation(this UIElement element, AnimationAxis?axis = null,
                                                          float showFromOffset = 0.0f, float hideToOffset = 0.0f, Vector3?centerPoint = null,
                                                          float showFromScale  = 1.0f, float hideToScale  = 1.0f, float showDuration  = 800.0f, float hideDuration = 800.0f,
                                                          int showDelay        = 0, int hideDelay = 0, bool animateOpacity = true)
        {
            var elementVisual = element.Visual();
            var compositor    = elementVisual.Compositor;

            ElementCompositionPreview.SetIsTranslationEnabled(element, true);

            ScalarKeyFrameAnimation  hideOpacityAnimation = null;
            ScalarKeyFrameAnimation  showOpacityAnimation = null;
            ScalarKeyFrameAnimation  hideOffsetAnimation  = null;
            ScalarKeyFrameAnimation  showOffsetAnimation  = null;
            Vector2KeyFrameAnimation hideScaleAnimation   = null;
            Vector2KeyFrameAnimation showeScaleAnimation  = null;

            if (animateOpacity)
            {
                hideOpacityAnimation = compositor.CreateScalarKeyFrameAnimation();
                hideOpacityAnimation.InsertKeyFrame(1.0f, 0.0f);
                hideOpacityAnimation.Duration  = TimeSpan.FromMilliseconds(hideDuration);
                hideOpacityAnimation.DelayTime = TimeSpan.FromMilliseconds(hideDelay);
                hideOpacityAnimation.Target    = "Opacity";
            }

            if (!hideToOffset.Equals(0.0f))
            {
                if (axis == null)
                {
                    throw new NullReferenceException("Please specify AnimationAxis!");
                }

                hideOffsetAnimation = compositor.CreateScalarKeyFrameAnimation();
                hideOffsetAnimation.InsertKeyFrame(1.0f, hideToOffset);
                hideOffsetAnimation.Duration  = TimeSpan.FromMilliseconds(hideDuration);
                hideOffsetAnimation.DelayTime = TimeSpan.FromMilliseconds(hideDelay);
                hideOffsetAnimation.Target    = $"Translation.{axis}";
            }

            if (centerPoint.HasValue)
            {
                elementVisual.CenterPoint = centerPoint.Value;
            }

            if (!hideToScale.Equals(1.0f))
            {
                hideScaleAnimation = compositor.CreateVector2KeyFrameAnimation();
                hideScaleAnimation.InsertKeyFrame(1.0f, new Vector2(hideToScale));
                hideScaleAnimation.Duration  = TimeSpan.FromMilliseconds(hideDuration);
                hideScaleAnimation.DelayTime = TimeSpan.FromMilliseconds(hideDelay);
                hideScaleAnimation.Target    = "Scale.XY";
            }

            var hideAnimationGroup = compositor.CreateAnimationGroup();

            if (hideOpacityAnimation != null)
            {
                hideAnimationGroup.Add(hideOpacityAnimation);
            }
            if (hideOffsetAnimation != null)
            {
                hideAnimationGroup.Add(hideOffsetAnimation);
            }
            if (hideScaleAnimation != null)
            {
                hideAnimationGroup.Add(hideScaleAnimation);
            }

            ElementCompositionPreview.SetImplicitHideAnimation(element, hideAnimationGroup);

            if (animateOpacity)
            {
                elementVisual.Opacity = 0.0f;

                showOpacityAnimation = compositor.CreateScalarKeyFrameAnimation();
                showOpacityAnimation.InsertKeyFrame(1.0f, 1.0f);
                showOpacityAnimation.Duration  = TimeSpan.FromMilliseconds(showDuration);
                showOpacityAnimation.DelayTime = TimeSpan.FromMilliseconds(showDelay);
                showOpacityAnimation.Target    = "Opacity";
            }

            if (!showFromOffset.Equals(0.0f))
            {
                if (axis == null)
                {
                    throw new NullReferenceException("Please specify AnimationAxis!");
                }

                showOffsetAnimation = compositor.CreateScalarKeyFrameAnimation();
                showOffsetAnimation.InsertKeyFrame(0.0f, showFromOffset);
                showOffsetAnimation.InsertKeyFrame(1.0f, 0.0f);
                showOffsetAnimation.Duration  = TimeSpan.FromMilliseconds(showDuration);
                showOffsetAnimation.DelayTime = TimeSpan.FromMilliseconds(showDelay);
                showOffsetAnimation.Target    = $"Translation.{axis}";
            }

            if (!showFromScale.Equals(1.0f))
            {
                showeScaleAnimation = compositor.CreateVector2KeyFrameAnimation();
                showeScaleAnimation.InsertKeyFrame(0.0f, new Vector2(showFromScale));
                showeScaleAnimation.InsertKeyFrame(1.0f, Vector2.One);
                showeScaleAnimation.Duration  = TimeSpan.FromMilliseconds(showDuration);
                showeScaleAnimation.DelayTime = TimeSpan.FromMilliseconds(showDelay);
                showeScaleAnimation.Target    = "Scale.XY";
            }

            var showAnimationGroup = compositor.CreateAnimationGroup();

            if (showOpacityAnimation != null)
            {
                showAnimationGroup.Add(showOpacityAnimation);
            }
            if (showOffsetAnimation != null)
            {
                showAnimationGroup.Add(showOffsetAnimation);
            }
            if (showeScaleAnimation != null)
            {
                showAnimationGroup.Add(showeScaleAnimation);
            }

            ElementCompositionPreview.SetImplicitShowAnimation(element, showAnimationGroup);
        }
Exemplo n.º 40
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);
            }
        }