【问题标题】:Move a line smoothly across the screen在屏幕上平滑移动一条线
【发布时间】:2013-01-28 20:00:25
【问题描述】:

我正在尝试在屏幕上移动一条红线(无卡顿),并且我尝试了各种不同的方法。从 GDI+ 双缓冲(使用 BufferedGraphics 类)到 WPF 的 WriteableBitmap,都失败了。可能是我使用的计时器不够准确,可能是垂直同步撕裂,但这似乎是不可能的。我们现在是 2013 年,我有一个高端 GPU,但我仍然无法重现我的旧 8 位 SNES 没有问题的东西。

是否有人提供 100% 流畅且无闪烁的 WinForms 代码示例,或者如果没有 DirectX,这只是不可能完成的任务?

【问题讨论】:

  • 在 32 Hz 所以每秒 32 个像素

标签: .net wpf winforms graphics gdi+


【解决方案1】:

在 WPF 中,您可以简单地为 Line 控件设置动画。

<Canvas>
    <Line x:Name="line"
        X2="{Binding X1, RelativeSource={RelativeSource Mode=Self}}"
        Y2="{Binding ActualHeight, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=Canvas}}" Stroke="Red" StrokeThickness="4">
    </Line>
</Canvas>

您可以使用如下方法创建和启动动画:

private void StartAnimation()
{
    var animation = new DoubleAnimation
    {
        To = ActualWidth, // width of the window
        Duration = TimeSpan.FromSeconds(ActualWidth / 32),
        RepeatBehavior = RepeatBehavior.Forever
    };

    line.BeginAnimation(Line.X1Property, animation);
}

除了为 Line 的 X1 属性设置动画并让 X2 属性跟随绑定之外,您还可以为 Line 的 RenderTransform 设置动画:

<Canvas>
    <Line Y2="{Binding ActualHeight, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=Canvas}}" Stroke="Red" StrokeThickness="4">
        <Line.RenderTransform>
            <TranslateTransform x:Name="transform"/>
        </Line.RenderTransform>
    </Line>
</Canvas>

StartAnimation 方法现在看起来像这样:

private void StartAnimation()
{
    var animation = new DoubleAnimation
    {
        To = ActualWidth, // width of the window
        Duration = TimeSpan.FromSeconds(ActualWidth / 32),
        RepeatBehavior = RepeatBehavior.Forever
    };

    transform.BeginAnimation(TranslateTransform.XProperty, animation);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-27
    • 1970-01-01
    • 2013-07-11
    • 1970-01-01
    • 2015-09-05
    相关资源
    最近更新 更多