Create storyboard and doubleanimation
本文关键字:doubleanimation and storyboard Create | 更新日期: 2023-09-27 18:09:33
我正在WPF上制作游戏SizzlingHot。我有一个画布,用来加载水果掉落的图像。当我点击startButton的时候,它应该会创建一个带有doubleAnimation的storyboard来显示掉落的水果。我在方法中有以下代码:
NameScope.SetNameScope(this, new NameScope());
Cherry cherry = new Cherry(); // I get the image from this class
// GameCanvas.Children.Add(cherry.FruitImage); // idk if this should be here and its invalid because the parameter in the parantheses shoud be UI element it does not allow BitmapImage
DoubleAnimation myDoubleAnimation = new DoubleAnimation(100, 500, new Duration(TimeSpan.FromSeconds(5)));
myDoubleAnimation.From = -150;
myDoubleAnimation.To = 500;
Storyboard.SetTargetProperty(myDoubleAnimation, new PropertyPath("(Canvas.Top)"));
Storyboard.SetTarget(myDoubleAnimation, cherry.FruitImage);
Storyboard myStoryboard = new Storyboard();
myStoryboard.Children.Add(myDoubleAnimation);
GameCanvas.Resources.Add(myStoryboard,cherry.FruitImage);
myStoryboard.Begin(this, true);
当我运行这个时,在最后一行,它给了我一个
InvalidOperationException -由于对象的当前阶段,操作无效。
我不明白这里有什么问题,当我调试它时,我可以看到图像被找到。
只能将UIElement
添加到Canvas
中,不能将BitmapImage
直接添加到Canvas
中
一个选项可以是添加一个动态的Image
,并将Source
设置为FruitImage
,然后您可以在GameCanvas
上动画/定位Image
的例子:
Cherry cherry = new Cherry();
// Create host for BitmapImage
Image imageHost = new Image { Source = cherry.FruitImage };
GameCanvas.Children.Add(imageHost);
// Animate Image
imageHost.BeginAnimation(Canvas.TopProperty, new DoubleAnimation(-150, 500, new Duration(TimeSpan.FromSeconds(5))));
尝试在您的图像上这样做,如果您还没有:
image.BeginInit();
image.UriSource = new Uri(filename, UriKind.Relative);
image.EndInit();
cherryImage.Source = image;
如果cherry.FruitImage
是一个图像,你可以简单地像这样动画它:
cherry.FruitImage.BeginAnimation(
Canvas.TopProperty,
new DoubleAnimation(-150, 500, TimeSpan.FromSeconds(5)));
不需要故事板