이전 글은 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>
이 예에서 가장 큰 문제는 속성 경로 구문을 기억할 수 없다면 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();
직접 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)计算出目标属性的当前值最后传递给目标属性,如下图所示:
既然这样,也可以接收到这个计算出来的Double,再通过Converter计算出目标的PointCollection值:
假设告诉这个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的优势就很大。
运行结果如下:
完整的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的步骤。 稍微修改下还可以做成泛型的
2. PointAnimation 확장AnimationBridge
이때에는 생각을 조금 바꿔야 합니다. DoubleAnimation은 다음과 같이 이해될 수 있습니다. Storyboard는 TimeSpan을 DoubleAnimation에 전달하고 DoubleAnimation은 이 TimeSpan(때때로 EasingFunction과 결합됨)을 사용하여 대상 속성의 현재 값을 계산하고 마지막으로 다음 그림과 같이 이를 대상 속성에 전달합니다.


ProgressToPointCollectionBridge
로 선택했습니다. Polygon은 Point를 ProgressToPointCollectionBridge에 바인딩하고 DoubleAnimation은 ProgressToPointCollectionBridge.Progress를 변경하여 Point를 변경하는 것을 볼 수 있습니다. XAML의 단순성은 매우 만족스럽습니다. 여러 지점을 조작해야 하는 경우 PointAnimation에 비해 큰 이점이 있습니다. 🎜🎜실행 결과는 다음과 같습니다. 🎜🎜
- 🎜애니메이션 관련 클래스에 대해 너무 많이 알 필요는 없습니다. 종속성 속성과 바인딩이 있습니다. 기본 사항만 기다리세요. 🎜🎜
- 🎜는 애니메이션 API 변경으로 인해 변경되지 않으며 WPF, Silverlight 및 UWP와 호환됩니다(아마 WPF에서 실제로 이러한 코드를 테스트하지 않았을 것입니다). 🎜🎜
- 🎜코드는 TimeSpan 및 EasingFunction 계산 단계를 생략할 정도로 매우 간단합니다. 약간만 수정하면 일반
AnimationBridge
로 만들어 PointCollection 이외의 데이터 유형을 지원할 수도 있습니다. 🎜🎜🎜🎜 이전 기사를 바탕으로 UWP에서 제공하지 않는 기능은 앞으로 대체 방법을 통해 구현할 수 있다는 느낌을 항상 받습니다. 🎜🎜4. 참고🎜🎜SVG 모양 모핑 작동 방식🎜Gadal 메타 강의 계획서🎜
위 내용은 Shape를 활용한 애니메이션 예시에 대한 자세한 설명의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

C#은 2000 년 Microsoft가 발표 한 프로그래밍 언어로 C의 힘과 Java의 단순성을 결합하는 것을 목표로합니다. 1.C#은 캡슐화, 상속 및 다형성을 지원하는 유형 안전 객체 지향 프로그래밍 언어입니다. 2. C#의 컴파일 프로세스는 코드를 중간 언어 (IL)로 변환 한 다음 .NET 런타임 환경 (CLR)에서 기계 코드 실행으로 컴파일합니다. 3. C#의 기본 사용에는 가변 선언, 제어 흐름 및 기능 정의가 포함되며, 고급 사용법은 비동기 프로그래밍, LINQ 및 대표 등을 포함합니다. 5. 성능 최적화 제안에는 LINQ 사용, 비동기 프로그래밍 및 코드 가독성 향상이 포함됩니다.

C#은 프로그래밍 언어이며 .NET은 소프트웨어 프레임 워크입니다. 1.C#은 Microsoft에 의해 개발되었으며 다중 플랫폼 개발에 적합합니다. 2..NET은 클래스 라이브러리 및 런타임 환경을 제공하며 다국어를 지원합니다. 두 사람은 현대적인 응용 프로그램을 구축하기 위해 함께 작동합니다.

C# .NET은 C# 언어 및 .NET 프레임 워크의 장점을 결합한 강력한 개발 플랫폼입니다. 1) 엔터프라이즈 애플리케이션, 웹 개발, 게임 개발 및 모바일 애플리케이션 개발에 널리 사용됩니다. 2) C# 코드는 중간 언어로 컴파일되며 .NET 런타임 환경에서 실행되며 쓰레기 수집, 유형 안전 및 LINQ 쿼리를 지원합니다. 3) 사용의 예로는 기본 콘솔 출력 및 고급 LINQ 쿼리가 포함됩니다. 4) 빈 참조 및 유형 변환 오류와 같은 일반적인 오류는 디버거 및 로깅을 통해 해결할 수 있습니다. 5) 성능 최적화 제안에는 비동기 프로그래밍 및 LINQ 쿼리 최적화가 포함됩니다. 6) 경쟁에도 불구하고 C#.net은 지속적인 혁신을 통해 중요한 위치를 유지합니다.

