>  기사  >  백엔드 개발  >  Shape를 활용한 애니메이션 예시에 대한 자세한 설명

Shape를 활용한 애니메이션 예시에 대한 자세한 설명

零下一度
零下一度원래의
2017-06-23 15:05:471628검색

이전 글은 DoubleAnimation 적용에 대한 내용이 거의 대부분이었고, 이번 글은 PointAnimation에 대한 내용입니다.

1. PointAnimation을 사용하세요

PointAnimation을 사용하면 Shape가 변형될 수 있지만 실제로 이렇게 사용하는 사람은 많지 않습니다. 결국 WPF에서 만든 대부분의 소프트웨어는 그렇게 화려할 필요가 없습니다.

1.1 XAML에서 PointAnimation 사용

<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>

Shape를 활용한 애니메이션 예시에 대한 자세한 설명

이 예에서 가장 큰 문제는 속성 경로 구문을 기억할 수 없다면 Blend 생성에 의존하는 것이 가장 좋습니다.

1.2 코드에서 PointAnimation 사용하기

차트 등 Point가 많은 경우 일반적으로 C# 코드에서는 PointAnimation을 사용합니다.

_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();

Shape를 활용한 애니메이션 예시에 대한 자세한 설명

직접 SetTarget을 할 수 있기 때문에, so 속성 - 경로 구문은 매우 간단할 수 있습니다. SetTarget,所以Property-path语法就可以很简单。

2. 扩展PointAnimation

上面两个例子的动画都还算简单,如果更复杂些,XAML或C#代码都需要写到很复杂。我参考了这个网页 想做出类似的动画,但发现需要写很多XAML所以放弃用PointAnimation实现。这个页面的动画核心是这段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>

只需一组Point的集合就可以控制所有Point的动画,确实比PointAnimation高效很多。 在WPF中可以通过继承Timeline实现一个PointCollectionAnimamtion,具体可以参考这个项目。可惜的是虽然UWP的Timeline类并不封闭,但完全不知道如何继承并派生一个自定义的Animation。

这时候需要稍微变通一下思维。可以将DoubleAnimation理解成这样:Storyboard将TimeSpan传递给DoubleAnimation,DoubleAnimation通过这个TimeSpan(有时还需要结合EasingFunction)计算出目标属性的当前值最后传递给目标属性,如下图所示:

Shape를 활용한 애니메이션 예시에 대한 자세한 설명

既然这样,也可以接收到这个计算出来的Double,再通过Converter计算出目标的PointCollection值:

Shape를 활용한 애니메이션 예시에 대한 자세한 설명

假设告诉这个Converter当传入的Double值(命名为Progress)为0的时候,PointCollection是{0,0 1,1 …},Progress为100时PointCollection是{1,1 2,2 …},当Progress处于其中任何值时的计算方法则是:

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;
}

这样就完成了从TimeSpan到PointCollection的转换过程。然后就是定义在XAML上的使用方式。参考上面PointCollectionAnimation,虽然多了个Converter,但XAML也应该足够简洁:

<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" />

最终我选择了将这个Converter命名为ProgressToPointCollectionBridge。可以看出Polygon 将Points绑定到ProgressToPointCollectionBridge,DoubleAnimation 改变ProgressToPointCollectionBridge.Progress,从而改变Points。XAML的简洁程度还算令人满意,如果需要操作多个点的话相对于PointAnimation的优势就很大。

运行结果如下:

Shape를 활용한 애니메이션 예시에 대한 자세한 설명

完整的XAML:

<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. 结语

如果将DoubleAnimation说成“对目标的Double属性做动画”,那PointAnimation可以说成“对目标的Point.X和Point.Y两个Double属性同时做动画”,ColorAnimation则是“对目标的Color.A、R、G、B四个Int属性同时做动画”。这样理解的话PointAnimation和ColorAnimation只不过是DoubleAnimation的延伸而已,进一步的说,通过DoubleAnimation应该可以延伸出所有类型属性的动画。不过我并不清楚怎么在UWP上自定义动画,只能通过本文的折衷方式扩展。虽然XAML需要写复杂些,但这样也有它的好处:

  • 不需要了解太多Animation相关类的知识,只需要有依赖属性、绑定等基础知识就够了。

  • 不会因为动画API的改变而更改,可以兼容WPF、Silverlight和UWP(大概吧,我没有真的在WPF上测试这些代码)。

  • 代码足够简单,省去了计算TimeSpan及EasingFunction的步骤。 稍微修改下还可以做成泛型的AnimationBridge 808ed36a4929ba137db2b9ee76c79186

    2. PointAnimation 확장
위 두 예제의 애니메이션은 비교적 간단합니다. 더 복잡하다면 XAML 또는 C# 코드를 매우 복잡하게 작성해야 합니다. 이 웹페이지를 참고해서 비슷한 애니메이션을 만들고 싶었지만 XAML을 많이 작성해야 한다는 사실을 깨닫고 PointAnimation을 사용하여 구현하는 것을 포기했습니다. 이 페이지의 핵심 애니메이션은 다음 HTML입니다.

