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

爱谁谁
发布: 2025-08-28 10:46:14
原创
1005人浏览过

上一篇文章主要介绍了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处于其中任何值时的计算方法如下:

AppMall应用商店
AppMall应用商店

AI应用商店,提供即时交付、按需付费的人工智能应用服务

AppMall应用商店 56
查看详情 AppMall应用商店
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;"><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

以上就是[UWP]用Shape做动画(2):使用与扩展PointAnimation的详细内容,更多请关注php中文网其它相关文章!

最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

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