コード例 #1
0
        private void SamplePage_Loaded(object sender, Windows.UI.Xaml.RoutedEventArgs e)
        {
            // Get backing visual from shadow container and interop compositor
            _shadowContainer = ElementCompositionPreview.GetElementVisual(ShadowContainer);
            _compositor      = _shadowContainer.Compositor;

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

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

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

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

            // Initialize toggle mask
            _isMaskEnabled = false;
        }
コード例 #2
0
        public BackDrop()
        {
            _mRootVisual = ElementCompositionPreview.GetElementVisual(this);

            Compositor = _mRootVisual.Compositor;

            _mBlurVisual = Compositor.CreateSpriteVisual();

#if SDKVERSION_14393
            CompositionEffectBrush brush = BuildBlurBrush();
            brush.SetSourceParameter("source", _mCompositor.CreateBackdropBrush());
            _mBlurBrush        = brush;
            _mBlurVisual.Brush = _mBlurBrush;

            BlurAmount = 9;
#else
            m_blurBrush        = Compositor.CreateColorBrush(Colors.White);
            m_blurVisual.Brush = m_blurBrush;
#endif
            ElementCompositionPreview.SetElementChildVisual(this, _mBlurVisual);

            Loading  += OnLoading;
            Unloaded += OnUnloaded;
        }
コード例 #3
0
ファイル: Gears.cs プロジェクト: shenchauhan/WindowsUIDevLabs
        private void Setup()
        {
            var firstGearVisual = ElementCompositionPreview.GetElementVisual(FirstGear);

            firstGearVisual.Size        = new Vector2((float)FirstGear.ActualWidth, (float)FirstGear.ActualHeight);
            firstGearVisual.AnchorPoint = new Vector2(0.5f, 0.5f);

            for (int i = Container.Children.Count - 1; i > 0; i--)
            {
                Container.Children.RemoveAt(i);
            }

            _x             = 87;
            _y             = 0d;
            _width         = 100;
            _height        = 100;
            _gearDimension = 87;

            Count        = 1;
            _gearVisuals = new List <Visual>()
            {
                firstGearVisual
            };
        }
コード例 #4
0
        //</SnippetDoubleTapped>


        //private void SetVideoVisual()
        //{
        //    //<SnippetCompositor>
        //    Visual elementVisual = ElementCompositionPreview.GetElementVisual(_compositionCanvas);
        //    var compositor = elementVisual.Compositor;

        //    _mediaPlayer.SetSurfaceSize(new Size(_compositionCanvas.ActualWidth, _compositionCanvas.ActualHeight));
        //    MediaPlayerSurface surface = _mediaPlayer.GetSurface(compositor);

        //    SpriteVisual spriteVisual = compositor.CreateSpriteVisual();
        //    spriteVisual.Brush = compositor.CreateSurfaceBrush(surface.CompositionSurface);

        //    ElementCompositionPreview.SetElementChildVisual(_compositionCanvas, spriteVisual);
        //    //</SnippetCompositor>
        //}

        private void SetVideoVisualButton_Click(object sender, RoutedEventArgs e)
        {
            //<SnippetCompositor>
            _mediaPlayer.SetSurfaceSize(new Size(_compositionCanvas.ActualWidth, _compositionCanvas.ActualHeight));

            var compositor             = ElementCompositionPreview.GetElementVisual(this).Compositor;
            MediaPlayerSurface surface = _mediaPlayer.GetSurface(compositor);

            SpriteVisual spriteVisual = compositor.CreateSpriteVisual();

            spriteVisual.Size =
                new System.Numerics.Vector2((float)_compositionCanvas.ActualWidth, (float)_compositionCanvas.ActualHeight);

            CompositionBrush brush = compositor.CreateSurfaceBrush(surface.CompositionSurface);

            spriteVisual.Brush = brush;

            ContainerVisual container = compositor.CreateContainerVisual();

            container.Children.InsertAtTop(spriteVisual);

            ElementCompositionPreview.SetElementChildVisual(_compositionCanvas, container);
            //</SnippetCompositor>
        }
        private async void Page_Loaded(object sender, RoutedEventArgs e)
        {
            ThumbnailList.ItemsSource = ThumbnailList.ItemsSource = Model.AggregateDataSources(new ObservableCollection <Thumbnail>[] { Model.Landscapes, Model.Nature });

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

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

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

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

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

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

            // Create the .png surface
            _maskSurface = await ImageLoader.Instance.LoadFromUriAsync(new Uri("ms-appx:///Assets/NormalMapsAndMasks/ForegroundFocusMask.png"));

            ElementCompositionPreview.SetElementChildVisual(ThumbnailList, _destinationSprite);

            // Update the effect to set the appropriate brush
            UpdateEffect();
        }
コード例 #6
0
        void UpdateClip()
        {
            if (Child == null)
            {
                return;
            }

            var clipGeometry = Clip;

            if (clipGeometry == null)
            {
                return;
            }

            double width  = Child.ActualWidth;
            double height = Child.ActualHeight;

            if (height <= 0 && width <= 0)
            {
                return;
            }

            var visual     = ElementCompositionPreview.GetElementVisual(Child);
            var compositor = visual.Compositor;

            var pathSize = new Graphics.Rect(0, 0, width, height);
            var clipPath = clipGeometry.PathForBounds(pathSize);
            var device   = CanvasDevice.GetSharedDevice();
            var geometry = clipPath.AsPath(device);

            var path          = new CompositionPath(geometry);
            var pathGeometry  = compositor.CreatePathGeometry(path);
            var geometricClip = compositor.CreateGeometricClip(pathGeometry);

            visual.Clip = geometricClip;
        }
コード例 #7
0
        /* This function occurs each time an element is made ready for use.
         * This is necessary for virtualization. */
        private void OnElementPrepared(Microsoft.UI.Xaml.Controls.ItemsRepeater sender, Microsoft.UI.Xaml.Controls.ItemsRepeaterElementPreparedEventArgs args)
        {
            var item             = ElementCompositionPreview.GetElementVisual(args.Element);
            var svVisual         = ElementCompositionPreview.GetElementVisual(Animated_ScrollViewer);
            var scrollProperties = ElementCompositionPreview.GetScrollViewerManipulationPropertySet(Animated_ScrollViewer);

            var scaleExpresion = scrollProperties.Compositor.CreateExpressionAnimation();

            scaleExpresion.SetReferenceParameter("svVisual", svVisual);
            scaleExpresion.SetReferenceParameter("scrollProperties", scrollProperties);
            scaleExpresion.SetReferenceParameter("item", item);

            // Scale the item based on the distance of the item relative to the center of the viewport.
            scaleExpresion.Expression = "1 - abs((svVisual.Size.Y/2 - scrollProperties.Translation.Y) - (item.Offset.Y + item.Size.Y/2))*(.25/(svVisual.Size.Y/2))";

            // Animate the item to change size based on distance from center of viewpoint
            item.StartAnimation("Scale.X", scaleExpresion);
            item.StartAnimation("Scale.Y", scaleExpresion);
            var centerPointExpression = scrollProperties.Compositor.CreateExpressionAnimation();

            centerPointExpression.SetReferenceParameter("item", item);
            centerPointExpression.Expression = "Vector3(item.Size.X/2, item.Size.Y/2, 0)";
            item.StartAnimation("CenterPoint", centerPointExpression);
        }
コード例 #8
0
        public BackDrop()
        {
            m_rootVisual = ElementCompositionPreview.GetElementVisual(this as UIElement);
            Compositor   = m_rootVisual.Compositor;

            m_blurVisual = Compositor.CreateSpriteVisual();

#if SDKVERSION_14393
            CompositionEffectBrush brush = BuildBlurBrush();
            brush.SetSourceParameter("source", m_compositor.CreateBackdropBrush());
            m_blurBrush        = brush;
            m_blurVisual.Brush = m_blurBrush;

            BlurAmount = 9;
            TintColor  = Colors.Transparent;
#else
            m_blurBrush        = Compositor.CreateColorBrush(Colors.White);
            m_blurVisual.Brush = m_blurBrush;
#endif
            ElementCompositionPreview.SetElementChildVisual(this as UIElement, m_blurVisual);

            this.Loading  += OnLoading;
            this.Unloaded += OnUnloaded;
        }