rrreee

모든 포인트의 애니메이션을 제어하려면 포인트 세트만 필요하며 이는 실제로 PointAnimation보다 훨씬 효율적입니다. WPF에서는 타임라인을 상속하여 PointCollectionAnimamtion을 구현할 수 있습니다. 자세한 내용은 이 프로젝트를 참조하세요. 안타깝게도 UWP의 Timeline 클래스는 닫혀 있지 않지만 사용자 지정 애니메이션을 상속하고 파생시키는 방법을 모르겠습니다.


이때에는 생각을 조금 바꿔야 합니다. DoubleAnimation은 다음과 같이 이해될 수 있습니다. Storyboard는 TimeSpan을 DoubleAnimation에 전달하고 DoubleAnimation은 이 TimeSpan(때때로 EasingFunction과 결합됨)을 사용하여 대상 속성의 현재 값을 계산하고 마지막으로 다음 그림과 같이 이를 대상 속성에 전달합니다.

🎜Shape를 활용한 애니메이션 예시에 대한 자세한 설명🎜🎜이 경우 계산된 Double을 받아서 계산할 수도 있습니다. Converter PointCollection 값을 통해 대상: 🎜🎜Shape를 활용한 애니메이션 예시에 대한 자세한 설명🎜🎜이 Converter에 언제 알려준다고 가정해 보세요. 들어오는 Double 값(Progress라고 명명됨)이 0일 때 PointCollection은 {0,0 1,1...}이고 Progress가 100일 때 PointCollection은 {1,1 2,2...}이고 Progress가 임의일 때 이 값 중 계산 방법은 다음과 같습니다.🎜🎜rrreee🎜🎜이렇게 하면 TimeSpan에서 PointCollection으로의 변환 프로세스가 완료됩니다. 그런 다음 XAML에 정의하여 사용하는 방법이 있습니다. 위의 PointCollectionAnimation을 참조하면 추가 변환기가 있지만 XAML은 충분히 간결해야 합니다. 🎜🎜rrreee🎜🎜결국 이 변환기의 이름을 ProgressToPointCollectionBridge로 선택했습니다. Polygon은 Point를 ProgressToPointCollectionBridge에 바인딩하고 DoubleAnimation은 ProgressToPointCollectionBridge.Progress를 변경하여 Point를 변경하는 것을 볼 수 있습니다. XAML의 단순성은 매우 만족스럽습니다. 여러 지점을 조작해야 하는 경우 PointAnimation에 비해 큰 이점이 있습니다. 🎜🎜실행 결과는 다음과 같습니다. 🎜🎜Shape를 활용한 애니메이션 예시에 대한 자세한 설명🎜🎜전체 XAML: 🎜 🎜rrreee 🎜🎜ProgressToPointCollectionBridge:🎜🎜rrreee🎜🎜3. 결론🎜🎜DoubleAnimation이 "대상의 Double 속성을 애니메이션화"한다고 하면 PointAnimation은 "Point.X와 Point.Y를 모두 애니메이션화한다"고 말할 수 있습니다. 동시에 대상의 이중 속성 "애니메이션"인 반면 ColorAnimation은 "대상의 Color.A, R, G 및 B의 네 가지 Int 속성을 동시에 애니메이션화합니다." 이러한 방식으로 이해하면 PointAnimation 및 ColorAnimation은 DoubleAnimation의 확장일 뿐입니다. 또한 DoubleAnimation은 모든 유형의 속성에 대한 애니메이션을 확장할 수 있어야 합니다. 하지만 UWP에서 애니메이션을 사용자 지정하는 방법은 이 문서의 절충 방법을 통해서만 확장할 수 있습니다. XAML은 더 복잡하게 작성해야 하지만 다음과 같은 장점도 있습니다. 🎜
  • 🎜애니메이션 관련 클래스에 대해 너무 많이 알 필요는 없습니다. 종속성 속성과 바인딩이 있습니다. 기본 사항만 기다리세요. 🎜🎜
  • 🎜는 애니메이션 API 변경으로 인해 변경되지 않으며 WPF, Silverlight 및 UWP와 호환됩니다(아마 WPF에서 실제로 이러한 코드를 테스트하지 않았을 것입니다). 🎜🎜
  • 🎜코드는 TimeSpan 및 EasingFunction 계산 단계를 생략할 정도로 매우 간단합니다. 약간만 수정하면 일반 AnimationBridge 808ed36a4929ba137db2b9ee76c79186로 만들어 PointCollection 이외의 데이터 유형을 지원할 수도 있습니다. 🎜🎜🎜🎜 이전 기사를 바탕으로 UWP에서 제공하지 않는 기능은 앞으로 대체 방법을 통해 구현할 수 있다는 느낌을 항상 받습니다. 🎜🎜4. 참고🎜🎜SVG 모양 모핑 작동 방식🎜Gadal 메타 강의 계획서🎜

위 내용은 Shape를 활용한 애니메이션 예시에 대한 자세한 설명의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.