Maison  >  Article  >  développement back-end  >  Explication détaillée d'exemples d'animation utilisant Shape

Explication détaillée d'exemples d'animation utilisant Shape

零下一度
零下一度original
2017-06-23 15:05:471629parcourir

L'article précédent portait presque uniquement sur l'application de DoubleAnimation, et cet article concerne PointAnimation.

1. Utiliser PointAnimation

L'utilisation de PointAnimation peut déformer Shape, mais en fait, je ne vois pas beaucoup de gens l'utiliser de cette façon. Après tout, la plupart des logiciels créés par WPF n'ont pas besoin de l'être. tellement chic.

1.1 Utilisation de PointAnimation sur XAML

<Storyboard x:Name="Storyboard2"            RepeatBehavior="Forever"            AutoReverse="True"            Duration="0:0:4"><PointAnimation Storyboard.TargetProperty="(Path.Data).(PathGeometry.Figures)[0].(PathFigure.StartPoint)"                    Storyboard.TargetName="Path2"                    To="0,0"                    EnableDependentAnimation="True" /><PointAnimation Storyboard.TargetProperty="(Path.Data).(PathGeometry.Figures)[0].(PathFigure.Segments)[0].(LineSegment.Point)"                    Storyboard.TargetName="Path2"                    To="100,0"                    EnableDependentAnimation="True" /><ColorAnimation To="#FF85C82E"                    Storyboard.TargetProperty="(Shape.Fill).(SolidColorBrush.Color)"                    Storyboard.TargetName="Path2" /></Storyboard>…<Path Margin="0,20,0,0"      x:Name="Path2"      Fill="GreenYellow"><Path.Data><PathGeometry><PathFigure StartPoint="50,0"><LineSegment Point="50,0" /><LineSegment Point="0,100" /><LineSegment Point="0,100" /><LineSegment Point="100,100" /><LineSegment Point="100,100" /></PathFigure></PathGeometry></Path.Data></Path>

Explication détaillée d'exemples d'animation utilisant Shape

Le plus gros casse-tête dans cet exemple est la syntaxe du chemin de propriété, si vous Je ne peux pas le mémoriser, il est préférable de s'appuyer sur la génération Blend.

1.2 Utiliser PointAnimation dans le code

S'il y a beaucoup de points, comme des graphiques, PointAnimation est généralement utilisé dans le code C# :

_storyboard = new Storyboard();
Random random = new Random();for (int i = 0; i < _pathFigure.Segments.Count; i++)
{var animation = new PointAnimation { Duration = TimeSpan.FromSeconds(3) };
    Storyboard.SetTarget(animation, _pathFigure.Segments[i]);
    Storyboard.SetTargetProperty(animation, "(LineSegment.Point)");
    animation.EnableDependentAnimation = true;
    animation.EasingFunction = new QuarticEase { EasingMode = EasingMode.EaseOut };
    animation.To = new Point((_pathFigure.Segments[i] as LineSegment).Point.X, (i % 2 == 0 ? 1 : -1) * i * 1.2 + 60);
    _storyboard.Children.Add(animation);
}
_storyboard.Begin();

Explication détaillée d'exemples d'animation utilisant Shape

Parce que vous pouvez directement SetTarget, la syntaxe Property-path peut être très simple.

2. Extend PointAnimation

Les animations dans les deux exemples ci-dessus sont relativement simples si elles sont plus compliquées, le code XAML ou C# devra être écrit de manière très compliquée. J'ai fait référence à cette page Web et je voulais créer une animation similaire, mais j'ai découvert que j'avais besoin d'écrire beaucoup de XAML, j'ai donc abandonné l'utilisation de PointAnimation pour l'implémenter. L'animation principale de cette page est ce HTML :

