c# - 为什么移动矩形不一致?

标签 c# .net winforms

我是 C# 的新手,我正在尝试制作一个允许使用输入移动矩形的简单程序。问题是在 C# 中更新矩形的位置时,矩形有时看起来会消失很短的时间,然后重新出现在它的新位置,而不是持续移动。

我用 p5.js 做过类似的事情和 java (Jswing)。

这是我写的代码

 public class WinFormsTest : Form
{
    System.Windows.Forms.Timer timer;
    Graphics graphics;
    Brush brush;
    Rectangle rect = new Rectangle(0, 0, 80, 80);

    public WinFormsTest()
    {
       Draw();
    }

    public void Draw()
    {
        Text = "HelloWold";
        Height = 800;
        Width = 800;

        timer = new System.Windows.Forms.Timer();
        timer.Interval = 1;
        timer.Tick += new EventHandler(timer_Tick);
        Invalidate();
        timer.Start();

    }
    private void timer_Tick(object sender, EventArgs e)
    {
        graphics = CreateGraphics();
        brush = new SolidBrush(Color.Green);
        graphics.Clear(Color.White);
        Random rnd = new Random();
        graphics.FillRectangle(brush, rect);
        rect.X++;
        rect.Y++;

    }

    public static void Main(string[] args)
    {
        Application.Run(new WinFormsTest());
    }
}

我希望矩形始终移动而不会有时消失和重新出现。

最佳答案

不要在 winforms 中这样做。它对图形加速或优化的支持非常有限。

试试 wpfuwp ,它有很多关于开箱即用支持的动画的特性。

参见 Microsoft docs

您也可以选择 DirectX 解决方案,但那会更加矫枉过正。

请注意,这些框架通常使用 MVVM 模式,其中您有一个带有代码的 Page,一个 ViewModel 来执行作为数据源和由 XAML 组成的 View

这比普通的旧 WinForms 更难处理,但如果您正在学习,并且真的想构建外观漂亮的应用程序,那绝对是正确的选择。


WPF 动画带有很多基类/帮助类,可以看出 here

这是一个示例,纯 XAML:

<!-- just a container -->
<Canvas Background="Orange"> 
    <-- a canvas to apply the animation on -->
    <Canvas  x:Name="target" Background="Green"> 
        <!-- your rectangle -->
        <Rectangle Width="200" Height="100" Fill="Blue" Stroke="Black" StrokeThickness="4"/>
         <!-- the animation trigger -->
        <Canvas.Triggers>
            <EventTrigger RoutedEvent="FrameworkElement.Loaded">
                <BeginStoryboard>
                    <Storyboard RepeatBehavior="Forever" AutoReverse="True">
                          <DoubleAnimation Storyboard.TargetName="target" 
                                           Storyboard.TargetProperty="Left"
                                           From="0" To="100" 
                                           Duration="0:0:3"/>
                     </Storyboard>
                 </BeginStoryboard>
             </EventTrigger>
         </Canvas.Triggers>
    </Canvas>
</Canvas>

关于c# - 为什么移动矩形不一致?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56692419/

相关文章:

c# - 如何在 C# 中将字符串的内容复制到剪贴板?

.net - 为什么在绑定(bind)到它时没有设置我的依赖属性?

c# - 如何在 SelectedIndexChanged 事件之前检测 TabControl 中标签页的变化?

c# - 表达式定义说明

c# - 如何在 AboutBox 的描述字段内显示超链接

c# - 无需授权或用户登录即可保护 webapi 2

c# - 如何获取 Windows 窗体在屏幕上的位置?

c# - 如何向ffmpeg提供登录用户名和密码?

c# Activator.CreateInstance 不初始化变量

winforms - 如何使用 OpenFileDialog 选择多个文件?