You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

WPF中RotateTransform动画时长失效问题求助

WPF RotateTransform动画无平滑过渡的解决方法

问题根源

你的代码中动画时长设置错误:使用了TimeSpan.FromMicroseconds(250),250微秒仅等于0.25毫秒,这个时长极短,肉眼完全无法感知平滑过渡,看起来就是直接跳转到目标角度。

修正方案

  1. 修正动画时长单位:将TimeSpan.FromMicroseconds(250)改为TimeSpan.FromMilliseconds(250),设置正确的250毫秒动画时长。
  2. 优化状态判断逻辑:直接依赖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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.26 21:47:13