【发布时间】:2020-05-29 00:59:47
【问题描述】:
我一直在尝试为 Wpf 的游戏制作动画序列。作为 WPF 的新手,我没有找到有效的 XAML 答案。我设法拼凑了一些 C# 代码,它可以工作,但后来我发现我无法更改图像源。我在互联网上进行了很多搜索,尝试了更改缓存等操作,但没有任何效果。
在下面的代码中,标记为“忽略此赋值”的语句就是这样。没有异常或其他错误,只是单步执行它表明任务没有被兑现。我在搜索相关主题时确实找到了答案(我将在回答帖子中给出),但我想发布这个以希望其他开发人员对这个问题以及如何制作 WPF 图像动画有很多挫败感的爆炸。 实际的图片无关紧要,使用任何你想要的。
XAML
<StackPanel Background="#333333">
<Button x:Name="boomButton" HorizontalAlignment="Center"
FontSize="24" VerticalAlignment="Bottom" Click="boomButton_Click" >BOOM</Button>
<Button x:Name="resetButton" HorizontalAlignment="Center"
FontSize="24" VerticalAlignment="Bottom" Click="resetButton_Click" >Reset</Button>
<Image x:Name="bmb" Source="Images\bomberbase.png" Stretch="None" />
</StackPanel>
C# 后端代码
public partial class MainWindow : Window
{
public static BitmapImage mBoom1Img, mBoom2Img, mBoom3Img;
public static BitmapImage mBomberImg, mBlankImg;
public static BitmapImage mUnknownEnhancementImg, mAirfieldCraterImg;
public MainWindow()
{
InitializeComponent();
mBoom1Img = BitmapImageFromSource("Images/boom1.png");
mBoom2Img = BitmapImageFromSource("Images/boom2.png");
mBoom3Img = BitmapImageFromSource("Images/boom3.png");
mBomberImg = BitmapImageFromSource("Images/bomberbase.png");
mBlankImg = BitmapImageFromSource("Images/blank.png");
mUnknownEnhancementImg = BitmapImageFromSource("Images/unknownEnhancement.png");
mAirfieldCraterImg = BitmapImageFromSource("Images/airfieldCrater.png");
}
public static BitmapImage BitmapImageFromSource(string aRelPath)
{
BitmapImage bi3 = new BitmapImage();
bi3.BeginInit();
bi3.UriSource = new Uri(aRelPath, UriKind.Relative);
bi3.EndInit();
return bi3;
}
private void resetButton_Click(object sender, RoutedEventArgs e)
{
bmb.Source = mUnknownEnhancementImg; // This assignment ignored
}
private void boomButton_Click(object sender, RoutedEventArgs e)
{
ObjectAnimationUsingKeyFrames animation = new ObjectAnimationUsingKeyFrames();
animation.BeginTime = TimeSpan.FromSeconds(0);
animation.Duration = new TimeSpan(0, 0, 0, 3, 0);
DiscreteObjectKeyFrame fbmb = new DiscreteObjectKeyFrame(mBomberImg, TimeSpan.FromMilliseconds(0));
animation.KeyFrames.Add(fbmb);
DiscreteObjectKeyFrame f1 = new DiscreteObjectKeyFrame(mBoom1Img, TimeSpan.FromMilliseconds(200));
animation.KeyFrames.Add(f1);
DiscreteObjectKeyFrame f2 = new DiscreteObjectKeyFrame(mBoom2Img, TimeSpan.FromMilliseconds(400));
animation.KeyFrames.Add(f2);
DiscreteObjectKeyFrame f3 = new DiscreteObjectKeyFrame(mBoom3Img, TimeSpan.FromMilliseconds(600));
animation.KeyFrames.Add(f3);
DiscreteObjectKeyFrame f4 = new DiscreteObjectKeyFrame(mBlankImg, TimeSpan.FromMilliseconds(1000));
animation.KeyFrames.Add(f4);
animation.Completed += new EventHandler(animation_Complete);
bmb.BeginAnimation(Image.SourceProperty, animation);
}
private void animation_Complete(object sender, EventArgs e)
{
// This unlocks the animation's hold on the property!
//bmb.BeginAnimation(Image.SourceProperty, null);
bmb.Source = mAirfieldCraterImg; // This assignment ignored
}
}
【问题讨论】: