WinUI 3 XAML 元素由Windows合成视觉层提供支持。 在 WinUI 3 中,可以使用 UIElement.StartAnimation 直接在 UIElement 实例上运行 CompositionAnimation 对象。 这与 UWP 不同,在 UWP 中,你首先需要使用 ElementCompositionPreview.GetElementVisual 提取底层视觉对象。
通过此互操作,可以将 Spring 动画、表达式动画和其他合成动画类型应用于 WinUI 3 元素。
获取合成器
使用 CompositionTarget.GetCompositorForCurrentThread() 获取当前 XAML UI 线程的 Compositor:
using Microsoft.UI.Composition;
using Microsoft.UI.Xaml.Media;
Compositor compositor = CompositionTarget.GetCompositorForCurrentThread();
从 UI 线程调用此方法。 通过 Compositor 它可创建动画、画笔和效果。
在 UIElement 上运行 Spring 动画
创建一个以 Scale 属性为目标的 SpringVector3NaturalMotionAnimation,然后调用 UIElement.StartAnimation 来运行它:
using System.Numerics;
using Microsoft.UI.Composition;
using Microsoft.UI.Xaml;
using Microsoft.UI.Xaml.Input;
using Microsoft.UI.Xaml.Media;
private readonly Compositor _compositor = CompositionTarget.GetCompositorForCurrentThread();
private SpringVector3NaturalMotionAnimation? _springAnimation;
private SpringVector3NaturalMotionAnimation CreateOrUpdateSpringAnimation(float finalValue)
{
_springAnimation ??= _compositor.CreateSpringVector3Animation();
_springAnimation.Target = "Scale";
_springAnimation.FinalValue = new Vector3(finalValue, finalValue, 1.0f);
return _springAnimation;
}
private void Element_PointerEntered(object sender, PointerRoutedEventArgs e)
{
var springAnimation = CreateOrUpdateSpringAnimation(1.5f);
(sender as UIElement)?.StartAnimation(springAnimation);
}
private void Element_PointerExited(object sender, PointerRoutedEventArgs e)
{
var springAnimation = CreateOrUpdateSpringAnimation(1.0f);
(sender as UIElement)?.StartAnimation(springAnimation);
}
SpringVector3NaturalMotionAnimation 使用弹簧物理效果。 元素可以略微过冲并稳定到位,营造自然的感觉。
调整弹簧行为
通过设置 DampingRatio 和 Period 来控制弹簧行为:
_springAnimation.DampingRatio = 0.6f;
_springAnimation.Period = TimeSpan.FromMilliseconds(50);
DampingRatio |
Effect |
|---|---|
< 1.0 |
欠阻尼。 元素在安定之前会反弹。 |
= 1.0 |
临界阻尼。 元素无过冲地到达目标位置。 |
> 1.0 |
过阻尼。 该元素将更慢地接近目标。 |
使用表达式动画
表达式动画使用数学表达式根据另一个值持续驱动某个属性。 在 WinUI 3 中,可以直接在 UIElement 上启动表达式动画:
using System.Numerics;
using Microsoft.UI.Xaml;
using Microsoft.UI.Xaml.Media;
var compositor = CompositionTarget.GetCompositorForCurrentThread();
var source = compositor.CreatePropertySet();
source.InsertVector3("Offset", new Vector3(40.0f, 0.0f, 0.0f));
var expressionAnimation = compositor.CreateExpressionAnimation("source.Offset");
expressionAnimation.SetReferenceParameter("source", source);
expressionAnimation.Target = "Translation";
myElement.StartAnimation(expressionAnimation);
有关表达式动画的详细信息,请参阅 基于关系的动画。
WinUI 3 和 UWP 差异
在 UWP 中,必须先从元素中提取一个 Visual 元素,然后才能对它运行合成动画:
// UWP pattern
var visual = ElementCompositionPreview.GetElementVisual(myElement);
visual.StartAnimation("Scale", springAnimation);
在 WinUI 3 中,可以直接在 UIElement 上调用 StartAnimation:
// WinUI 3 pattern
myElement.StartAnimation(springAnimation);
打开 WinUI 3 Gallery
WinUI 3 示例库应用包含 WinUI 3 控件和功能的交互式示例。