WPF中RotateTransform动画时长失效问题求助
WPF RotateTransform动画无平滑过渡的解决方法
问题根源
你的代码中动画时长设置错误:使用了TimeSpan.FromMicroseconds(250),250微秒仅等于0.25毫秒,这个时长极短,肉眼完全无法感知平滑过渡,看起来就是直接跳转到目标角度。
修正方案
- 修正动画时长单位:将
TimeSpan.FromMicroseconds(250)改为TimeSpan.FromMilliseconds(250),设置正确的250毫秒动画时长。 - 优化状态判断逻辑:直接依赖
RotateTransform.Angle判断状态存在隐患——动画运行中Angle是动态变化的,且可能因浮点精度问题无法精确等于0或180。改用布尔变量跟踪当前旋转状态更可靠。
修正后的后台代码
public partial class MainWindow : Window { RotateTransform testButtonRotateTransform; private bool isRotated = false; // 记录当前旋转状态 public MainWindow() { InitializeComponent(); TransformGroup transformGroup = new TransformGroup(); ScaleTransform scaleTransform = new ScaleTransform(0.8, 0.8); testButtonRotateTransform = new RotateTransform(0); transformGroup.Children.Add(scaleTransform); transformGroup.Children.Add(testButtonRotateTransform); testButton.RenderTransformOrigin = new Point(0.5, 0.5); testButton.RenderTransform = transformGroup; } private void Button_Click(object sender, RoutedEventArgs e) { double targetAngle = isRotated ? 0 : 180; DoubleAnimation angleRotationAnimation = new DoubleAnimation( testButtonRotateTransform.Angle, targetAngle, new Duration(TimeSpan.FromMilliseconds(250))); testButtonRotateTransform.BeginAnimation(RotateTransform.AngleProperty, angleRotationAnimation); isRotated = !isRotated; } }
额外说明
- 动画的
From参数直接使用当前testButtonRotateTransform.Angle,即使在动画未完成时点击按钮,也能从当前角度平滑切换到目标角度,提升交互流畅性。 - 保持
RenderTransformOrigin设置为(0.5, 0.5),确保按钮以自身中心为旋转轴,符合预期效果。
内容的提问来源于stack exchange,提问作者LKeene
相关产品推荐
相关产品推荐

