如何旋转图像,使其看起来像在 C# UWP 中浮动?

How to rotate a image so that it seems like it's floating in C# UWP?

我在XAML中添加了一张图片,想连续随机旋转它,让它看起来像在漂浮。
这是我已经尝试过的代码。

XAML

<Image Source="Assets\balloon-red.png"
           x:Name="redBaloon"
           Width="300"
           Stretch="Uniform"
           Height="Auto"
           Margin="490,124,490,-124" /> 

C#

public MainPage()  
{
    this.InitializeComponent();  
    Loaded += MainPage_Loaded;  
    Random randRotate = new Random();  
    RotateTransform imageRotate = new RotateTransform();  
    redBaloon.RenderTransform = imageRotate;  
    imageRotate.Angle = randRotate.Next(-5,5);  
}

只转一圈。但我希望它不断旋转。我怎样才能做到这一点?我想我必须在主 class 之外编写代码,但我不知道正确的方法。请帮帮我。

要连续重复旋转,您可以使用 DispatcherTimer。

public MainPage() {
        this.InitializeComponent();
        StartTimers();
    }

    DispatcherTimer dispatcherTimer;
    public void StartTimers() {
        dispatcherTimer = new DispatcherTimer();
        dispatcherTimer.Tick += dispatcherTimer_Tick;
        dispatcherTimer.Interval = new TimeSpan(0, 0, 1);
        dispatcherTimer.Start();
    }

    // callback runs on UI thread
    void dispatcherTimer_Tick(object sender, object e) {
        // execute repeating task here
        Random randRotate = new Random();
        RotateTransform imageRotate = new RotateTransform();
        redBaloon.RenderTransform = imageRotate;
        imageRotate.Angle = randRotate.Next(-5, 5);
    }

以上代码重复了Tick内部定义的操作。

有关此内容的更多详细信息,请查看此处 DispatcherTimer