我是 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
,它有很多关于开箱即用支持的动画的特性。
您也可以选择 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/