0

0

[UWP]用Shape做动画(2):使用与扩展PointAnimation

爱谁谁

爱谁谁

发布时间:2025-08-28 10:46:14

|

1015人浏览过

|

来源于php中文网

原创

上一篇文章主要介绍了doubleanimation的应用,本文将深入探讨pointanimation的使用和扩展。

  1. 使用PointAnimation PointAnimation可以使Shape变形,但这种用法并不常见,因为WPF开发的软件通常不需要如此复杂的效果。

1.1 在XAML中使用PointAnimation 在XAML中使用PointAnimation的代码如下:

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

[UWP]用Shape做动画(2):使用与扩展PointAnimation

在这个例子中,最棘手的是Property-path语法,如果不熟悉,最好依赖Blend来生成。

1.2 在代码中使用PointAnimation 如果需要处理大量的Point,例如图表,通常会在C#代码中使用PointAnimation:

_storyboard = new Storyboard();
Random random = new Random();
for (int i = 0; i < _points.Count; i++)
{
    var pointAnimation = new PointAnimation
    {
        Duration = TimeSpan.FromSeconds(2),
        To = new Point(random.NextDouble() * 100, random.NextDouble() * 100)
    };
    Storyboard.SetTarget(pointAnimation, _points[i]);
    Storyboard.SetTargetProperty(pointAnimation, new PropertyPath("Point"));
    _storyboard.Children.Add(pointAnimation);
}
_storyboard.Begin();

[UWP]用Shape做动画(2):使用与扩展PointAnimation

因为可以直接使用

SetTarget
,所以Property-path语法可以简化。

  1. 扩展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 attributeName="points" begin="indefinite" dur="500ms" fill="freeze" id="animation-to-check" 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>
    <animate attributeName="points" begin="indefinite" dur="500ms" fill="freeze" id="animation-to-star" 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"></animate>
</polygon>

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

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

[UWP]用Shape做动画(2):使用与扩展PointAnimation

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

[UWP]用Shape做动画(2):使用与扩展PointAnimation

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

云从科技AI开放平台
云从科技AI开放平台

云从AI开放平台

下载
private PointCollection GetCurrentPoints(PointCollection fromPoints, PointCollection toPoints, double percentage)
{
    var result = new PointCollection();
    for (var i = 0; i < fromPoints.Count; i++)
    {
        var fromPoint = fromPoints[i];
        var toPoint = toPoints[i];
        var x = fromPoint.X + (toPoint.X - fromPoint.X) * percentage / 100;
        var y = fromPoint.Y + (toPoint.Y - fromPoint.Y) * percentage / 100;
        result.Add(new Point(x, y));
    }
    return result;
}

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

<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>
</ProgressToPointCollectionBridge>
<Storyboard FillBehavior="HoldEnd" x:Name="Storyboard1">
    <DoubleAnimation Duration="0:0:2" EnableDependentAnimation="True" FillBehavior="HoldEnd" Storyboard.TargetName="ProgressToPointCollectionBridge" Storyboard.TargetProperty="(local:ProgressToPointCollectionBridge.Progress)" To="100"></DoubleAnimation>
</Storyboard>
...
<Polygon Height="250" Points="{Binding Source={StaticResource ProgressToPointCollectionBridge},Path=Points}" Stretch="Fill" Stroke="DarkOliveGreen" StrokeThickness="2" Width="250" x:Name="polygon"></Polygon>

最终,我选择将这个Converter命名为

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

运行结果如下:

[UWP]用Shape做动画(2):使用与扩展PointAnimation

完整的XAML如下:

<UserControl.Resources>
    <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>
    </ProgressToPointCollectionBridge>
    <Storyboard FillBehavior="HoldEnd" x:Name="Storyboard1">
        <DoubleAnimation Duration="0:0:2" EnableDependentAnimation="True" FillBehavior="HoldEnd" Storyboard.TargetName="ProgressToPointCollectionBridge" Storyboard.TargetProperty="(local:ProgressToPointCollectionBridge.Progress)" To="100">
            <DoubleAnimation.EasingFunction>
                <ElasticEase EasingMode="EaseInOut"></ElasticEase>
            </DoubleAnimation.EasingFunction>
        </DoubleAnimation>
        <ColorAnimation d:IsOptimized="True" Duration="0:0:2" Storyboard.TargetName="polygon" Storyboard.TargetProperty="(Shape.Fill).(SolidColorBrush.Color)" To="#FF48F412">
            <ColorAnimation.EasingFunction>
                <ElasticEase EasingMode="EaseInOut"></ElasticEase>
            </ColorAnimation.EasingFunction>
        </ColorAnimation>
    </Storyboard>
</UserControl.Resources>
<Grid Background="White" x:Name="LayoutRoot">
    <Polygon Fill="#FFEBF412" Height="250" Points="{Binding Source={StaticResource ProgressToPointCollectionBridge},Path=Points}" Stretch="Fill" Stroke="DarkOliveGreen" StrokeThickness="2" Width="250" x:Name="polygon"></Polygon>
</Grid>

ProgressToPointCollectionBridge的实现如下:

[ContentProperty(Name = nameof(Children))]
public class ProgressToPointCollectionBridge : DependencyObject
{
    public ProgressToPointCollectionBridge()
    {
        Children = new ObservableCollection<PointCollection>();
    }
<pre class="brush:php;toolbar:false;">/// <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)
    {
        Points = Children[0];
    }
    else if (Children.Count == 2)
    {
        var fromPoints = Children[0];
        var toPoints = Children[1];
        Points = GetCurrentPoints(fromPoints, toPoints, Progress);
    }
}