<polygon fill="#FFD41D" points="97.3,0 127.4,60.9 194.6,70.7 145.9,118.1 157.4,185.1 97.3,153.5 37.2,185.1 48.6,118.1 0,70.7     67.2,60.9">  
      <animate id="animation-to-check" begin="indefinite" fill="freeze" attributeName="points" dur="500ms" to="110,58.2 147.3,0 192.1,29 141.7,105.1 118.7,139.8 88.8,185.1 46.1,156.5 0,125 23.5,86.6     71.1,116.7"/>
      <animate id="animation-to-star" begin="indefinite" fill="freeze" attributeName="points" dur="500ms" to="97.3,0 127.4,60.9 194.6,70.7 145.9,118.1 157.4,185.1 97.3,153.5 37.2,185.1 48.6,118.1 0,70.7     67.2,60.9"/>  </polygon>

Vous n'avez besoin que d'un ensemble de points pour contrôler l'animation de tous les points, ce qui est en effet bien plus efficace que PointAnimation. Dans WPF, vous pouvez implémenter une PointCollectionAnimamtion en héritant de Timeline. Pour plus de détails, veuillez vous référer à ce projet. Malheureusement, bien que la classe Timeline d'UWP ne soit pas fermée, je ne sais pas comment hériter et dériver une animation personnalisée.

En ce moment, vous devez changer un peu votre façon de penser. DoubleAnimation peut être compris comme ceci : Storyboard transmet TimeSpan à DoubleAnimation, et DoubleAnimation calcule la valeur actuelle de l'attribut cible via ce TimeSpan (il doit parfois être combiné avec EasingFunction) et la transmet finalement à l'attribut cible, comme indiqué dans ce qui suit. figure :

Explication détaillée d'exemples d'animation utilisant Shape

Dans ce cas, vous pouvez également recevoir ce Double calculé, puis calculer la valeur PointCollection cible via le Convertisseur :

Explication détaillée d'exemples d'animation utilisant Shape

Supposons que vous disiez à ce convertisseur que lorsque la valeur Double entrante (nommée Progress) est 0, PointCollection est {0,0 1,1...}, lorsque Progress est 100, PointCollection est {1,1 2,2. ..}, lorsque Progress atteint l'une de ces valeurs. La méthode de calcul du temps est :

private PointCollection GetCurrentPoints(PointCollection fromPoints, PointCollection toPoints, double percentage)
{var result = new PointCollection();for (var i = 0;
        i < Math.Min(fromPoints.Count, toPoints.Count);
        i++)
    {
        var x = (1 - percentage / 100d) * fromPoints[i].X + percentage / 100d * toPoints[i].X;
        var y = (1 - percentage / 100d) * fromPoints[i].Y + percentage / 100d * toPoints[i].Y;

        result.Add(new Point(x, y));
    }return result;
}

Ceci termine le processus de conversion de TimeSpan en PointCollection. Ensuite, il y a la façon de l’utiliser en XAML. En référence au PointCollectionAnimation ci-dessus, bien qu'il existe un convertisseur supplémentaire, le XAML devrait être suffisamment concis :

<local:ProgressToPointCollectionBridge x:Name="ProgressToPointCollectionBridge"><PointCollection>97.3,0 127.4,60.9 194.6,70.7 145.9,118.1 157.4,185.1 97.3,153.5 37.2,185.1 48.6,118.1 0,70.7 67.2,60.9</PointCollection><PointCollection>110,58.2 147.3,0 192.1,29 141.7,105.1 118.7,139.8 88.8,185.1 46.1,156.5 0,125 23.5,86.6 71.1,116.7</PointCollection></local:ProgressToPointCollectionBridge><Storyboard x:Name="Storyboard1"            FillBehavior="HoldEnd"><DoubleAnimation Duration="0:0:2"                        To="100"                        FillBehavior="HoldEnd"                        Storyboard.TargetProperty="(local:ProgressToPointCollectionBridge.Progress)"                        Storyboard.TargetName="ProgressToPointCollectionBridge"                        EnableDependentAnimation="True"/></Storyboard>…<Polygon x:Name="polygon"            Points="{Binding Source={StaticResource ProgressToPointCollectionBridge},Path=Points}"            Stroke="DarkOliveGreen"            StrokeThickness="2"            Height="250"            Width="250"            Stretch="Fill" />

