XAML 與 Composition 的互通性

WinUI 3 的 XAML 元素由 Windows Composition 視覺圖層支援。 在 WinUI 3 中,你可以使用 UIElement.StartAnimation 直接在 UIElement 執行個體上執行 CompositionAnimation 物件。 這和 UWP 不同,UWP 需要先用 ElementCompositionPreview.GetElementVisual來擷取底層視覺圖。

這種互通性讓你能將彈簧動畫、表情動畫及其他合成動畫類型套用到 WinUI 3 元素。

去找合成器

使用 CompositionTarget.GetCompositorForCurrentThread() 以取得目前 XAML UI 執行緒的 Compositor

using Microsoft.UI.Composition;
using Microsoft.UI.Xaml.Media;

Compositor compositor = CompositionTarget.GetCompositorForCurrentThread();

從 UI 執行緒呼叫這個方法。 它 Compositor 讓你可以製作動畫、畫筆和特效。

在 UIElement 上執行彈簧動畫

建立一個以 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 使用彈簧物理效果。 這個元素有時會稍微超出,然後穩定下來,營造出自然的感覺。

調整彈簧效果

透過設定 DampingRatioPeriod控制彈簧行為:

_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,才能對其執行 Composition 動畫:

// UWP pattern
var visual = ElementCompositionPreview.GetElementVisual(myElement);
visual.StartAnimation("Scale", springAnimation);

在 WinUI 3 中,您可以直接在 UIElement 上呼叫 StartAnimation

// WinUI 3 pattern
myElement.StartAnimation(springAnimation);

WinUI 3 圖庫應用程式包含 WinUI 3 控制項與功能的互動範例。