コード例 #9
0
        public void CreateGaussBlurEffect()
        {
            var compositor       = ElementCompositionPreview.GetElementVisual(this).Compositor;
            var backgroundVisual = ElementCompositionPreview.GetElementVisual(imgBackground);

            var blurEffect = new Microsoft.Graphics.Canvas.Effects.GaussianBlurEffect()
            {
                Name       = "Blur",
                Source     = new Windows.UI.Composition.CompositionEffectSourceParameter("blur"),
                BlurAmount = 10
            };

            var backdropBrush     = compositor.CreateBackdropBrush();
            var blurEffectFactory = compositor.CreateEffectFactory(blurEffect, new string[] { "Blur.BlurAmount" });
            var blurBrush         = blurEffectFactory.CreateBrush();

            blurBrush.SetSourceParameter("blur", backdropBrush);

            var blurAnimation = compositor.CreateExpressionAnimation("");
            var blurProgress  = "Clamp(visual.Translation.Y/-450,0,1)";

            blurAnimation.Expression = ("Lerp(0,10," + blurProgress + ")");
            blurAnimation.SetReferenceParameter("visual", backgroundVisual);
            blurBrush.Properties.StartAnimation("Blur.BlurAmount", blurAnimation);

            var spriteVisual = compositor.CreateSpriteVisual();

            spriteVisual.Brush = blurBrush;

            ElementCompositionPreview.SetElementChildVisual(imgBackground, spriteVisual);

            var sizeAnimation = compositor.CreateExpressionAnimation("visual.Size");

            sizeAnimation.SetReferenceParameter("visual", backgroundVisual);
            spriteVisual.StartAnimation("Size", sizeAnimation);
        }
コード例 #10
0
        public AnimationDrawer()
        {
            InitializeComponent();

            _handler = new AnimatedRepeaterHandler <Animation>(Repeater, ScrollingHost);
            _handler.DownloadFile = DownloadFile;

            _throttler          = new DispatcherTimer();
            _throttler.Interval = TimeSpan.FromMilliseconds(Constants.AnimatedThrottle);
            _throttler.Tick    += (s, args) =>
            {
                _throttler.Stop();
                _handler.LoadVisibleItems(false);
            };

            ElementCompositionPreview.GetElementVisual(this).Clip = Window.Current.Compositor.CreateInsetClip();

            var shadow = DropShadowEx.Attach(Separator, 20, 0.25f);

            Separator.SizeChanged += (s, args) =>
            {
                shadow.Size = args.NewSize.ToVector2();
            };

            var observable = Observable.FromEventPattern <TextChangedEventArgs>(FieldAnimations, "TextChanged");
            var throttled  = observable.Throttle(TimeSpan.FromMilliseconds(Constants.TypingTimeout)).ObserveOnDispatcher().Subscribe(x =>
            {
                ViewModel.FindAnimations(FieldAnimations.Text);
                //var items = ViewModel.Stickers.SearchStickers;
                //if (items != null && string.Equals(FieldStickers.Text, items.Query))
                //{
                //    await items.LoadMoreItemsAsync(1);
                //    await items.LoadMoreItemsAsync(2);
                //}
            });
        }
コード例 #11
0
        private void InitializeComposition()
        {
            this.compositor  = ElementCompositionPreview.GetElementVisual(this).Compositor;
            this.thumbVisual = ElementCompositionPreview.GetElementVisual(thumb);
            this.trackVisual = ElementCompositionPreview.GetElementVisual(trackCanvas);

            propSet = this.compositor.CreatePropertySet();
            trackCanvas.PointerWheelChanged += new PointerEventHandler(PointerWheel_Changed);
            trackCanvas.PointerMoved        += new PointerEventHandler(MousePointer_Moved);
            trackCanvas.PointerReleased     += new PointerEventHandler(MousePointer_Released);

            // These pointer events are needed if want to click-to-seek. Weird eventing issues between when these get called and when need to call OnDragStart() and OnDragStop() methods
            // trackCanvas.PointerPressed += new PointerEventHandler(MousePointer_Pressed);
            // thumb.PointerPressed += new PointerEventHandler(MousePointer_ThumbPressed);
            this.interactionSource = VisualInteractionSource.Create(this.trackVisual);
            this.interactionSource.PositionXSourceMode = InteractionSourceMode.EnabledWithInertia;
            this.tracker = InteractionTracker.CreateWithOwner(this.compositor, this);
            this.tracker.InteractionSources.Add(this.interactionSource);

            // This is the Expression that we will use to drive the position of the Thumb Scrubber
            // Idea is that we will then update the position of InteractionTracker to move thes scrubber around - this is done via the Pointer Events tied to the TrackCanvas object
            // Note: this is using ExpressionBuilder
            this.thumbExpressionAnimation = -tracker.GetReference().Position.X;
        }
コード例 #12
0
        private void EnsureImplicitAnimations()
        {
            if (_implicitAnimations == null)
            {
                var compositor = ElementCompositionPreview.GetElementVisual(this).Compositor;

                var offsetAnimation = compositor.CreateVector3KeyFrameAnimation();
                offsetAnimation.Target = nameof(Visual.Offset);
                offsetAnimation.InsertExpressionKeyFrame(1.0f, "this.FinalValue");
                offsetAnimation.Duration = TimeSpan.FromMilliseconds(400);

                var sizeAnimation = compositor.CreateVector2KeyFrameAnimation();
                sizeAnimation.Target = nameof(Visual.Size);
                sizeAnimation.InsertExpressionKeyFrame(1.0f, "this.FinalValue");
                sizeAnimation.Duration = TimeSpan.FromMilliseconds(400);

                var animationGroup = compositor.CreateAnimationGroup();
                animationGroup.Add(offsetAnimation);
                animationGroup.Add(sizeAnimation);

                _implicitAnimations = compositor.CreateImplicitAnimationCollection();
                _implicitAnimations[nameof(Visual.Offset)] = animationGroup;
            }
        }
コード例 #13
0
        protected override void OnApplyTemplate()
        {
            _label1 = _label = GetTemplateChild("ContentPresenter1") as FrameworkElement;
            _label2 = GetTemplateChild("ContentPresenter2") as FrameworkElement;

            _visual1 = _visual = ElementCompositionPreview.GetElementVisual(_label1);
            _visual2 = ElementCompositionPreview.GetElementVisual(_label2);

            if (_label2 is TextBlock text2)
            {
                text2.Text = string.Empty;
            }
            else if (_label2 is ContentPresenter presenter2)
            {
                presenter2.Content = new object();
            }

            _visual2.Opacity     = 0;
            _visual2.Scale       = new Vector3();
            _visual2.CenterPoint = new Vector3(10);

            if (_label1 is TextBlock text1)
            {
                text1.Text = IsChecked == true ? CheckedGlyph : Glyph ?? string.Empty;
            }
            else if (_label1 is ContentPresenter presenter1)
            {
                presenter1.Content = IsChecked == true ? CheckedContent : Content ?? new object();
            }

            _visual1.Opacity     = 1;
            _visual1.Scale       = new Vector3(1);
            _visual1.CenterPoint = new Vector3(10);

            base.OnApplyTemplate();
        }
コード例 #14
0
        private void MainContentGrid_Loaded(object sender, RoutedEventArgs e)
        {
            var    s      = sender as UIElement;
            Visual visual = ElementCompositionPreview.GetElementVisual(s);
            float  width  = (float)s.RenderSize.Width;
            float  height = (float)s.RenderSize.Height;

            visual.Opacity     = 0;
            visual.CenterPoint = new System.Numerics.Vector3(width / 2, height / 2, 0);
            visual.Scale       = new System.Numerics.Vector3(.5f, .5f, 0);

            var fadeAnimation = _compositor.CreateScalarKeyFrameAnimation();

            fadeAnimation.Duration = TimeSpan.FromMilliseconds(700);
            fadeAnimation.InsertKeyFrame(1f, 1f);

            var scaleAnimation = _compositor.CreateVector3KeyFrameAnimation();

            scaleAnimation.Duration = TimeSpan.FromMilliseconds(500);
            scaleAnimation.InsertKeyFrame(1f, new System.Numerics.Vector3(1, 1, 0));

            visual.StartAnimation("Opacity", fadeAnimation);
            visual.StartAnimation("Scale", scaleAnimation);
        }
コード例 #15
0
        private void UpdateSeeAlsoPanelVerticalTranslationAnimation()
        {
            var isEnabled = LayoutVisualStates.CurrentState == LargeLayout;

            ElementCompositionPreview.SetIsTranslationEnabled(seeAlsoPanel, true);

            var targetPanelVisual = ElementCompositionPreview.GetElementVisual(seeAlsoPanel);

            targetPanelVisual.Properties.InsertVector3("Translation", Vector3.Zero);

            if (isEnabled)
            {
                var scrollProperties = ElementCompositionPreview.GetScrollViewerManipulationPropertySet(svPanel);

                var expression = _compositor.CreateExpressionAnimation("ScrollManipulation.Translation.Y * -1");
                expression.SetReferenceParameter("ScrollManipulation", scrollProperties);
                expression.Target = "Translation.Y";
                targetPanelVisual.StartAnimation(expression.Target, expression);
            }
            else
            {
                targetPanelVisual.StopAnimation("Translation.Y");
            }
        }
コード例 #16
0
        private void InitComposition()
        {
            _compositor = ElementCompositionPreview.GetElementVisual(this).Compositor;

            _visual             = _compositor.CreateSpriteVisual();
            _visual.Size        = new Vector2(75.0f);
            _visual.Offset      = new Vector3(50.0f, 50.0f, 0.0f);
            _visual.CenterPoint = new Vector3(_visual.Size / 2.0f, 0.0f);
            _visual.Brush       = _compositor.CreateColorBrush(Colors.Red);

            ElementCompositionPreview.SetElementChildVisual(this, _visual);

            var offsetAnimation = _compositor.CreateVector3KeyFrameAnimation();

            offsetAnimation.Target = nameof(Visual.Offset);
            offsetAnimation.InsertExpressionKeyFrame(1.0f, "this.FinalValue");
            offsetAnimation.Duration = TimeSpan.FromMilliseconds(1500);

            var rotationAnimation = _compositor.CreateScalarKeyFrameAnimation();

            rotationAnimation.Target = nameof(Visual.RotationAngleInDegrees);
            rotationAnimation.InsertKeyFrame(0.0f, 0.0f);
            rotationAnimation.InsertKeyFrame(1.0f, 360.0f);
            rotationAnimation.Duration = TimeSpan.FromMilliseconds(1500);

            var animationGroup = _compositor.CreateAnimationGroup();

            animationGroup.Add(offsetAnimation);
            animationGroup.Add(rotationAnimation);

            var implicitAnimations = _compositor.CreateImplicitAnimationCollection();

            implicitAnimations[nameof(Visual.Offset)] = animationGroup;

            _visual.ImplicitAnimations = implicitAnimations;
        }
コード例 #17
0
        public void CreateAnimation()
        {
            _compositor = ElementCompositionPreview.GetElementVisual(this).Compositor;
            var visual1 = _compositor.CreateSpriteVisual();
            var visual2 = _compositor.CreateSpriteVisual();

            visual1.Brush = _compositor.CreateColorBrush(Colors.Red);
            visual1.Size  = new Vector2(80, 80);
            visual2.Brush = _compositor.CreateColorBrush(Colors.Blue);
            visual2.Size  = new Vector2(80, 80);
            var animation1 = _compositor.CreateScalarKeyFrameAnimation();

            animation1.InsertKeyFrame(0.0f, 0);
            animation1.InsertKeyFrame(1.0f, 360f);
            animation1.Duration          = TimeSpan.FromSeconds(5);
            animation1.IterationBehavior = AnimationIterationBehavior.Forever;
            var animation2 = _compositor.CreateExpressionAnimation("-visual1.RotationAngleInDegrees");

            animation2.SetReferenceParameter("visual1", visual1);
            ElementCompositionPreview.SetElementChildVisual(canvas1, visual1);
            ElementCompositionPreview.SetElementChildVisual(canvas2, visual2);
            visual1.StartAnimation("RotationAngleInDegrees", animation1);
            visual2.StartAnimation("RotationAngleInDegrees", animation2);
        }
コード例 #18
0
        private void AlbumList_Loaded(object sender, RoutedEventArgs e)
        {
            var ani = ConnectedAnimationService.GetForCurrentView().GetAnimation(Consts.ArtistPageInAnimation);

            if (ani != null)
            {
                ani.TryStart(Title, new UIElement[] { HeaderBG, Details });
            }

            var scrollviewer = AlbumList.GetScrollViewer();

            _scrollerPropertySet = ElementCompositionPreview.GetScrollViewerManipulationPropertySet(scrollviewer);
            _compositor          = _scrollerPropertySet.Compositor;

            _props = _compositor.CreatePropertySet();
            _props.InsertScalar("progress", 0);
            _props.InsertScalar("clampSize", (float)Title.ActualHeight + 64);
            _props.InsertScalar("scaleFactor", 0.5f);

            // Get references to our property sets for use with ExpressionNodes
            var scrollingProperties = _scrollerPropertySet.GetSpecializedReference <ManipulationPropertySetReferenceNode>();
            var props           = _props.GetReference();
            var progressNode    = props.GetScalarProperty("progress");
            var clampSizeNode   = props.GetScalarProperty("clampSize");
            var scaleFactorNode = props.GetScalarProperty("scaleFactor");

            // Create and start an ExpressionAnimation to track scroll progress over the desired distance
            ExpressionNode progressAnimation = EF.Clamp(-scrollingProperties.Translation.Y / ((float)Header.Height - clampSizeNode), 0, 1);

            _props.StartAnimation("progress", progressAnimation);

            // Get the backing visual for the header so that its properties can be animated
            Visual headerVisual = ElementCompositionPreview.GetElementVisual(Header);

            // Create and start an ExpressionAnimation to clamp the header's offset to keep it onscreen
            ExpressionNode headerTranslationAnimation = EF.Conditional(progressNode < 1, scrollingProperties.Translation.Y, -(float)Header.Height + (float)Title.ActualHeight + 64);

            headerVisual.StartAnimation("Offset.Y", headerTranslationAnimation);

            //// Create and start an ExpressionAnimation to scale the header during overpan
            //ExpressionNode headerScaleAnimation = EF.Lerp(1, 1.25f, EF.Clamp(scrollingProperties.Translation.Y / 50, 0, 1));
            //headerVisual.StartAnimation("Scale.X", headerScaleAnimation);
            //headerVisual.StartAnimation("Scale.Y", headerScaleAnimation);

            ////Set the header's CenterPoint to ensure the overpan scale looks as desired
            //headerVisual.CenterPoint = new Vector3((float)(Header.ActualWidth / 2), (float)Header.ActualHeight, 0);

            var titleVisual       = ElementCompositionPreview.GetElementVisual(Title);
            var titleshrinkVisual = ElementCompositionPreview.GetElementVisual(TitleShrink);
            var fixAnimation      = EF.Conditional(progressNode < 1, -scrollingProperties.Translation.Y, (float)Header.Height - ((float)Title.ActualHeight + 64));

            titleVisual.StartAnimation("Offset.Y", fixAnimation);
            titleshrinkVisual.StartAnimation("Offset.Y", fixAnimation);
            var detailsVisual    = ElementCompositionPreview.GetElementVisual(Details);
            var opacityAnimation = EF.Clamp(1 - (progressNode * 8), 0, 1);

            detailsVisual.StartAnimation("Opacity", opacityAnimation);

            var headerbgVisual         = ElementCompositionPreview.GetElementVisual(HeaderBG);
            var headerbgOverlayVisual  = ElementCompositionPreview.GetElementVisual(HeaderBGOverlay);
            var bgBlurVisual           = ElementCompositionPreview.GetElementVisual(BGBlur);
            var bgOpacityAnimation     = EF.Clamp(1 - progressNode, 0, 1);
            var bgblurOpacityAnimation = EF.Clamp(progressNode, 0, 1);

            titleshrinkVisual.StartAnimation("Opacity", bgblurOpacityAnimation);
            titleVisual.StartAnimation("Opacity", bgOpacityAnimation);
            headerbgVisual.StartAnimation("Opacity", bgOpacityAnimation);
            headerbgOverlayVisual.StartAnimation("Opacity", bgOpacityAnimation);
            bgBlurVisual.StartAnimation("Opacity", bgblurOpacityAnimation);
        }
コード例 #19
0
        /// <summary>
        /// Initialize all Composition related stuff here (Compositor, Animations etc)
        /// </summary>
        private void InitializeComposition()
        {
            var rootVisual = ElementCompositionPreview.GetElementVisual(this);

            // Compositor
            _compositor = rootVisual.Compositor;
            // Composition Generator
            _generator = CompositionGeneratorFactory.GetCompositionGenerator(_compositor);

            // Final Value Expressions
            var vector3Expr = _compositor.CreateFinalValueExpression <Vector3>();
            var scalarExpr  = _compositor.CreateFinalValueExpression <float>();

            // Opacity Animation
            var opacityAnimation = _compositor.CreateKeyFrameAnimation <float>()
                                   .HavingDuration(DefaultOpacityAnimationDuration)
                                   .ForTarget(() => rootVisual.Opacity);

            opacityAnimation.InsertExpressionKeyFrame(1f, scalarExpr);

            // Scale Animation
            var scaleAnimation = _compositor.CreateKeyFrameAnimation <Vector3>()
                                 .HavingDuration(DefaultScaleAnimationDuration)
                                 .ForTarget(() => rootVisual.Scale);

            scaleAnimation.InsertExpressionKeyFrame(1f, vector3Expr);

            // ImplicitAnimation
            _implicitAnimationCollection            = _compositor.CreateImplicitAnimationCollection();
            _implicitAnimationCollection["Opacity"] = opacityAnimation.Animation;
            _implicitAnimationCollection["Scale"]   = scaleAnimation.Animation;

            // Expand Animations
            _expandLeftInset = _compositor.CreateKeyFrameAnimation <float>()
                               .HavingDuration(InsetAnimationDuration)
                               .DelayBy(InsetAnimationDelayDuration);

            _expandLeftInset.InsertKeyFrame(1f, 0);

            _expandRightInset = _compositor.CreateKeyFrameAnimation <float>()
                                .HavingDuration(InsetAnimationDuration)
                                .DelayBy(InsetAnimationDelayDuration);

            _expandInsetClip = _compositor.CreateKeyFrameAnimation <float>()
                               .HavingDuration(InsetClipAnimationDuration);

            _expandInsetClip.InsertKeyFrame(1f, 0);

            // Collapse Animations
            _collapseLeftInset = _compositor.CreateKeyFrameAnimation <float>()
                                 .HavingDuration(InsetAnimationDuration);

            _collapseRightInset = _compositor.CreateKeyFrameAnimation <float>()
                                  .HavingDuration(InsetAnimationDuration);

            _collapseInsetClip = _compositor.CreateKeyFrameAnimation <float>()
                                 .HavingDuration(InsetClipAnimationDuration);

            // Root Container
            _rootContainer = _compositor.CreateContainerVisual();

            // Background Layer
            _bgLayer             = _compositor.CreateLayerVisual();
            _bgLayer.Size        = _rootContainer.Size;
            _bgLayer.CenterPoint = new Vector3(_bgLayer.Size * 0.5f, 0);

            // Top Layer
            _topLayer      = _compositor.CreateLayerVisual();
            _topLayer.Size = _rootContainer.Size;

            _rootContainer.Children.InsertAtBottom(_bgLayer);
            _rootContainer.Children.InsertAtTop(_topLayer);

            // Add the rootContainer to the visual tree
            ElementCompositionPreview.SetElementChildVisual(this, _rootContainer);
        }
コード例 #20
0
        private void BackgroundImage_ImageOpened(object sender, RoutedEventArgs e)
        {
            var gfxEffect = new BlendEffect
            {
                Mode       = BlendEffectMode.Multiply,
                Background = new ColorSourceEffect
                {
                    Name  = "Darken",
                    Color = Color.FromArgb(102, 0, 0, 0),
                },
                Foreground = new GaussianBlurEffect()
                {
                    Name         = "Blur",
                    BlurAmount   = 20.0f,
                    BorderMode   = EffectBorderMode.Hard,
                    Optimization = EffectOptimization.Speed,
                    Source       = new CompositionEffectSourceParameter("ImageSource")
                }
            };


            Visual     _backgroundVisual     = ElementCompositionPreview.GetElementVisual(BackgroundGrid);
            Compositor _backgroundCompositor = _backgroundVisual.Compositor;

            var effectBrush = _backgroundCompositor.CreateEffectFactory(gfxEffect).CreateBrush();

            var destinationBrush = _backgroundCompositor.CreateBackdropBrush();

            effectBrush.SetSourceParameter("ImageSource", destinationBrush);

            //Generate a UIElement visual.
            var blurSprite = _backgroundCompositor.CreateSpriteVisual();

            blurSprite.Size  = new Vector2((float)BackgroundGrid.ActualWidth, (float)BackgroundGrid.ActualHeight);
            blurSprite.Brush = effectBrush;
            //Then "inject" it to the XAML.
            ElementCompositionPreview.SetElementChildVisual(BackgroundGrid, blurSprite);

            //create animation for opacity of the image from 0 -> 1
            DoubleAnimation animation = new DoubleAnimation()
            {
                From           = 0,
                To             = 1,
                EasingFunction = new CircleEase()
                {
                    EasingMode = EasingMode.EaseOut
                },
                Duration = new Duration(TimeSpan.FromSeconds(0.3))
            };

            animation.EnableDependentAnimation = true;

            //create storyboard.
            Storyboard loadImageOpacity = new Storyboard();

            loadImageOpacity.Children.Add(animation);

            //start the storyboard
            Storyboard.SetTarget(animation, BackgroundImage);
            Storyboard.SetTargetProperty(animation, "Opacity");
            loadImageOpacity.Begin();
            gfxEffect.Dispose();
        }