Au final, j'ai choisi de nommer ce convertisseur ProgressToPointCollectionBridge. On peut voir que Polygon lie les points à ProgressToPointCollectionBridge et que DoubleAnimation modifie ProgressToPointCollectionBridge.Progress, modifiant ainsi les points. La simplicité de XAML est tout à fait satisfaisante. Si vous devez exploiter plusieurs points, il présente de grands avantages par rapport à PointAnimation.

Les résultats en cours d'exécution sont les suivants :

Explication détaillée d'exemples d'animation utilisant Shape

XAML complet :

<UserControl.Resources><local:ProgressToPointCollectionBridge x:Name="ProgressToPointCollectionBridge"><PointCollection>97.3,0 127.4,60.9 194.6,70.7 145.9,118.1 157.4,185.1 97.3,153.5 37.2,185.1 48.6,118.1 0,70.7 67.2,60.9</PointCollection><PointCollection>110,58.2 147.3,0 192.1,29 141.7,105.1 118.7,139.8 88.8,185.1 46.1,156.5 0,125 23.5,86.6 71.1,116.7</PointCollection></local:ProgressToPointCollectionBridge><Storyboard x:Name="Storyboard1"                FillBehavior="HoldEnd"><DoubleAnimation Duration="0:0:2"                            To="100"                            FillBehavior="HoldEnd"                            Storyboard.TargetProperty="(local:ProgressToPointCollectionBridge.Progress)"                            Storyboard.TargetName="ProgressToPointCollectionBridge"                            EnableDependentAnimation="True"><DoubleAnimation.EasingFunction><ElasticEase EasingMode="EaseInOut" /></DoubleAnimation.EasingFunction></DoubleAnimation><ColorAnimation Duration="0:0:2"                        To="#FF48F412"                        Storyboard.TargetProperty="(Shape.Fill).(SolidColorBrush.Color)"                        Storyboard.TargetName="polygon"                        d:IsOptimized="True"><ColorAnimation.EasingFunction><ElasticEase EasingMode="EaseInOut" /></ColorAnimation.EasingFunction></ColorAnimation></Storyboard></UserControl.Resources><Grid x:Name="LayoutRoot"        Background="White"><Polygon x:Name="polygon"                Points="{Binding Source={StaticResource ProgressToPointCollectionBridge},Path=Points}"                Stroke="DarkOliveGreen"                StrokeThickness="2"                Height="250"                Width="250"                Stretch="Fill"                Fill="#FFEBF412" /></Grid>

ProgressToPointCollectionBridge :