private PointCollection GetCurrentPoints(PointCollection fromPoints, PointCollection toPoints, double percentage)
{
    var result = new PointCollection();
    for (var i = 0; i < fromPoints.Count; i++)
    {
        var fromPoint = fromPoints[i];
        var toPoint = toPoints[i];
        var x = fromPoint.X + (toPoint.X - fromPoint.X) * percentage / 100;
        var y = fromPoint.Y + (toPoint.Y - fromPoint.Y) * percentage / 100;
        result.Add(new Point(x, y));
    }
    return result;
}

public static readonly DependencyProperty PointsProperty =
    DependencyProperty.Register("Points", typeof(PointCollection), typeof(ProgressToPointCollectionBridge), new PropertyMetadata(null));

public static readonly DependencyProperty ProgressProperty =
    DependencyProperty.Register("Progress", typeof(double), typeof(ProgressToPointCollectionBridge), new PropertyMetadata(0.0, OnProgressChanged));

private static void OnProgressChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
    var bridge = (ProgressToPointCollectionBridge)d;
    bridge.OnProgressChanged((double)e.OldValue, (double)e.NewValue);
}

public static readonly DependencyProperty ChildrenProperty =
    DependencyProperty.Register("Children", typeof(Collection<PointCollection>), typeof(ProgressToPointCollectionBridge), new PropertyMetadata(null, OnChildrenChanged));

private static void OnChildrenChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
    var bridge = (ProgressToPointCollectionBridge)d;
    bridge.OnChildrenChanged((Collection<PointCollection>)e.OldValue, (Collection<PointCollection>)e.NewValue);
}

}

  1. 结语 如果将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
    ,提供PointCollection以外的数据类型支持。

结合上一篇文章再发散一下,总觉得将来遇到UWP没有提供的功能都可以通过变通的方法实现,Binding和DependencyProperty真是UWP开发者的好朋友。

  1. 参考文献
  • How SVG Shape Morphing Works
  • Gadal MetaSyllabus

热门AI工具

更多
DeepSeek
DeepSeek

幻方量化公司旗下的开源大模型平台

豆包大模型
豆包大模型

字节跳动自主研发的一系列大型语言模型

WorkBuddy
WorkBuddy

腾讯云推出的AI原生桌面智能体工作台

腾讯元宝
腾讯元宝

腾讯混元平台推出的AI助手

文心一言
文心一言

文心一言是百度开发的AI聊天机器人,通过对话可以生成各种形式的内容。

讯飞写作
讯飞写作

基于讯飞星火大模型的AI写作工具,可以快速生成新闻稿件、品宣文案、工作总结、心得体会等各种文文稿

即梦AI
即梦AI

一站式AI创作平台,免费AI图片和视频生成。

ChatGPT
ChatGPT

最最强大的AI聊天机器人程序,ChatGPT不单是聊天机器人,还能进行撰写邮件、视频脚本、文案、翻译、代码等任务。

相关专题

更多
数据类型有哪几种
数据类型有哪几种

数据类型有整型、浮点型、字符型、字符串型、布尔型、数组、结构体和枚举等。本专题为大家提供相关的文章、下载、课程内容,供大家免费下载体验。

338

2023.10.31

php数据类型
php数据类型

本专题整合了php数据类型相关内容,阅读专题下面的文章了解更多详细内容。

225

2025.10.31

c语言 数据类型
c语言 数据类型

本专题整合了c语言数据类型相关内容,阅读专题下面的文章了解更多详细内容。

138

2026.02.12

string转int
string转int

在编程中,我们经常会遇到需要将字符串(str)转换为整数(int)的情况。这可能是因为我们需要对字符串进行数值计算,或者需要将用户输入的字符串转换为整数进行处理。php中文网给大家带来了相关的教程以及文章,欢迎大家前来学习阅读。

1031

2023.08.02

int占多少字节
int占多少字节

int占4个字节,意味着一个int变量可以存储范围在-2,147,483,648到2,147,483,647之间的整数值,在某些情况下也可能是2个字节或8个字节,int是一种常用的数据类型,用于表示整数,需要根据具体情况选择合适的数据类型,以确保程序的正确性和性能。本专题为大家提供相关的文章、下载、课程内容,供大家免费下载体验。

612

2024.08.29

c++怎么把double转成int
c++怎么把double转成int

本专题整合了 c++ double相关教程,阅读专题下面的文章了解更多详细内容。

334

2025.08.29

C++中int的含义
C++中int的含义

本专题整合了C++中int相关内容,阅读专题下面的文章了解更多详细内容。

235

2025.08.29

c++怎么把double转成int
c++怎么把double转成int

本专题整合了 c++ double相关教程,阅读专题下面的文章了解更多详细内容。

334

2025.08.29

Python异步编程与Asyncio高并发应用实践
Python异步编程与Asyncio高并发应用实践

本专题围绕 Python 异步编程模型展开,深入讲解 Asyncio 框架的核心原理与应用实践。内容包括事件循环机制、协程任务调度、异步 IO 处理以及并发任务管理策略。通过构建高并发网络请求与异步数据处理案例,帮助开发者掌握 Python 在高并发场景中的高效开发方法,并提升系统资源利用率与整体运行性能。

37

2026.03.12

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
相关推荐
/
热门推荐
/
最新课程
PostgreSQL 教程
PostgreSQL 教程

共48课时 | 10.6万人学习

Excel 教程
Excel 教程

共162课时 | 21.2万人学习

PHP基础入门课程
PHP基础入门课程

共33课时 | 2.3万人学习

关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号