コード例 #21
0
        private void MainGridLoaded(object sender, RoutedEventArgs e)
        {
            m_compositor = ElementCompositionPreview.GetElementVisual(MainGrid).Compositor;
            m_root       = m_compositor.CreateContainerVisual();
            ElementCompositionPreview.SetElementChildVisual(MainGrid, m_root);

            Size imageSize;

            m_noEffectBrush = CreateBrushFromAsset(
                "Bruno'sFamily2015 (13)-X2.jpg",
                out imageSize);
            m_imageAspectRatio = (imageSize.Width == 0 && imageSize.Height == 0) ? 1 : imageSize.Width / imageSize.Height;

            m_sprite = m_compositor.CreateSpriteVisual();
            ResizeImage(new Size(MainGrid.ActualWidth, MainGrid.ActualHeight));
            m_root.Children.InsertAtTop(m_sprite);

            // Image with alpha channel as an mask.
            var alphaMaskEffectDesc = new CompositeEffect
            {
                Mode    = CanvasComposite.DestinationIn,
                Sources =
                {
                    new CompositionEffectSourceParameter("Image"),
                    new Transform2DEffect
                    {
                        Name   = "MaskTransform",
                        Source = new CompositionEffectSourceParameter("Mask")
                    }
                }
            };

            m_alphaMaskEffectBrush = m_compositor.CreateEffectFactory(
                alphaMaskEffectDesc,
                new[] { "MaskTransform.TransformMatrix" }
                ).CreateBrush();
            m_alphaMaskEffectBrush.SetSourceParameter(
                "Image",
                m_noEffectBrush);
            m_alphaMaskEffectBrush.SetSourceParameter(
                "Mask",
                CreateBrushFromAsset("CircleMask.png"));

            // Arithmetic operations between two images.
            var arithmeticEffectDesc = new ArithmeticCompositeEffect
            {
                Name        = "effect",
                ClampOutput = false,
                Source1     = new CompositionEffectSourceParameter("Source1"),
                Source2     = new CompositionEffectSourceParameter("Source2")
            };

            m_arithmeticEffectBrush = m_compositor.CreateEffectFactory(
                arithmeticEffectDesc,
                new[]
            {
                "effect.MultiplyAmount",
                "effect.Source1Amount",
                "effect.Source2Amount",
                "effect.Offset"
            }
                ).CreateBrush();
            m_arithmeticEffectBrush.SetSourceParameter(
                "Source1",
                m_noEffectBrush);
            m_arithmeticEffectBrush.SetSourceParameter(
                "Source2",
                CreateBrushFromAsset("_P2A8041.jpg"));

            // Creates a blend effect that combines two images.
            var foregroundBrush = CreateBrushFromAsset("Checkerboard_100x100.png");

            m_blendEffectBrushes = new CompositionEffectBrush[m_supportedBlendModes.Length];
            for (int i = 0; i < m_supportedBlendModes.Length; i++)
            {
                var blendEffectDesc = new BlendEffect
                {
                    Mode       = m_supportedBlendModes[i],
                    Background = new CompositionEffectSourceParameter("Background"),
                    Foreground = new CompositionEffectSourceParameter("Foreground")
                };
                m_blendEffectBrushes[i] = m_compositor.CreateEffectFactory(
                    blendEffectDesc
                    ).CreateBrush();
                m_blendEffectBrushes[i].SetSourceParameter(
                    "Background",
                    m_noEffectBrush);
                m_blendEffectBrushes[i].SetSourceParameter(
                    "Foreground",
                    foregroundBrush);
            }

            // Generates an image containing a solid color.
            var colorSourceEffectDesc = new ColorSourceEffect // FloodEffect
            {
                Name = "effect"
            };

            m_colorSourceEffectBrush = m_compositor.CreateEffectFactory(
                colorSourceEffectDesc,
                new[] { "effect.Color" }
                ).CreateBrush();

            // Changes the contrast of an image.
            var contrastEffectDesc = new ContrastEffect
            {
                Name   = "effect",
                Source = new CompositionEffectSourceParameter("Image")
            };

            m_contrastEffectBrush = m_compositor.CreateEffectFactory(
                contrastEffectDesc,
                new[] { "effect.Contrast" }
                ).CreateBrush();
            m_contrastEffectBrush.SetSourceParameter(
                "Image",
                m_noEffectBrush);

            // Changes the exposure of an image.
            var exposureEffectDesc = new ExposureEffect
            {
                Name   = "effect",
                Source = new CompositionEffectSourceParameter("Image")
            };

            m_exposureEffectBrush = m_compositor.CreateEffectFactory(
                exposureEffectDesc,
                new[] { "effect.Exposure" }
                ).CreateBrush();
            m_exposureEffectBrush.SetSourceParameter(
                "Image",
                m_noEffectBrush);

            // Alters the colors of an image by applying a per-channel gamma transfer function.
            var gammaTransferEffectDesc = new GammaTransferEffect
            {
                Name         = "effect",
                RedDisable   = false,
                GreenDisable = false,
                BlueDisable  = false,
                AlphaDisable = false,
                Source       = new CompositionEffectSourceParameter("Image")
            };

            m_gammaTransferEffectBrush = m_compositor.CreateEffectFactory(
                gammaTransferEffectDesc,
                new[]
            {
                "effect.RedAmplitude",
                "effect.RedExponent",
                "effect.RedOffset",
                "effect.GreenAmplitude",
                "effect.GreenExponent",
                "effect.GreenOffset",
                "effect.BlueAmplitude",
                "effect.BlueExponent",
                "effect.BlueOffset"
            }
                ).CreateBrush();
            m_gammaTransferEffectBrush.SetSourceParameter(
                "Image",
                m_noEffectBrush);

            // Converts an image to monochromatic gray.
            var grayscaleEffectDesc = new GrayscaleEffect
            {
                Name   = "effect",
                Source = new CompositionEffectSourceParameter("Image")
            };

            m_grayscaleEffectBrush = m_compositor.CreateEffectFactory(
                grayscaleEffectDesc
                ).CreateBrush();
            m_grayscaleEffectBrush.SetSourceParameter(
                "Image",
                m_noEffectBrush);

            // Alters the color of an image by rotating its hue values.
            var hueRotationEffectDesc = new HueRotationEffect
            {
                Name   = "effect",
                Source = new CompositionEffectSourceParameter("Image")
            };

            m_hueRotationEffectBrush = m_compositor.CreateEffectFactory(
                hueRotationEffectDesc,
                new[] { "effect.Angle" }
                ).CreateBrush();
            m_hueRotationEffectBrush.SetSourceParameter(
                "Image",
                m_noEffectBrush);

            // Inverts the colors of an image.
            var invertEffectDesc = new InvertEffect
            {
                Name   = "effect",
                Source = new CompositionEffectSourceParameter("Image")
            };

            m_invertEffectBrush = m_compositor.CreateEffectFactory(
                invertEffectDesc
                ).CreateBrush();
            m_invertEffectBrush.SetSourceParameter(
                "Image",
                m_noEffectBrush);

            // Alters the saturation of an image.
            var saturationEffectDesc = new SaturationEffect
            {
                Name   = "effect",
                Source = new CompositionEffectSourceParameter("Image")
            };

            m_saturateEffectBrush = m_compositor.CreateEffectFactory(
                saturationEffectDesc,
                new[] { "effect.Saturation" }
                ).CreateBrush();
            m_saturateEffectBrush.SetSourceParameter(
                "Image",
                m_noEffectBrush);

            // Converts an image to sepia tones.
            var supportedAlphaModes = new[]
            {
                CanvasAlphaMode.Premultiplied,
                CanvasAlphaMode.Straight
            };

            m_sepiaEffectBrushes = new CompositionEffectBrush[supportedAlphaModes.Length];
            for (int i = 0; i < supportedAlphaModes.Length; i++)
            {
                var sepiaEffectDesc = new SepiaEffect
                {
                    Name      = "effect",
                    AlphaMode = supportedAlphaModes[i],
                    Source    = new CompositionEffectSourceParameter("Image")
                };
                m_sepiaEffectBrushes[i] = m_compositor.CreateEffectFactory(
                    sepiaEffectDesc,
                    new[] { "effect.Intensity" }
                    ).CreateBrush();
                m_sepiaEffectBrushes[i].SetSourceParameter(
                    "Image",
                    m_noEffectBrush);
            }

            // Adjusts the temperature and/or tint of an image.
            var temperatureAndTintEffectDesc = new TemperatureAndTintEffect
            {
                Name   = "effect",
                Source = new CompositionEffectSourceParameter("Image")
            };

            m_temperatureAndTintEffectBrush = m_compositor.CreateEffectFactory(
                temperatureAndTintEffectDesc,
                new[]
            {
                "effect.Temperature",
                "effect.Tint"
            }
                ).CreateBrush();
            m_temperatureAndTintEffectBrush.SetSourceParameter(
                "Image",
                m_noEffectBrush);

            // Applies a 2D affine transform matrix to an image.
            var transform2DEffectDesc = new Transform2DEffect
            {
                TransformMatrix = new Matrix3x2(
                    -1, 0,
                    0, 1,
                    m_sprite.Size.X, 0),
                Source = new CompositionEffectSourceParameter("Image")
            };

            m_transform2DEffectBrush = m_compositor.CreateEffectFactory(
                transform2DEffectDesc
                ).CreateBrush();
            m_transform2DEffectBrush.SetSourceParameter(
                "Image",
                m_noEffectBrush);

            // For simplying UI states switch, put effect parameter grids in an array
            m_effectParamsGrids = new Grid[(int)EffectType.NumEffectTypes];
            m_effectParamsGrids[(int)EffectType.NoEffect]           = null;
            m_effectParamsGrids[(int)EffectType.AlphaMask]          = AlphaMaskParams;
            m_effectParamsGrids[(int)EffectType.Arithmetic]         = ArithmeticParams;
            m_effectParamsGrids[(int)EffectType.Blend]              = BlendParams;
            m_effectParamsGrids[(int)EffectType.ColorSource]        = ColorSourceParams;
            m_effectParamsGrids[(int)EffectType.Contrast]           = ContrastParams;
            m_effectParamsGrids[(int)EffectType.Exposure]           = ExposureParams;
            m_effectParamsGrids[(int)EffectType.GammaTransfer]      = GammaTransferParams;
            m_effectParamsGrids[(int)EffectType.Grayscale]          = null;
            m_effectParamsGrids[(int)EffectType.HueRotation]        = HueRotationParams;
            m_effectParamsGrids[(int)EffectType.Invert]             = null;
            m_effectParamsGrids[(int)EffectType.Saturation]         = SaturationParams;
            m_effectParamsGrids[(int)EffectType.Sepia]              = SepiaParams;
            m_effectParamsGrids[(int)EffectType.TemperatureAndTint] = TemperatureAndTintParams;
            m_effectParamsGrids[(int)EffectType.Transform2D]        = null;

            // Same as grids
            m_effectBrushes = new CompositionBrush[(int)EffectType.NumEffectTypes];
            m_effectBrushes[(int)EffectType.NoEffect]           = m_noEffectBrush;
            m_effectBrushes[(int)EffectType.AlphaMask]          = m_alphaMaskEffectBrush;
            m_effectBrushes[(int)EffectType.Arithmetic]         = m_arithmeticEffectBrush;
            m_effectBrushes[(int)EffectType.Blend]              = m_blendEffectBrushes[m_activeBlendMode];
            m_effectBrushes[(int)EffectType.ColorSource]        = m_colorSourceEffectBrush;
            m_effectBrushes[(int)EffectType.Contrast]           = m_contrastEffectBrush;
            m_effectBrushes[(int)EffectType.Exposure]           = m_exposureEffectBrush;
            m_effectBrushes[(int)EffectType.GammaTransfer]      = m_gammaTransferEffectBrush;
            m_effectBrushes[(int)EffectType.Grayscale]          = m_grayscaleEffectBrush;
            m_effectBrushes[(int)EffectType.HueRotation]        = m_hueRotationEffectBrush;
            m_effectBrushes[(int)EffectType.Invert]             = m_invertEffectBrush;
            m_effectBrushes[(int)EffectType.Saturation]         = m_saturateEffectBrush;
            m_effectBrushes[(int)EffectType.Sepia]              = m_sepiaEffectBrushes[m_activeSepiaAlphaMode];
            m_effectBrushes[(int)EffectType.TemperatureAndTint] = m_temperatureAndTintEffectBrush;
            m_effectBrushes[(int)EffectType.Transform2D]        = m_transform2DEffectBrush;

            this.InitializeValues();
        }
コード例 #22
0
        private void Page_Loaded(object sender, RoutedEventArgs e)
        {
            ApplicationView.GetForCurrentView().TryResizeView(new Size(1792, 1008));
            _backgroundImageVisual = ElementCompositionPreview.GetElementVisual(BackgroundImage);
            _weatherLayerVisual    = ElementCompositionPreview.GetElementVisual(WeatherLayer);
            _todoLayerVisual       = ElementCompositionPreview.GetElementVisual(ToDoLayer);
            _calendarIconVisual    = ElementCompositionPreview.GetElementVisual(CalendarIcon);
            _backgroundVisual      = ElementCompositionPreview.GetElementVisual(Root);

            _compositor            = _backgroundImageVisual.Compositor;
            _backgroundVisual.Clip = _compositor.CreateInsetClip(0, 0, 0, 0);


            _backgroundImageVisual.Size = new Vector2((float)Root.ActualWidth, (float)Root.ActualHeight);


            _backgroundImageVisual.CenterPoint = new Vector3(
                (float)Root.ActualWidth / 2.0f,
                (float)Root.ActualHeight / 2.0f,
                0);

            _calendarIconVisual.CenterPoint = new Vector3(
                (float)CalendarIcon.ActualWidth / 2.0f,
                (float)CalendarIcon.ActualHeight / 2.0f,
                0);

            _weatherLayerVisual.CenterPoint = new Vector3(
                (float)WeatherLayer.ActualWidth / 2.0f,
                -(float)WeatherLayer.ActualHeight,
                0);

            _todoLayerVisual.CenterPoint = new Vector3(
                (float)ToDoLayer.ActualWidth / 2.0f,
                (float)ToDoLayer.ActualHeight / 2.0f,
                0);

            _backgroundVisual.Size = new Vector2((float)Root.ActualWidth, (float)Root.ActualHeight);

            _backgroundVisualDimmer       = _compositor.CreateSpriteVisual();
            _backgroundVisualDimmer.Brush = _compositor.CreateColorBrush(Windows.UI.Colors.Black);
            _backgroundVisualDimmer.Size  = _backgroundVisual.Size;

            ElementCompositionPreview.SetElementChildVisual(BackgroundImageOverlay, _backgroundVisualDimmer);


            //
            // Store the state 1 and 2 values.  We'll blend between them later.
            //

            _visualState1 = new VisualState
            {
                BackgroundBlurAmount   = 1.0f,
                BackgroundScale        = new Vector3(1.0f, 1.0f, 1.0f),
                CalendarIconOffset     = new Vector3(0, -50, 0),
                CalendarIconScale      = new Vector3(0.7f, 0.7f, 1.0f),
                ToDoLayerBlurAmount    = 0.3f,
                ToDoLayerOpacity       = 0.0f,
                ToDoLayerScale         = new Vector3(0.8f, 0.8f, 1.0f),
                WeatherLayerBlurAmount = 0.0f,
                WeatherLayerOpacity    = 3.0f,
                WeatherLayerScale      = new Vector3(1.0f),
            };

            _visualState2 = new VisualState
            {
                BackgroundBlurAmount   = 9.0f,
                BackgroundScale        = new Vector3(1.11f, 1.11f, 1.0f),
                CalendarIconOffset     = new Vector3(),
                CalendarIconScale      = new Vector3(1.0f),
                ToDoLayerBlurAmount    = 0.0f,
                ToDoLayerOpacity       = 1.0f,
                ToDoLayerScale         = new Vector3(1.0f),
                WeatherLayerBlurAmount = 0.3f,
                WeatherLayerOpacity    = 0.0f,
                WeatherLayerScale      = new Vector3(0.8f, 0.8f, 1.0f),
            };

            //
            // Store the interaction "progress" into a property set.
            // We'll reference it later in all of the expressions.
            //

            _propertySet = _compositor.CreatePropertySet();
            _propertySet.InsertScalar("progress", 0.0f);


            //
            // Create a "canned" key frame animation that we'll use to
            // play when the toggle button is pressed.
            //

            _cannedProgressAnimation          = _compositor.CreateVector3KeyFrameAnimation();
            _cannedProgressAnimation.Duration = TimeSpan.FromMilliseconds(1500);


            InitializeBlurVisuals();

            ConfigureInteractionTracker();

            ConfigureRestingPoints();

            ConfigureTransitionAnimations();

            TransitionToState1(false);
        }
コード例 #23
0
 public static Visual Visual(this UIElement element) =>
 ElementCompositionPreview.GetElementVisual(element);
コード例 #24
0
 public static Visual GetVisual(this UIElement element)
 {
     return(ElementCompositionPreview.GetElementVisual(element));
 }
コード例 #25
0
ファイル: UIElementExtensions.cs プロジェクト: jokm1/uno-2
        internal static void SetElevationInternal(this DependencyObject element, double elevation, Color shadowColor)
