Avalonia 用 C# 实现缩放动画和 System.InvalidCastException: 'Unable to cast object of type 'Avalonia.Media.ScaleTransform' to type 'Avalonia.Visual'.' 的解决方法
Avalonia 用 C# 实现缩放动画和 System.InvalidCastException: 'Unable to cast object of type 'Avalonia.Media.ScaleTransform' to type 'Avalonia.Visual'.' 的解决方法
一、前言
我在 Avalonia 的文档中并没有看到缩放动画的 C# 代码的调用方法。发现用本来的经验会遇到这个错误:
System.InvalidCastException: 'Unable to cast object of type 'Avalonia.Media.ScaleTransform' to type 'Avalonia.Visual'.'
经过研究,我发现在 Avalonia 的代码中是有缩放等相关变换的动画实现的,但是,用法和 WPF 并不一样。
二、正文
实现的效果:

如你所见,当前截图呈现的是一个水平发生了缩放的效果。
我们在 xaml 的部分是这样编写的:
<Button
Name="PART_Button"
Width="200"
Height="200"
Click="Button_Click">
<Button.RenderTransform>
<ScaleTransform ScaleX="0.5" ScaleY="0.5" />
</Button.RenderTransform>
</Button>
对应 C# 是这么实现的:
private void Button_Click(object? sender, Avalonia.Interactivity.RoutedEventArgs e)
{
var button = PART_Button;
var anim = new Animation();
anim.Duration = TimeSpan.FromSeconds(3);
var kf1 = new KeyFrame()
{
Cue = new Cue(0),
};
kf1.Setters.Add(new Setter(ScaleTransform.ScaleXProperty, 0d));
var kf2 = new KeyFrame()
{
Cue = new Cue(1),
};
kf2.Setters.Add(new Setter(ScaleTransform.ScaleXProperty, 1d));
anim.Children.AddRange([kf1,kf2]);
anim.RunAsync(button);
}
三、划重点
在 anim.RunAsync() 中不要传 ScaleTransform 实例,参数请传控件本身,比如示例中的按钮控件button 本身。

浙公网安备 33010602011771号