我是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中这样做。它对图形加速或优化的支持非常有限。
尝试wpf
或uwp
,它具有许多与开箱即用的动画有关的功能。
见Microsoft docs
您也可以寻求一个DirectX
解决方案,但这将是一个过大的杀伤力。
请注意,这些框架通常使用MVVM
模式,其中您有一个Page
及其后面的代码,一个ViewModel
用作数据源,而View
由XAML
组成。
与普通的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>