[ContentProperty(Name = nameof(Children))]public class ProgressToPointCollectionBridge : DependencyObject
{public ProgressToPointCollectionBridge()
    {
        Children = new ObservableCollection<PointCollection>();
    }/// <summary>///     获取或设置Points的值/// </summary>public PointCollection Points
    {get { return (PointCollection) GetValue(PointsProperty); }set { SetValue(PointsProperty, value); }
    }/// <summary>///     获取或设置Progress的值/// </summary>public double Progress
    {get { return (double) GetValue(ProgressProperty); }set { SetValue(ProgressProperty, value); }
    }/// <summary>///     获取或设置Children的值/// </summary>public Collection<PointCollection> Children
    {get { return (Collection<PointCollection>) GetValue(ChildrenProperty); }set { SetValue(ChildrenProperty, value); }
    }protected virtual void OnProgressChanged(double oldValue, double newValue)
    {UpdatePoints();
    }protected virtual void OnChildrenChanged(Collection<PointCollection> oldValue, Collection<PointCollection> newValue)
    {var oldCollection = oldValue as INotifyCollectionChanged;if (oldCollection != null)
            oldCollection.CollectionChanged -= OnChildrenCollectionChanged;var newCollection = newValue as INotifyCollectionChanged;if (newCollection != null)
            newCollection.CollectionChanged += OnChildrenCollectionChanged;UpdatePoints();
    }private void OnChildrenCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
    {UpdatePoints();
    }private void UpdatePoints()
    {if (Children == null || Children.Any() == false)
        {
            Points = null;
        }else if (Children.Count == 1)
        {var fromPoints = new PointCollection();for (var i = 0; i < Children[0].Count; i++)
                fromPoints.Add(new Point(0, 0));var toPoints = Children[0];
            Points = GetCurrentPoints(fromPoints, toPoints, Progress);
        }else{var rangePerSection = 100d / (Children.Count - 1);var fromIndex = Math.Min(Children.Count - 2, Convert.ToInt32(Math.Floor(Progress / rangePerSection)));
            fromIndex = Math.Max(fromIndex, 0);var toIndex = fromIndex + 1;
            PointCollection fromPoints;if (fromIndex == toIndex)
            {
                fromPoints = new PointCollection();for (var i = 0; i < Children[0].Count; i++)
                    fromPoints.Add(new Point(0, 0));
            }else{
                fromPoints = Children.ElementAt(fromIndex);
            }var toPoints = Children.ElementAt(toIndex);
            var percentage = (Progress / rangePerSection - fromIndex) * 100;

            Points = GetCurrentPoints(fromPoints, toPoints, percentage);
        }
    }private PointCollection GetCurrentPoints(PointCollection fromPoints, PointCollection toPoints, double percentage)
    {var result = new PointCollection();for (var i = 0;
            i < Math.Min(fromPoints.Count, toPoints.Count);
            i++)
        {
            var x = (1 - percentage / 100d) * fromPoints[i].X + percentage / 100d * toPoints[i].X;
            var y = (1 - percentage / 100d) * fromPoints[i].Y + percentage / 100d * toPoints[i].Y;

            result.Add(new Point(x, y));
        }return result;
    }#region DependencyProperties#endregion}

3. Conclusion

Si on dit que DoubleAnimation "anime la propriété Double de la cible", alors PointAnimation peut être dit "anime le point de la cible". .X et Point. Y deux propriétés Double sont animées en même temps", ColorAnimation est "les quatre propriétés Int Color.A, R, G, B de la cible sont animées en même temps." Compris de cette manière, PointAnimation et ColorAnimation ne sont que des extensions de DoubleAnimation. De plus, DoubleAnimation devrait être capable d'étendre l'animation de tous les types d'attributs. Cependant, je ne sais pas comment personnaliser les animations sur UWP, je ne peux l'étendre que via la méthode de compromis décrite dans cet article. Bien que XAML doive être écrit de manière plus compliquée, il a aussi ses avantages :

  • Vous n'avez pas besoin d'en savoir trop sur les classes liées à l'animation, vous n'avez besoin que de connaissances de base telles que les dépendances. propriétés et liaison.

  • ne changera pas en raison des changements dans l'API d'animation, et est compatible avec WPF, Silverlight et UWP (probablement, je n'ai pas vraiment testé ces codes sur WPF).

  • Le code est assez simple, éliminant les étapes de calcul de TimeSpan et d'EasingFunction. Avec de légères modifications, il peut également être transformé en un AnimationBridge 808ed36a4929ba137db2b9ee76c79186 générique pour prendre en charge des types de données autres que PointCollection.

Sur la base de l'article précédent, j'ai toujours le sentiment que toutes les fonctions non fournies par UWP peuvent être implémentées via des méthodes alternatives à l'avenir. Binding et DependencyProperty sont vraiment les meilleures pour les développeurs UWP. .

4. Référence

Comment fonctionne le morphing de forme SVG
Gadal MetaSyllabus

Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

Déclaration:
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn