gpt4 book ai didi

c# - WPF:从代码动画化 TranslateTransform

转载 作者:可可西里 更新时间:2023-11-01 03:04:17 26 4
gpt4 key购买 nike

我有一个 WPF Canvas ,我在上面通过代码动态创建对象。这些对象正在通过设置 RenderTransform 属性进行转换,并且需要应用这些转换之一的动画。目前,我无法获取任何转换的属性以进行动画处理(尽管没有引发异常并且动画似乎在运行 - 已引发完成的事件)。

此外,如果动画系统受到压力,有时 Storyboard.Completed 事件永远不会引发。

我遇到的所有示例都对 XAML 的转换进行动画处理。 MSDN documentation建议必须将转换的 x:Name 属性设置为可动画化,但我还没有找到从代码中设置它的有效方法。

有什么想法吗?

这是重现问题的完整代码 list :

using System;
using System.Diagnostics;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace AnimationCompletedTest {
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window {

Canvas panel;
public MainWindow() {
InitializeComponent();
MouseDown += DoDynamicAnimation;

Content = panel = new Canvas();
}

void DoDynamicAnimation(object sender, MouseButtonEventArgs args) {

for (int i = 0; i < 12; ++i) {
var e = new Ellipse {
Width = 16,
Height = 16,
Fill = SystemColors.HighlightBrush
};
Canvas.SetLeft(e, Mouse.GetPosition(this).X);
Canvas.SetTop(e, Mouse.GetPosition(this).Y);

var tg = new TransformGroup();
var translation = new TranslateTransform(30, 0);
tg.Children.Add(translation);
tg.Children.Add(new RotateTransform(i * 30));
e.RenderTransform = tg;

panel.Children.Add(e);

var s = new Storyboard();
Storyboard.SetTarget(s, translation);
Storyboard.SetTargetProperty(s, new PropertyPath(TranslateTransform.XProperty));

s.Children.Add(
new DoubleAnimation(3, 100, new Duration(new TimeSpan(0, 0, 0, 1, 0))) {
EasingFunction = new PowerEase {EasingMode = EasingMode.EaseOut}
});

s.Completed +=
(sndr, evtArgs) => {
Debug.WriteLine("Animation {0} completed {1}", s.GetHashCode(), Stopwatch.GetTimestamp());
panel.Children.Remove(e);
};

Debug.WriteLine("Animation {0} started {1}", s.GetHashCode(), Stopwatch.GetTimestamp());

s.Begin();
}
}

[STAThread]
public static void Main() {
var app = new Application();
app.Run(new MainWindow());
}
}
}

最佳答案

省略 Storyboard:

var T = new TranslateTransform(40, 0);
Duration duration = new Duration(new TimeSpan(0, 0, 0, 1, 0));
DoubleAnimation anim = new DoubleAnimation(30, duration);
T.BeginAnimation(TranslateTransform.YProperty, anim);

(语法的小修正)

关于c# - WPF:从代码动画化 TranslateTransform,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2841124/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com