在Avalonia,如何在关键帧动画中开始和停止
private Animation StartAnimation(Control control)
{
Animation animation = new Animation();
animation.Duration = TimeSpan.FromMilliseconds(1000);
animation.IterationCount = new IterationCount(2);
KeyFrame key1 = new KeyFrame();
key1.KeyTime = TimeSpan.FromMilliseconds(500);
key1.Setters.Add(new Avalonia.Styling.Setter(WidthProperty, 50 + 10d));
key1.Setters.Add(new Avalonia.Styling.Setter(HeightProperty, 50 + 10d));
key1.Setters.Add(new Avalonia.Styling.Setter(OpacityProperty, 1));
animation.Children.Add(key1);
return animation;
}发布于 2022-11-25 05:59:31
抱歉反应晚了..。
在Avalonia,如何在关键帧动画中开始和停止
假设您只对关键帧感兴趣,因为您可以将代码隐藏与XAML标记混合在一起,我可以想出两种方法,下面是示例代码的完整示例,我注释了一些更改/错误,所以您仍然可以复制粘贴它。
A) 背后的代码
public class FooControl : TemplatedControl
{
// assuming you derived from a TemplatedControl since you used
// WidthProperty etc.
private FooControl @this = null;
private CancellationToken _cancelToken;
private CancellationTokenSource _cancelTokenSource;
private Clock _animationClock = null;
private Animation _animation = null;
public FooControl()
{
@this = this; // for Async calls with 'this' as parameter
_animationClock = new Clock();
_cancelTokenSource = new CancellationTokenSource();
_cancelToken= _cancelTokenSource.Token;
_animation = CreateAnimation();
}
// I changed your 'StartAnimation(..)' to 'CreateAnimation()'
// Also you didn't use/need the parameter 'control'
// !!!
// Important: You always need at least two Keyframes!
// The animation-system tries to interpolate between the source-
// and destination-values of a setter-property of two adjacent
// keyframes
private Animation CreateAnimation()
{
_animation = new Animation();
_animation.Duration = TimeSpan.FromMilliseconds(1000);
_animation.IterationCount = new IterationCount(2);
KeyFrame key0 = new KeyFrame();
key0.KeyTime = TimeSpan.FromMilliseconds(0);
key0.Setters.Add(new Avalonia.Styling.Setter(WidthProperty, 0));
key1.Setters.Add(new Avalonia.Styling.Setter(HeightProperty, 0));
key1.Setters.Add(new Avalonia.Styling.Setter(OpacityProperty, 0));
KeyFrame key1 = new KeyFrame();
key1.KeyTime = TimeSpan.FromMilliseconds(500);
key1.Setters.Add(new Avalonia.Styling.Setter(WidthProperty,50+10));
key1.Setters.Add(new Avalonia.Styling.Setter(HeightProperty,60));
key1.Setters.Add(new Avalonia.Styling.Setter(OpacityProperty,1));
_animation.Children.Add(key1);
return animation;
}
private async Task RunAnimation()
{
await _scrollingAnimation?.RunAsync(_scrollingStackPanel,_playbackClock);
}
private void StopAnimation()
{
_cancelTokenSource.Cancel();
}
}有关取消令牌,请参阅这
B)使用XAML/标记
将动画添加到XAML中的样式,并给该样式一个选择器。使用
哪些使用可以激活/禁用样式和动画。常见的是使用自定义伪类。通过添加或删除当前设置的伪类,您还将触发/取消动画。
方法来设置/删除伪类(静态调用):
Pseudoclasses.Set(“:伪类名”,bool isSet);
这可以与后面的代码混合使用。如果有人要求,我可以为XAML版本添加完整的示例源代码。
https://stackoverflow.com/questions/71879258
复制相似问题