#endif
        {
#if __ANDROID__
            if (element is Android.Views.View view)
            {
                AndroidX.Core.View.ViewCompat.SetElevation(view, (float)Uno.UI.ViewHelper.LogicalToPhysicalPixels(elevation));
                if (Android.OS.Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.P)
                {
                    view.SetOutlineAmbientShadowColor(shadowColor);
                    view.SetOutlineSpotShadowColor(shadowColor);
                }
            }
#elif __IOS__ || __MACOS__
#if __MACOS__
            if (element is AppKit.NSView view)
#else
            if (element is UIKit.UIView view)
        #endif
            {
                if (elevation > 0)
                {
                    // Values for 1dp elevation according to https://material.io/guidelines/resources/shadows.html#shadows-illustrator
                    const float x    = 0.25f;
                    const float y    = 0.92f * 0.5f;                  // Looks more accurate than the recommended 0.92f.
                    const float blur = 0.5f;

        #if __MACOS__
                    view.WantsLayer = true;
                    view.Shadow ??= new AppKit.NSShadow();
        #endif
                    view.Layer.MasksToBounds = false;
                    view.Layer.ShadowOpacity = shadowColor.A / 255f;
        #if __MACOS__
                    view.Layer.ShadowColor = AppKit.NSColor.FromRgb(shadowColor.R, shadowColor.G, shadowColor.B).CGColor;
        #else
                    view.Layer.ShadowColor = UIKit.UIColor.FromRGB(shadowColor.R, shadowColor.G, shadowColor.B).CGColor;
        #endif
                    view.Layer.ShadowRadius = (nfloat)(blur * elevation);
                    view.Layer.ShadowOffset = new CoreGraphics.CGSize(x * elevation, y * elevation);
                    view.Layer.ShadowPath   = path;
                }
                else if (view.Layer != null)
                {
                    view.Layer.ShadowOpacity = 0;
                }
            }
#elif __WASM__
            if (element is UIElement uiElement)
            {
                if (elevation > 0)
                {
                    // Values for 1dp elevation according to https://material.io/guidelines/resources/shadows.html#shadows-illustrator
                    const double x    = 0.25d;
                    const double y    = 0.92f * 0.5f;                  // Looks more accurate than the recommended 0.92f.
                    const double blur = 0.5f;

                    var str = $"{(x * elevation).ToStringInvariant()}px {(y * elevation).ToStringInvariant()}px {(blur * elevation).ToStringInvariant()}px {shadowColor.ToCssString()}";
                    uiElement.SetStyle("box-shadow", str);
                }
                else
                {
                    uiElement.ResetStyle("box-shadow");
                }
            }
#elif NETFX_CORE
            if (element is UIElement uiElement)
            {
                var compositor   = ElementCompositionPreview.GetElementVisual(uiElement).Compositor;
                var spriteVisual = compositor.CreateSpriteVisual();

                var newSize = new Vector2(0, 0);
                if (uiElement is FrameworkElement contentFE)
                {
                    newSize = new Vector2((float)contentFE.ActualWidth, (float)contentFE.ActualHeight);
                }

                if (!(host is Canvas uiHost) || newSize == default)
                {
                    return;
                }

                spriteVisual.Size = newSize;
                if (elevation > 0)
                {
                    // Values for 1dp elevation according to https://material.io/guidelines/resources/shadows.html#shadows-illustrator
                    const float x    = 0.25f;
                    const float y    = 0.92f * 0.5f;                  // Looks more accurate than the recommended 0.92f.
                    const float blur = 0.5f;

                    var shadow = compositor.CreateDropShadow();
                    shadow.Offset     = new Vector3((float)elevation * x, (float)elevation * y, -(float)elevation);
                    shadow.BlurRadius = (float)(blur * elevation);

                    shadow.Mask = uiElement switch
                    {
                        // GetAlphaMask is only available for shapes, images, and textblocks
                        Shape shape => shape.GetAlphaMask(),
                        Image image => image.GetAlphaMask(),
                        TextBlock tb => tb.GetAlphaMask(),
                              _ => shadow.Mask
                    };

                    if (!cornerRadius.Equals(default))
コード例 #26
0
        private void SetupAnimatedValuesSpy()
        {
            string visualHorizontalTargetedPropertyName =
                PlatformConfiguration.IsOsVersionGreaterThan(OSVersion.Redstone2) ? "visual.Translation.X" : "visual.TransformMatrix._41";

            if (this.parallaxView1 != null && this.parallaxView1.Child is UIElement)
            {
                UIElement  ppChild       = this.parallaxView1.Child as UIElement;
                Visual     visualPPChild = ElementCompositionPreview.GetElementVisual(ppChild);
                Compositor compositor    = visualPPChild.Compositor;

                if (this.AnimatedValuesSpy == null)
                {
                    this.AnimatedValuesSpy = compositor.CreatePropertySet();
                }

                this.AnimatedValuesSpy.InsertScalar("HorizontalOffset1", 0.0f);

                this.HorizontalOffsetAnimation1 = compositor.CreateExpressionAnimation(visualHorizontalTargetedPropertyName);
                this.HorizontalOffsetAnimation1.SetReferenceParameter("visual", visualPPChild);
            }

            if (this.parallaxView2 != null && this.parallaxView2.Child is UIElement)
            {
                UIElement  ppChild       = this.parallaxView2.Child as UIElement;
                Visual     visualPPChild = ElementCompositionPreview.GetElementVisual(ppChild);
                Compositor compositor    = visualPPChild.Compositor;

                if (this.AnimatedValuesSpy == null)
                {
                    this.AnimatedValuesSpy = compositor.CreatePropertySet();
                }

                this.AnimatedValuesSpy.InsertScalar("HorizontalOffset2", 0.0f);

                this.HorizontalOffsetAnimation2 = compositor.CreateExpressionAnimation(visualHorizontalTargetedPropertyName);
                this.HorizontalOffsetAnimation2.SetReferenceParameter("visual", visualPPChild);
            }

            string visualVerticalTargetedPropertyName =
                PlatformConfiguration.IsOsVersionGreaterThan(OSVersion.Redstone2) ? "visual.Translation.Y" : "visual.TransformMatrix._42";

            if (this.parallaxView3 != null && this.parallaxView3.Child is UIElement)
            {
                UIElement  ppChild       = this.parallaxView3.Child as UIElement;
                Visual     visualPPChild = ElementCompositionPreview.GetElementVisual(ppChild);
                Compositor compositor    = visualPPChild.Compositor;

                if (this.AnimatedValuesSpy == null)
                {
                    this.AnimatedValuesSpy = compositor.CreatePropertySet();
                }

                this.AnimatedValuesSpy.InsertScalar("VerticalOffset1", 0.0f);

                this.VerticalOffsetAnimation1 = compositor.CreateExpressionAnimation(visualVerticalTargetedPropertyName);
                this.VerticalOffsetAnimation1.SetReferenceParameter("visual", visualPPChild);
            }

            if (this.parallaxView4 != null && this.parallaxView4.Child is UIElement)
            {
                UIElement  ppChild       = this.parallaxView4.Child as UIElement;
                Visual     visualPPChild = ElementCompositionPreview.GetElementVisual(ppChild);
                Compositor compositor    = visualPPChild.Compositor;

                if (this.AnimatedValuesSpy == null)
                {
                    this.AnimatedValuesSpy = compositor.CreatePropertySet();
                }

                this.AnimatedValuesSpy.InsertScalar("VerticalOffset2", 0.0f);

                this.VerticalOffsetAnimation2 = compositor.CreateExpressionAnimation(visualVerticalTargetedPropertyName);
                this.VerticalOffsetAnimation2.SetReferenceParameter("visual", visualPPChild);
            }

            CheckSpyingTicksRequirement();
        }
コード例 #27
0
        protected override void OnApplyTemplate()
        {
            // TODO: Uno specific: NavigationView may not be set yet, wait for later #4689
            if (GetNavigationView() is null)
            {
                // Postpone template application for later
                return;
            }

            // Stop UpdateVisualState before template is applied. Otherwise the visuals may be unexpected
            m_appliedTemplate = false;

            UnhookEventsAndClearFields();

            base.OnApplyTemplate();

            // Find selection indicator
            // Retrieve pointers to stable controls
            //IControlProtected controlProtected = this;
            m_helper.Init(this);

            var rootGrid = GetTemplateChild(c_rootGrid) as Grid;

            if (rootGrid != null)
            {
                m_rootGrid = rootGrid;

                var flyoutBase = FlyoutBase.GetAttachedFlyout(rootGrid);
                if (flyoutBase != null)
                {
                    flyoutBase.Closing += OnFlyoutClosing;
                    m_flyoutClosingRevoker.Disposable = Disposable.Create(() => flyoutBase.Closing -= OnFlyoutClosing);
                }
            }

            HookInputEvents();

            IsEnabledChanged += OnIsEnabledChanged;
            m_isEnabledChangedRevoker.Disposable = Disposable.Create(() => IsEnabledChanged -= OnIsEnabledChanged);

            m_toolTip = (ToolTip)GetTemplateChild("ToolTip");

            var splitView = GetSplitView();

            if (splitView != null)
            {
                PrepNavigationViewItem(splitView);
            }
            else
            {
                // If the NVI is not prepared in an ItemPresenter, it will not have reference to SplitView. So check OnLoaded
                // if it the reference has been manually set in NavigationViewItemBase::OnLoaded().
                Loaded -= OnLoaded;
                Loaded += OnLoaded;
            }

            // Retrieve reference to NavigationView
            var nvImpl = GetNavigationView();

            if (nvImpl != null)
            {
                var repeater = GetTemplateChild(c_repeater) as ItemsRepeater;
                if (repeater != null)
                {
                    m_repeater = repeater;

                    // Primary element setup happens in NavigationView
                    repeater.ElementPrepared += nvImpl.OnRepeaterElementPrepared;
                    m_repeaterElementPreparedRevoker.Disposable = Disposable.Create(() => repeater.ElementPrepared -= nvImpl.OnRepeaterElementPrepared);
                    repeater.ElementClearing += nvImpl.OnRepeaterElementClearing;
                    m_repeaterElementClearingRevoker.Disposable = Disposable.Create(() => repeater.ElementClearing -= nvImpl.OnRepeaterElementClearing);

                    repeater.ItemTemplate = nvImpl.GetNavigationViewItemsFactory();
                }

                UpdateRepeaterItemsSource();
            }

            m_flyoutContentGrid = (Grid)GetTemplateChild(c_flyoutContentGrid);

            m_appliedTemplate = true;

            UpdateItemIndentation();
            UpdateVisualStateNoTransition();
            ReparentRepeater();
            // We dont want to update the repeater visibilty during OnApplyTemplate if NavigationView is in a mode when items are shown in a flyout
            if (!ShouldRepeaterShowInFlyout())
            {
                ShowHideChildren();
            }

            var visual = ElementCompositionPreview.GetElementVisual(this);

            NavigationView.CreateAndAttachHeaderAnimation(visual);

            _fullyInitialized = true;
        }
コード例 #28
0
        /// <summary>
        /// Uses Composition API to get the UIElement and sets an ExpressionAnimation
        /// The ExpressionAnimation uses the height of the UIElement to calculate an opacity value
        /// for the Header as it is scrolling off-screen. The opacity reaches 0 when the Header
        /// is entirely scrolled off.
        /// </summary>
        /// <returns><c>true</c> if the assignment was successful; otherwise, <c>false</c>.</returns>
        private bool AssignAnimation()
        {
            StopAnimation();

            if (AssociatedObject == null)
            {
                return(false);
            }

            if (_scrollViewer == null)
            {
                _scrollViewer = AssociatedObject as ScrollViewer ?? AssociatedObject.FindDescendant <ScrollViewer>();
            }

            if (_scrollViewer == null)
            {
                return(false);
            }

            var listView = AssociatedObject as Windows.UI.Xaml.Controls.ListViewBase ?? AssociatedObject.FindDescendant <Windows.UI.Xaml.Controls.ListViewBase>();

            if (listView != null && listView.ItemsPanelRoot != null)
            {
                Canvas.SetZIndex(listView.ItemsPanelRoot, -1);
            }

            if (_scrollProperties == null)
            {
                _scrollProperties = ElementCompositionPreview.GetScrollViewerManipulationPropertySet(_scrollViewer);
            }

            if (_scrollProperties == null)
            {
                return(false);
            }

            // Implicit operation: Find the Header object of the control if it uses ListViewBase
            if (HeaderElement == null && listView != null)
            {
                HeaderElement = listView.Header as UIElement;
            }

            var headerElement = HeaderElement as FrameworkElement;

            if (headerElement == null || headerElement.RenderSize.Height == 0)
            {
                return(false);
            }

            if (_headerVisual == null)
            {
                _headerVisual = ElementCompositionPreview.GetElementVisual(headerElement);
            }

            if (_headerVisual == null)
            {
                return(false);
            }

            _scrollViewer.ViewChanged -= ScrollViewer_ViewChanged;
            _scrollViewer.ViewChanged += ScrollViewer_ViewChanged;

            _scrollViewer.GotFocus -= ScrollViewer_GotFocus;
            _scrollViewer.GotFocus += ScrollViewer_GotFocus;

            headerElement.SizeChanged -= ScrollHeader_SizeChanged;
            headerElement.SizeChanged += ScrollHeader_SizeChanged;

            var compositor = _scrollProperties.Compositor;

            if (_animationProperties == null)
            {
                _animationProperties = compositor.CreatePropertySet();
                _animationProperties.InsertScalar("OffsetY", 0.0f);
            }

            var propSetOffset       = _animationProperties.GetReference().GetScalarProperty("OffsetY");
            var scrollPropSet       = _scrollProperties.GetSpecializedReference <ManipulationPropertySetReferenceNode>();
            var expressionAnimation = ExpressionFunctions.Max(ExpressionFunctions.Min(propSetOffset, -scrollPropSet.Translation.Y), 0);

            _headerVisual.StartAnimation("Offset.Y", expressionAnimation);

            return(true);
        }
コード例 #29
0
ファイル: VoIPPage.xaml.cs プロジェクト: murka1611/Unigram
        public VoIPPage(IProtoService protoService, ICacheService cacheService, IEventAggregator aggregator, IVoipService voipService)
        {
            InitializeComponent();

            _protoService = protoService;
            _cacheService = cacheService;
            _aggregator   = aggregator;

            _service = voipService;

            _durationTimer          = new DispatcherTimer();
            _durationTimer.Interval = TimeSpan.FromMilliseconds(500);
            _durationTimer.Tick    += DurationTimer_Tick;

            _debugTimer          = new DispatcherTimer();
            _debugTimer.Interval = TimeSpan.FromMilliseconds(500);
            _debugTimer.Tick    += DebugTimer_Tick;

            #region Reset

            LargeEmoji0.Source = null;
            LargeEmoji1.Source = null;
            LargeEmoji2.Source = null;
            LargeEmoji3.Source = null;

            #endregion

            #region Composition

            _descriptionVisual = ElementCompositionPreview.GetElementVisual(DescriptionLabel);
            _largeVisual       = ElementCompositionPreview.GetElementVisual(LargePanel);
            _compositor        = _largeVisual.Compositor;

            var graphicsEffect = new GaussianBlurEffect
            {
                Name       = "Blur",
                BlurAmount = 0,
                BorderMode = EffectBorderMode.Hard,
                Source     = new CompositionEffectSourceParameter("backdrop")
            };

            var effectFactory = _compositor.CreateEffectFactory(graphicsEffect, new[] { "Blur.BlurAmount" });
            var effectBrush   = effectFactory.CreateBrush();
            var backdrop      = _compositor.CreateBackdropBrush();
            effectBrush.SetSourceParameter("backdrop", backdrop);

            _blurBrush        = effectBrush;
            _blurVisual       = _compositor.CreateSpriteVisual();
            _blurVisual.Brush = _blurBrush;

            // Why does this crashes due to an access violation exception on certain devices?
            ElementCompositionPreview.SetElementChildVisual(BlurPanel, _blurVisual);

            var viewfinder = DropShadowEx.Attach(ViewfinderShadow, 20, 0.25f);
            viewfinder.RelativeSizeAdjustment = Vector2.One;

            #endregion

            //var titleBar = ApplicationView.GetForCurrentView().TitleBar;
            //titleBar.ButtonBackgroundColor = Colors.Transparent;
            //titleBar.ButtonForegroundColor = Colors.White;
            //titleBar.ButtonInactiveBackgroundColor = Colors.Transparent;
            //titleBar.ButtonInactiveForegroundColor = Colors.White;

            //Window.Current.SetTitleBar(BlurPanel);

            if (voipService.Call != null)
            {
                Update(voipService.Call, voipService.CallStarted);
            }

            if (voipService.Manager != null)
            {
                Connect(voipService.Manager);
            }

            Connect(voipService.Capturer);

            _viewfinder = ElementCompositionPreview.GetElementVisual(ViewfinderPanel);

            ViewfinderPanel.PointerPressed  += Viewfinder_PointerPressed;
            ViewfinderPanel.PointerMoved    += Viewfinder_PointerMoved;
            ViewfinderPanel.PointerReleased += Viewfinder_PointerReleased;
        }
コード例 #30
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);
        }