C#.NET의 미래 트렌드는 주로 클라우드 컴퓨팅, 마이크로 서비스, AI 및 기계 학습 통합, 크로스 플랫폼 개발의 세 가지 측면에 중점을 둡니다. 1) 클라우드 컴퓨팅 및 마이크로 서비스 : C#.net은 Azure 플랫폼을 통해 클라우드 환경 성능을 최적화하고 효율적인 마이크로 서비스 아키텍처의 구성을 지원합니다. 2) AI 및 기계 학습의 통합 : ML.NET 라이브러리의 도움으로 C# 개발자는 기계 학습 모델을 응용 프로그램에 포함시켜 지능형 애플리케이션의 개발을 촉진 할 수 있습니다. 3) 크로스 플랫폼 개발 : .NETCORE 및 .NET5를 통해 C# 응용 프로그램은 Windows, Linux 및 MacOS에서 실행되어 배포 범위를 확장 할 수 있습니다.

C#.NET 개발의 최신 개발 및 모범 사례에는 다음이 포함됩니다. 1. 비동기 프로그래밍은 응용 프로그램 응답 성을 향상시키고 Async 및 Await 키워드를 사용하여 비 차단 코드를 단순화합니다. 2. LINQ는 지연된 실행 및 표현 트리를 통해 데이터를 효율적으로 조작하는 강력한 쿼리 기능을 제공합니다. 3. 성능 최적화 제안에는 비동기 프로그래밍 사용, LINQ 쿼리 최적화, 합리적으로 메모리 관리, 코드 가독성 및 유지 보수 개선 및 단위 테스트 작성이 포함됩니다.

.NET을 사용하여 응용 프로그램을 구축하는 방법? .NET을 사용하여 응용 프로그램 빌드 응용 프로그램은 다음 단계를 통해 달성 할 수 있습니다. 1) C# 언어 및 크로스 플랫폼 개발 지원을 포함한 .NET의 기본 사항을 이해합니다. 2) .NET 생태계의 구성 요소 및 작동 원리와 같은 핵심 개념을 배우십시오. 3) 간단한 콘솔 애플리케이션에서 복잡한 WebApis 및 데이터베이스 운영에 이르기까지 기본 및 고급 사용을 마스터합니다. 4) 구성 및 데이터베이스 연결 문제와 같은 일반적인 오류 및 디버깅 기술에 익숙해야합니다. 5) 응용 프로그램 성능 최적화 및 비동기 프로그래밍 및 캐싱과 같은 모범 사례.

C#은 엔터프라이즈 레벨 애플리케이션, 게임 개발, 모바일 응용 프로그램 및 웹 개발에서 널리 사용됩니다. 1) 엔터프라이즈 레벨 애플리케이션에서 C#은 종종 asp.netcore가 webapi를 개발하는 데 사용됩니다. 2) 게임 개발에서 C#은 Unity 엔진과 결합되어 역할 제어 및 기타 기능을 실현합니다. 3) C#은 코드 유연성 및 응용 프로그램 성능을 향상시키기 위해 다형성 및 비동기 프로그래밍을 지원합니다.

C# 및 .NET은 웹, 데스크탑 및 모바일 개발에 적합합니다. 1) 웹 개발에서 ASP.NETCORE는 크로스 플랫폼 개발을 지원합니다. 2) 데스크탑 개발은 WPF 및 Winforms를 사용하여 다양한 요구에 적합합니다. 3) 모바일 개발은 Xamarin을 통한 크로스 플랫폼 응용 프로그램을 실현합니다.


핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

Video Face Swap
완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

인기 기사

뜨거운 도구

SublimeText3 중국어 버전
중국어 버전, 사용하기 매우 쉽습니다.

VSCode Windows 64비트 다운로드
Microsoft에서 출시한 강력한 무료 IDE 편집기

드림위버 CS6
시각적 웹 개발 도구

Dreamweaver Mac版
시각적 웹 개발 도구

SublimeText3 Linux 새 버전
SublimeText3 Linux 최신 버전
